text:
package org.wso2.carbon.identity.governance.store;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.governance.internal.cache.IdentityDataStoreCache;
import org.wso2.carbon.identity.governance.internal.cache.IdentityDataStoreCacheKey;
import org.wso2.carbon.identity.governance.model.UserIdentityClaim;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.util.UserCoreUtil;

import java.util.Locale;
import java.util.Map;

/**
 *
 */
public class InMemoryIdentityDataStore extends UserIdentityDataStore {

    private static final Log log = LogFactory.getLog(InMemoryIdentityDataStore.class);
    private final IdentityDataStoreCache identityDataStoreCache = IdentityDataStoreCache.getInstance();

    @Override
    public void store(UserIdentityClaim userIdentityDTO, UserStoreManager userStoreManager)
            throws IdentityException {

        try {
            if (userIdentityDTO != null && userIdentityDTO.getUserName() != null) {
                String userName = UserCoreUtil.removeDomainFromName(userIdentityDTO.getUserName());
                if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
                    if (!IdentityUtil.isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager)
                            userStoreManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Case insensitive user store found. Changing username from : " + userName +
                                    " to : " + userName.toLowerCase(Locale.ENGLISH));
                        }
                        userName = userName.toLowerCase(Locale.ENGLISH);
                    } else if (!IdentityUtil.isUseCaseSensitiveUsernameForCacheKeys(
                            (org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Case insensitive username for cache key is used. Changing username from : "
                                    + userName + " to : " + userName.toLowerCase(Locale.ENGLISH));
                        }
                        userName = userName.toLowerCase(Locale.ENGLISH);
                    }
                }

                if (log.isDebugEnabled()) {
                    StringBuilder data = new StringBuilder("{");
                    if (userIdentityDTO.getUserIdentityDataMap() != null) {
                        for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap().entrySet()) {
                            data.append("[").append(entry.getKey()).append(" = ").append(entry.getValue()).append("], ");
                        }
                    }
                    if (data.indexOf(",") >= 0) {
                        data.deleteCharAt(data.lastIndexOf(","));
                    }
                    data.append("}");
                    log.debug("Storing UserIdentityClaimsDO to cache for user: " + userName + " with claims: " + data);
                }

                org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;
                String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

                IdentityDataStoreCacheKey key = new IdentityDataStoreCacheKey(domainName, userName);
                int tenantId = userStoreManager.getTenantId();
                UserIdentityClaim cachedUserIdentityDTO = identityDataStoreCache.getValueFromCache(key, tenantId);
                if (cachedUserIdentityDTO != null) {
                    cachedUserIdentityDTO.getUserIdentityDataMap().putAll(userIdentityDTO.getUserIdentityDataMap());
                    identityDataStoreCache.addToCache(key, cachedUserIdentityDTO, tenantId);
                } else {
                    identityDataStoreCache.addToCache(key, userIdentityDTO, tenantId);
                }
            }
        } catch (UserStoreException e) {
            log.error("Error while obtaining tenant ID from user store manager", e);
        }
    }

    @Override
    public UserIdentityClaim load(String userName, UserStoreManager userStoreManager) {

        try {
            if (userName != null) {
                userName = UserCoreUtil.removeDomainFromName(userName);
                if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
                    if (!IdentityUtil.isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager)
                            userStoreManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Case insensitive user store found. Changing username from : " + userName +
                                    " to : " + userName.toLowerCase(Locale.ENGLISH));
                        }
                        userName = userName.toLowerCase(Locale.ENGLISH);
                    } else if (!IdentityUtil.isUseCaseSensitiveUsernameForCacheKeys(
                            (org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Case insensitive username for cache key is used. Changing username from : "
                                    + userName + " to : " + userName.toLowerCase(Locale.ENGLISH));
                        }
                        userName = userName.toLowerCase(Locale.ENGLISH);
                    }
                }

                org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;

                String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

                IdentityDataStoreCacheKey key = new IdentityDataStoreCacheKey(domainName, userName);
                int tenantId = userStoreManager.getTenantId();
                UserIdentityClaim userIdentityDTO = identityDataStoreCache.getValueFromCache(key, tenantId);

                if (userIdentityDTO != null && log.isDebugEnabled()) {
                    StringBuilder data = new StringBuilder("{");
                    if (userIdentityDTO.getUserIdentityDataMap() != null) {
                        for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap().entrySet()) {
                            data.append("[").append(entry.getKey()).append(" = ").append(entry.getValue())
                                    .append("], ");
                        }
                    }
                    if (data.indexOf(",") >= 0) {
                        data.deleteCharAt(data.lastIndexOf(","));
                    }
                    data.append("}");
                    log.debug("Loaded UserIdentityClaimsDO from cache for user :" + userName + " with claims: " + data);

                }
                return userIdentityDTO;
            }
        } catch (UserStoreException e) {
            log.error("Error while obtaining tenant ID from user store manager");
        }
        return null;
    }

    @Override
    public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException {

        try {
            if (userName == null) {
                return;
            }
            userName = UserCoreUtil.removeDomainFromName(userName);
            if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
                if (!IdentityUtil.isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager)
                        userStoreManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Case insensitive user store found. Changing username from : " + userName + " to : " +
                                userName.toLowerCase(Locale.ENGLISH));
                    }
                    userName = userName.toLowerCase(Locale.ENGLISH);
                } else if (!IdentityUtil.isUseCaseSensitiveUsernameForCacheKeys(
                        (org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Case insensitive username for cache key is used. Changing username from : "
                                + userName + " to : " + userName.toLowerCase(Locale.ENGLISH));
                    }
                    userName = userName.toLowerCase(Locale.ENGLISH);
                }
            }
            org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager)
                    userStoreManager;
            String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                    .PROPERTY_DOMAIN_NAME);

            IdentityDataStoreCacheKey key = new IdentityDataStoreCacheKey(domainName, userName);
            identityDataStoreCache.clearCacheEntry(key, userStoreManager.getTenantId());
        } catch (UserStoreException e) {
            log.error("Error while obtaining tenant ID from user store manager");
        }
    }

}


text:
package pub.pjoc.util.reflect;

import org.junit.Assert;
import org.junit.Test;

import java.util.Map;

/**
 * @author xiongyingqi
 * @since 16-11-30 下午7:44
 */
public class ReflectionUtilsTest {
  @Test
  public void convertObjectFieldsToMap() throws Exception {
    Pojo pojo = new Pojo();
    Map<String, String> map = ReflectionUtils.convertObjectFieldsToMap(pojo);
    Assert.assertNotNull(map);
    Assert.assertNull(map.get("a"));
    Assert.assertNull(map.get("b"));

    Pojo pojo2 = new Pojo();
    pojo2.a = "a";
    pojo2.b = "b";
    Map<String, String> map2 = ReflectionUtils.convertObjectFieldsToMap(pojo2);
    Assert.assertNotNull(map2);
    Assert.assertNotNull(map2.get("a"));
    Assert.assertNotNull(map2.get("b"));

    Map<String, String> map3 = ReflectionUtils.convertObjectFieldsToMap(pojo2, SuperPojo.class);
    Assert.assertNotNull(map3);
    Assert.assertTrue(map3.containsKey("c"));
    Assert.assertNull(map3.get("c"));
  }

  static class Pojo extends SuperPojo {
    private String a;
    private String b;
  }

  static class SuperPojo {
    private String c;
  }

}

redpajama_set_name: RedPajamaGithub


text:
const path = require('path')
const os = require('os')
const process = require('process')
const handlebars = require('handlebars')

const getType = obj => {
  if ((obj.type || {}).name === 'custom') {
    return { name: obj.type.raw }
  }

  return obj.type && typeof obj.type.name === 'string'
    ? obj.type
    : typeof obj.name === 'string' ? obj : undefined
}

const defaultPropBody = text => {
  const lines = text.split(/\r\n|\r|\n/g)
  return new handlebars.SafeString(
    lines.length > 1 ? ` \n\`\`\`js\n${text}\n\`\`\`` : `\`${text}\``
  )
}

handlebars.registerPartial('Unknown', 'Unknown')

handlebars.registerPartial('func', 'Function')
handlebars.registerPartial('array', 'Array')
handlebars.registerPartial('object', 'Object')
handlebars.registerPartial('string', 'String')
handlebars.registerPartial('number', 'Number')
handlebars.registerPartial('bool', 'Boolean')
handlebars.registerPartial('node', 'ReactNode')
handlebars.registerPartial('element', 'ReactElement')
handlebars.registerPartial('any', '*')
handlebars.registerPartial('custom', 'custom')
handlebars.registerPartial('shape', 'Shape')
handlebars.registerPartial('ViewPropTypes.style', 'ViewPropTypes.style')
handlebars.registerPartial('Text.propTypes.style', 'Text.propTypes.style')

handlebars.registerPartial(
  'arrayOf',
  'Array[]<{{#with (typeObject this)}}{{> (typePartial value) value}}{{/with}}>'
)
handlebars.registerPartial(
  'objectOf',
  'Object[#]<{{#with (typeObject this)}}{{> (typePartial value) value}}{{/with}}>'
)
handlebars.registerPartial(
  'instanceOf',
  '{{#with (typeObject this)}}{{value}}{{/with}}'
)
handlebars.registerPartial(
  'enum',
  'Enum({{#with (typeObject this)}}{{#each value}}{{{this.value}}}{{#unless @last}},{{/unless}}{{/each}}{{/with}})'
)
handlebars.registerPartial(
  'union',
  'Union<{{#with (typeObject this)}}{{#each value}}{{> (typePartial this) this}}{{#unless @last}} | {{/unless}}{{/each}}{{/with}}>'
)

handlebars.registerHelper('typeObject', getType)
handlebars.registerHelper('defaultPropBody', defaultPropBody)

handlebars.registerHelper('typePartial', function(type) {
  const partials = [
    'any',
    'array',
    'arrayOf',
    'bool',
    'custom',
    'element',
    'enum',
    'func',
    'node',
    'number',
    'object',
    'string',
    'union',
    'instanceOf',
    'objectOf',
    'shape',
    'ViewPropTypes.style',
    'Text.propTypes.style'
  ]
  const typeObj = getType(type)
  return typeObj && partials.includes(typeObj.name) ? typeObj.name : 'Unknown'
})

const defaultTemplate = `
## {{componentName}}

{{#if srcLink }}From [\`{{srcLink}}\`]({{srcLink}}){{/if}}

{{#if description}}{{{description}}}{{/if}}

prop | type | default | required | description
---- | :----: | :-------: | :--------: | -----------
{{#each props}}
**{{@key}}** | \`{{> (typePartial this) this}}\` | {{#if this.defaultValue}}\`{{{this.defaultValue}}}\`{{/if}} | {{#if this.required}}:white_check_mark:{{else}}:x:{{/if}} | {{#if this.description}}{{{this.description}}}{{/if}}
{{/each}}

{{#if isMissingComposes}}
*Some or all of the composed components are missing from the list below because a documentation couldn't be generated for them.
See the source code of the component for more information.*
{{/if}}

{{#if composes.length}}
{{componentName}} gets more \`propTypes\` from these composed components
{{/if}}

{{#each composes}}
#### {{this.componentName}}

prop | type | default | required | description
---- | :----: | :-------: | :--------: | -----------
{{#each this.props}}
**{{@key}}** | \`{{> (typePartial this) this}}\` | {{#if this.defaultValue}}\`{{{this.defaultValue}}}\`{{/if}} | {{#if this.required}}:white_check_mark:{{else}}:x:{{/if}} | {{#if this.description}}{{{this.description}}}{{/if}}
{{/each}}

{{/each}}
`

let typeFlatteners = {}

const replaceNewLine = value => value.replace(new RegExp(os.EOL, 'g'), ' ')
const normalizeValue = (value, hasInnerValue) =>
  value ? (hasInnerValue ? value.value : value) : value

const flattenProp = (seed, currentObj, name, isImmediateNesting) => {
  const typeObject = getType(currentObj)

  if (typeObject) {
    const flattener = typeFlatteners[typeObject.name] || (() => {})
    flattener(seed, typeObject, name)
  }

  if (!isImmediateNesting) {
    seed[name] = Object.assign({}, currentObj, {
      description: normalizeValue(currentObj.description, false),
      defaultValue: normalizeValue(currentObj.defaultValue, true)
    })
  }
}

typeFlatteners = {
  arrayOf(seed, arrayType, name) {
    flattenProp(seed, arrayType.value, name + '[]', true)
  },
  shape(seed, shapeType, name) {
    Object.keys(shapeType.value).forEach(inner => {
      flattenProp(seed, shapeType.value[inner], name + '.' + inner)
    })
  },
  objectOf(seed, objectOfType, name) {
    flattenProp(seed, objectOfType.value, name + '[#]', true)
  }
}

const flattenProps = props => {
  const sortedProps = {}
  if (props) {
    const flattenedProps = Object.keys(props).reduce((seed, prop) => {
      flattenProp(seed, props[prop], prop)
      return seed
    }, {})

    Object.keys(flattenedProps)
      .sort()
      .forEach(key => {
        sortedProps[key] = flattenedProps[key]
      })
  }

  return sortedProps
}

class ReactDocGenMarkdownRenderer {
  constructor(options) {
    this.options = Object.assign(
      {
        componentsBasePath: process.cwd(),
        template: defaultTemplate
      },
      options
    )

    this.template = handlebars.compile(this.options.template)
    this.extension = '.md'
  }

  render(file, docs, composes) {
    const componentName = path.basename(file, path.extname(file))

    const sortedProps = flattenProps(docs.props)

    const composesFlattened = []
    if (composes.length !== 0) {
      composes.forEach(compose => {
        composesFlattened.push({
          srcLink: compose.file.replace(
            this.options.componentsBasePath + '/',
            ''
          ),
          componentName: compose.displayName,
          props: flattenProps(compose.props)
        })
      })
    }

    const mergedProps = Object.assign(
      {},
      ...composesFlattened.map(({ props }) => props),
      sortedProps
    )

    const mergedSortedProps = Object.keys(mergedProps)
      .sort()
      .reduce((acc, val) => {
        acc[val] = mergedProps[val]
        return acc
      }, {})

    return this.template({
      componentName,
      srcLink: file.replace(this.options.componentsBasePath + '/', ''),
      description: docs.description,
      isMissingComposes: (docs.composes || []).length !== composes.length,
      props: mergedSortedProps,
      composes: composesFlattened
    })
  }
}

module.exports = ReactDocGenMarkdownRenderer


text:
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/CrowdLinker/shortener/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/CrowdLinker/shortener/?branch=master)

Version
----
1.4

Tech
-----------

Crowdlinker Shortener uses a number of open source projects to work properly:

* [Laravel 4] - PHP MVC framework
* [AngularJS] - MVW javascript framework
* [Twitter Bootstrap] - great UI boilerplate for modern web apps
* [node.js] - evented I/O for the backend
* [npm] - Node package modules
* [Grunt] - Task Manager
* [Gulp] - The streaming build system. Too minify and compile SASS/SCSS.
* [jQuery] - duh
* [Vagrant] - Development Environment.
* [Embedly] - For Extracting URL
* [jVectorMap] - For Analytics geo visualizaton.
* [freegeoip] - REST Api for searching geolocation by ipaddress.
* [Mandrill] - SMTP server.

Features
-----------

* Generate Shortlink. Ability to use any custom domain of your choice.
* Single Sign On - Currently supports Facebook,Twitter and username/password.
* Track clicks (Including unique clicks)
* Track Location - Countries and City
* Share to your social network.
* Scheduling post to social network (coming soon).
* SafeBrowsing

Installation
--------------

```sh
git clone [git-repo-url] [foldername]
cd [foldername]
composer install

```

##### Create your '.env.php' (If using in production environment) or '.env.local.php' (In local) in root.

```sh
<?php
return [
    'FACEBOOK_ID' => '<facebook-key>',
    'FACEBOOK_SECRET' => '<facebook-secret>',
    'TWITTER_KEY' => '<twitter-key>',
    'TWITTER_SECRET' => '<twitter-secret>',
    'TWITTER_CALLBACK_URI' => '<your-domain>/auth/twitter/callback',
    'MANDRILL_USERNAME' => '<mandrill-username>',
    'MANDRILL_KEY' => '<mandrill-key>',
    'EMBEDLY_KEY' => '<embedly-key>',
    'SHORT_DOMAIN' => '<your-short-domain e.g sample.com>',
    'COMPANY_NAME' => '<company-name>',
    'COMPANY_SITE' => '<company-site>',
];

```
##### Configure Database.
* Configure app/config/database.php - For production
* Configure app/config/local/database.php - For local environment (All config for local environment goes to app/local/)

##### Migrate Database
* For production

```sh
php artisan migrate

```

* For local/dev environment

```sh
php artisan migrate --env=local

```
##### Setup cronjob
* Setup cronjob to run at midnight for following command (used for to analyze unique clicks):

```sh
0 0 * * * 1,2,3,4,5 /usr/bin/php /public_html/shortener/artisan crowdlinker:updatecount

```

**Free Software, Hell Yeah! Feel free to contribute or suggest any issues or new features.**
[Laravel 4]:http://laravel.com
[Grunt]:http://gruntjs.com/
[AngularJS]:https://angularjs.org/
[npm]:https:http://www.npmjs.org/
[node.js]:http://nodejs.org
[Twitter Bootstrap]:http://twitter.github.com/bootstrap/
[jQuery]:http://jquery.com
[Gulp]:http://gulpjs.com
[Vagrant]:http://www.vagrantup.com/
[Embedly]:http://embed.ly
[jVectorMap]:http://jvectormap.com/
[freegeoip]:http://freegeoip.net
[Mandrill]:http://mandrillapp.com


text:
package com.filestack.transforms.tasks;

import static org.junit.Assert.assertTrue;

import com.filestack.transforms.TransformTask;
import com.filestack.transforms.tasks.ModulateTask;
import org.junit.Test;

public class TestModulateTask {

  @Test
  public void testToString() {
    String correct = "modulate="
        + "brightness:155,"
        + "hue:155,"
        + "saturation:155";

    TransformTask task = new ModulateTask.Builder()
        .brightness(155)
        .hue(155)
        .saturation(155)
        .build();

    String output = task.toString();

    String message = String.format("Task string malformed\nCorrect: %s\nOutput: %s",
        correct, output);
    assertTrue(message, output.equals(correct));
  }
}


text:
package org.apache.flink.table.client.gateway.local.result;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamUtils;
import org.apache.flink.streaming.experimental.SocketStreamIterator;
import org.apache.flink.table.client.SqlClientException;
import org.apache.flink.table.client.gateway.SqlExecutionException;
import org.apache.flink.table.client.gateway.TypedResult;
import org.apache.flink.table.client.gateway.local.CollectStreamTableSink;
import org.apache.flink.table.client.gateway.local.ProgramDeployer;
import org.apache.flink.table.sinks.TableSink;
import org.apache.flink.types.Row;

import java.io.IOException;
import java.net.InetAddress;

/**
 * A result that works similarly to {@link DataStreamUtils#collect(DataStream)}.
 *
 * @param <C> cluster id to which this result belongs to
 */
public abstract class CollectStreamResult<C> extends BasicResult<C> implements DynamicResult<C> {

	private final TypeInformation<Row> outputType;
	private final SocketStreamIterator<Tuple2<Boolean, Row>> iterator;
	private final CollectStreamTableSink collectTableSink;
	private final ResultRetrievalThread retrievalThread;
	private final JobMonitoringThread monitoringThread;
	private ProgramDeployer<C> deployer;

	protected final Object resultLock;
	protected SqlExecutionException executionException;

	public CollectStreamResult(TypeInformation<Row> outputType, ExecutionConfig config,
			InetAddress gatewayAddress, int gatewayPort) {
		this.outputType = outputType;

		resultLock = new Object();

		// create socket stream iterator
		final TypeInformation<Tuple2<Boolean, Row>> socketType = Types.TUPLE(Types.BOOLEAN, outputType);
		final TypeSerializer<Tuple2<Boolean, Row>> serializer = socketType.createSerializer(config);
		try {
			// pass gateway port and address such that iterator knows where to bind to
			iterator = new SocketStreamIterator<>(gatewayPort, gatewayAddress, serializer);
		} catch (IOException e) {
			throw new SqlClientException("Could not start socket for result retrieval.", e);
		}

		// create table sink
		// pass binding address and port such that sink knows where to send to
		collectTableSink = new CollectStreamTableSink(iterator.getBindAddress(), iterator.getPort(), serializer);
		retrievalThread = new ResultRetrievalThread();
		monitoringThread = new JobMonitoringThread();
	}

	@Override
	public TypeInformation<Row> getOutputType() {
		return outputType;
	}

	@Override
	public void startRetrieval(ProgramDeployer<C> deployer) {
		// start listener thread
		retrievalThread.start();

		// start deployer
		this.deployer = deployer;
		monitoringThread.start();
	}

	@Override
	public TableSink<?> getTableSink() {
		return collectTableSink;
	}

	@Override
	public void close() {
		retrievalThread.isRunning = false;
		retrievalThread.interrupt();
		monitoringThread.interrupt();
		iterator.close();
	}

	// --------------------------------------------------------------------------------------------

	protected <T> TypedResult<T> handleMissingResult() {
		// check if the monitoring thread is still there
		// we need to wait until we know what is going on
		if (monitoringThread.isAlive()) {
			return TypedResult.empty();
		}
		// the job finished with an exception
		else if (executionException != null) {
			throw executionException;
		}
		// we assume that a bounded job finished
		else {
			return TypedResult.endOfStream();
		}
	}

	protected boolean isRetrieving() {
		return retrievalThread.isRunning;
	}

	protected abstract void processRecord(Tuple2<Boolean, Row> change);

	// --------------------------------------------------------------------------------------------

	private class JobMonitoringThread extends Thread {

		@Override
		public void run() {
			try {
				deployer.run();
			} catch (SqlExecutionException e) {
				executionException = e;
			}
		}
	}

	// --------------------------------------------------------------------------------------------

	private class ResultRetrievalThread extends Thread {

		public volatile boolean isRunning = true;

		@Override
		public void run() {
			try {
				while (isRunning && iterator.hasNext()) {
					final Tuple2<Boolean, Row> change = iterator.next();
					processRecord(change);
				}
			} catch (RuntimeException e) {
				// ignore socket exceptions
			}

			// no result anymore
			// either the job is done or an error occurred
			isRunning = false;
		}
	}
}


text:
using System;
using System.Threading.Tasks;
using LibGit2Sharp;
using GitHub.Primitives;
using System.Collections.Generic;
using GitHub.Models;

namespace GitHub.Services
{
    public interface IGitClient
    {
        /// <summary>
        /// Pull changes from the configured upstream remote and branch into the branch pointed at by HEAD.
        /// </summary>
        /// <param name="repository">The repository to pull</param>
        /// <returns></returns>
        Task Pull(IRepository repository);

        /// <summary>
        /// Pushes HEAD to specified branch on the remote.
        /// </summary>
        /// <param name="repository">The repository to push</param>
        /// <param name="branchName">the branch remote to push to</param>
        /// <param name="remoteName">The name of the remote</param>
        /// <returns></returns>
        Task Push(IRepository repository, string branchName, string remoteName);

        /// <summary>
        /// Fetches from the remote, using custom refspecs.
        /// </summary>
        /// <param name="repository">The repository to pull</param>
        /// <param name="remoteName">The name of the remote</param>
        /// <param name="refspecs">The custom refspecs or none to use the default</param>
        /// <returns></returns>
        Task Fetch(IRepository repository, string remoteName, params string[] refspecs);

        /// <summary>
        /// Fetches from a remote URI, using custom refspecs.
        /// </summary>
        /// <remarks>
        /// If the URI is the same as origin then origin will be used, otherwise a
        /// temporary remote will be created for the fetch. The fetch will always be made
        /// using HTTPS.
        /// </remarks>
        /// <param name="repository">The repository to pull</param>
        /// <param name="remoteUri">The remote URI to fetch from</param>
        /// <param name="refspecs">The custom refspecs</param>
        /// <returns></returns>
        Task Fetch(IRepository repository, UriString remoteUri, params string[] refspecs);

        /// <summary>
        /// Checks out a branch.
        /// </summary>
        /// <param name="repository">The repository to carry out the checkout on</param>
        /// <param name="branchName">The name of the branch</param>
        /// <returns></returns>
        Task Checkout(IRepository repository, string branchName);

        /// <summary>
        /// Checks if a commit exists a the repository.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="sha">The SHA of the commit.</param>
        /// <returns></returns>
        Task<bool> CommitExists(IRepository repository, string sha);

        /// <summary>
        /// Creates a new branch.
        /// </summary>
        /// <param name="repository">The repository to carry out the checkout on</param>
        /// <param name="branchName">The name of the branch</param>
        /// <returns></returns>
        Task CreateBranch(IRepository repository, string branchName);

        /// <summary>
        /// Gets the value of a configuration key.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="key">The configuration key. Keys are in the form 'section.name'.</param>
        /// <returns></returns>
        Task<T> GetConfig<T>(IRepository repository, string key);

        /// <summary>
        /// Sets the configuration key to the specified value in the local config.
        /// </summary>
        /// <param name="repository">The repository</param>
        /// <param name="key">The configuration key. Keys are in the form 'section.name'.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        Task SetConfig(IRepository repository, string key, string value);

        /// <summary>
        /// Sets the specified remote to the specified URL.
        /// </summary>
        /// <param name="repository">The repository to set</param>
        /// <param name="remoteName">The name of the remote</param>
        /// <param name="url">The URL to set as the remote</param>
        /// <returns></returns>
        Task SetRemote(IRepository repository, string remoteName, Uri url);

        /// <summary>
        /// Sets the remote branch that the local branch tracks
        /// </summary>
        /// <param name="repository">The repository to set</param>
        /// <param name="branchName">The name of the local branch</param>
        /// <param name="remoteName">The name of the remote</param>
        /// <returns></returns>
        Task SetTrackingBranch(IRepository repository, string branchName, string remoteName);

        /// <summary>
        /// Unsets the configuration key in the local config.
        /// </summary>
        /// <param name="repository">The repository</param>
        /// <param name="key">The configuration key. Keys are in the form 'section.name'.</param>
        /// <returns></returns>
        Task UnsetConfig(IRepository repository, string key);

        Task<Remote> GetHttpRemote(IRepository repo, string remote);

        /// <summary>
        /// Extracts a file at a specified commit from the repository.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="commitSha">The SHA of the commit.</param>
        /// <param name="fileName">The path to the file, relative to the repository.</param>
        /// <returns>
        /// The contents of the file, or null if the file was not found at the specified commit.
        /// </returns>
        Task<string> ExtractFile(IRepository repository, string commitSha, string fileName);

        /// <summary>
        /// Extracts a file at a specified commit from the repository as binary data.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="commitSha">The SHA of the commit.</param>
        /// <param name="fileName">The path to the file, relative to the repository.</param>
        /// <returns>
        /// The contents of the file, or null if the file was not found at the specified commit.
        /// </returns>
        Task<byte[]> ExtractFileBinary(IRepository repository, string commitSha, string fileName);

        /// <summary>
        /// Checks whether the latest commit of a file in the repository has the specified file
        /// contents.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="path">The relative path to the file.</param>
        /// <param name="contents">The file contents to test.</param>
        /// <returns></returns>
        Task<bool> IsModified(IRepository repository, string path, byte[] contents);

        /// <summary>
        /// Find the merge base SHA between two commits.
        /// </summary>
        /// <param name="repo">The repository.</param>
        /// <param name="targetCloneUrl">The clone url of the PR target repo.</param>
        /// <param name="baseSha">The PR base SHA.</param>
        /// <param name="headSha">The PR head SHA.</param>
        /// <param name="baseRef">The PR base ref (e.g. 'master').</param>
        /// <param name="pullNumber">The PR number.</param>
        /// <returns>
        /// The merge base SHA or null.
        /// </returns>
        /// <exception cref="LibGit2Sharp.NotFoundException">Thrown when the merge base can't be found.</exception>
        Task<string> GetPullRequestMergeBase(IRepository repo, UriString targetCloneUrl, string baseSha, string headSha, string baseRef, int pullNumber);

        /// <summary>
        /// Checks whether the current head is pushed to its remote tracking branch.
        /// </summary>
        /// <param name="repo">The repository.</param>
        /// <returns></returns>
        Task<bool> IsHeadPushed(IRepository repo);

        /// <summary>
        /// Gets the unique commits from <paramref name="compareBranch"/> to the merge base of
        /// <paramref name="baseBranch"/> and <paramref name="compareBranch"/> and returns their
        /// commit messages.
        /// </summary>
        /// <param name="repo">The repository.</param>
        /// <param name="baseBranch">The base branch to find a merge base with.</param>
        /// <param name="compareBranch">The compare branch to find a merge base with.</param>
        /// <param name="maxCommits">The maximum number of commits to return.</param>
        /// <returns>An enumerable of unique commits from the merge base to the compareBranch.</returns>
        Task<IReadOnlyList<CommitMessage>> GetMessagesForUniqueCommits(
            IRepository repo,
            string baseBranch,
            string compareBranch,
            int maxCommits);
    }
}


text:
package com.google.inject.service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;

/** Tests using Async Service. */

public class SingleServiceIntegrationTest extends TestCase {

  public final void testAsyncServiceLifecycle() throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch stopLatch = new CountDownLatch(1);
    AsyncService service =
        new AsyncService(executor) {
          @Override
          protected void onStart() {
            assertEquals(1, startLatch.getCount());
            assertEquals(1, stopLatch.getCount());

            startLatch.countDown();
          }

          @Override
          protected void onStop() {
            assertEquals(0, startLatch.getCount());
            assertEquals(1, stopLatch.getCount());

            stopLatch.countDown();
          }
        };

    Future<?> future = service.start();
    // This should not pass!  TODO(sameb): Why?  Looks like it should to me
    assertTrue(startLatch.await(2, TimeUnit.SECONDS));
    // onStart() is called before the state is set to STARTED, so we need
    // to wait until the Future finishes to guarantee it really was started.
    // This still manages to test what we want because the startLatch check
    // is before this.
    future.get(1, TimeUnit.SECONDS);

    service.stop();
    assertTrue(stopLatch.await(2, TimeUnit.SECONDS));

    executor.shutdown();
    assertEquals(0, startLatch.getCount());
    assertEquals(0, stopLatch.getCount());
  }

  public final void testAsyncServiceBlockingLifecycle()
      throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    final AtomicInteger integer = new AtomicInteger(2);
    AsyncService service =
        new AsyncService(executor) {
          @Override
          protected void onStart() {
            assertEquals(2, integer.getAndDecrement());
          }

          @Override
          protected void onStop() {
            assertEquals(1, integer.getAndDecrement());
          }
        };

    service.start().get(2, TimeUnit.SECONDS);
    service.stop().get(2, TimeUnit.SECONDS);

    executor.shutdown();
    assertEquals(0, integer.get());
  }
}


text:
package com.zoomulus.speakeasy.core.flow;

import lombok.AccessLevel;
import lombok.Setter;
import lombok.experimental.Accessors;

import com.zoomulus.speakeasy.core.message.Message;

public abstract class Receiver
{
    @Setter(AccessLevel.PACKAGE)
    @Accessors(fluent=true)
    Source source;

    protected void onMessageReceived(final Message message)
    {
        source.processMessage(message);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('dashboard', '0003_secondaryrole_short_name'),
    ]

    operations = [
        migrations.AddField(
            model_name='member',
            name='secondary_role',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='secondary_role', to='dashboard.SecondaryRole'),
            preserve_default=False,
        ),
    ]


text:
using DragonSpark.Runtime;
using DragonSpark.Sources.Parameterized;
using DragonSpark.Sources.Parameterized.Caching;
using DragonSpark.TypeSystem;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;

namespace DragonSpark.Extensions
{
	public static class EnumerableExtensions
	{
		public static T[] Fixed<T>( this IEnumerable<T> @this )
		{
			var array = @this is ImmutableArray<T> ? ((ImmutableArray<T>)@this).ToArray() : @this as T[] ?? @this.ToArray();
			var result = array.Length > 0 ? array : (T[])Enumerable.Empty<T>();
			return result;
		}

		public static IEnumerable<ValueTuple<T1, T2>> Introduce<T1, T2>( this ImmutableArray<T1> @this, T2 instance ) => Introduce( @this, instance, Where<ValueTuple<T1, T2>>.Always, Delegates<ValueTuple<T1, T2>>.Self );

		public static IEnumerable<T1> Introduce<T1, T2>( this IEnumerable<Func<T2, T1>> @this, T2 instance ) => Introduce( @this, instance, tuple => tuple.Item1( tuple.Item2 ) );

		public static IEnumerable<T1> Introduce<T1, T2>( this ImmutableArray<Func<T2, T1>> @this, T2 instance ) => Introduce( @this, instance, tuple => tuple.Item1( tuple.Item2 ) );

		public static IEnumerable<T1> Introduce<T1, T2>( this ImmutableArray<T1> @this, T2 instance, Func<ValueTuple<T1, T2>, bool> where ) => Introduce( @this, instance, @where, tuple => tuple.Item1 );

		public static IEnumerable<TResult> Introduce<T1, T2, TResult>( this ImmutableArray<T1> @this, T2 instance, Func<ValueTuple<T1, T2>, TResult> select ) => Introduce( @this, instance, Where<ValueTuple<T1, T2>>.Always, @select );

		public static IEnumerable<TResult> Introduce<T1, T2, TResult>( this ImmutableArray<T1> @this, T2 instance, Func<ValueTuple<T1, T2>, bool> where, Func<ValueTuple<T1, T2>, TResult> select )
		{
			foreach ( var item in @this )
			{
				var tuple = ValueTuple.Create( item, instance );
				if ( where( tuple ) )
				{
					yield return select( tuple );
				}
			}
		}

		public static IEnumerable<ValueTuple<T1, T2>> Introduce<T1, T2>( this IEnumerable<T1> @this, T2 instance ) => Introduce( @this, instance, Where<ValueTuple<T1, T2>>.Always, Delegates<ValueTuple<T1, T2>>.Self );

		public static IEnumerable<T1> Introduce<T1, T2>( this IEnumerable<T1> @this, T2 instance, Func<ValueTuple<T1, T2>, bool> where ) => Introduce( @this, instance, @where, tuple => tuple.Item1 );

		public static IEnumerable<TResult> Introduce<T1, T2, TResult>( this IEnumerable<T1> @this, T2 instance, Func<ValueTuple<T1, T2>, TResult> select ) => Introduce( @this, instance, Where<ValueTuple<T1, T2>>.Always, @select );

		public static IEnumerable<TResult> Introduce<T1, T2, TResult>( this IEnumerable<T1> @this, T2 instance, Func<ValueTuple<T1, T2>, bool> where, Func<ValueTuple<T1, T2>, TResult> select )
		{
			foreach ( var item in @this )
			{
				var tuple = ValueTuple.Create( item, instance );
				if ( where( tuple ) )
				{
					yield return select( tuple );
				}
			}
		}

		public static bool All( this IEnumerable<bool> source )
		{
			foreach ( var b in source )
			{
				if ( !b )
				{
					return false;
				}
			}

			return true;
		}

		public static IEnumerable<T> Prioritize<T>( this IEnumerable<T> @this ) => Prioritize( @this, Support<T>.PriorityLocator );

		public static IEnumerable<T> Prioritize<T>( this IEnumerable<T> @this, Func<T, IPriorityAware> locator ) => @this.OrderBy( locator, PriorityComparer.Default );

		public static TTo WithFirst<TFrom, TTo>( this IEnumerable<TFrom> @this, Func<TFrom, TTo> with, Func<TTo> defaultFunction = null ) => WithFirst( @this, Where<TFrom>.Always, with, defaultFunction );

		public static TTo WithFirst<TFrom, TTo>( this IEnumerable<TFrom> @this, Func<TFrom, bool> where, Func<TFrom, TTo> with, Func<TTo> defaultFunction = null ) => @this.WhereAssigned().FirstOrDefault( @where ).With( with, defaultFunction );

		public static T Only<T>( this IEnumerable<T> @this ) => Only( @this, Where<T>.Always );
		public static T Only<T>( this ImmutableArray<T> @this, Func<T, bool> where ) => @this.AsEnumerable().Only( where );
		public static T Only<T>( this IEnumerable<T> @this, Func<T, bool> where )
		{
			var enumerable = @this.Where( where ).ToArray();
			var result = enumerable.Length == 1 ? enumerable[0] : default(T);
			return result;
		}

		public static void Each<T>( this ImmutableArray<T> @this, Action<T> action ) => @this.AsEnumerable().ForEach( action );
		public static void Each<T>( this IEnumerable<T> @this, Action<T> action ) => @this.ForEach( action );

		public static IEnumerable<TResult> Each<T, TResult>( this IEnumerable<T> enumerable, Func<T, TResult> action ) => enumerable.Select( action ).ToArray();

		public static IEnumerable<T> Yield<T>( this T @this ) => EnumerableEx.Return( @this );

		public static TItem[] ToItem<TItem>( this TItem target ) where TItem : class => Array<TItem>.Default.Get( target );
		class Array<T> : Cache<T, T[]> where T : class
		{
			public static Array<T> Default { get; } = new Array<T>();
			Array() : base( arg => new[] { arg } ) {}
		}

		public static IEnumerable<T> Append<T>( this T @this, params T[] second ) => @this.Append( second.AsEnumerable() );
		public static IEnumerable<T> Append<T>( this T @this, IEnumerable<T> second ) => @this.Append_( second );

		static IEnumerable<T> Append_<T>( this T @this, IEnumerable<T> second )
		{
			yield return @this;
			foreach ( var element1 in second )
				yield return element1;
		}

		public static T[] Fixed<T>( this IEnumerable<T> @this, params T[] items ) => @this.Append( items ).Fixed();

		public static IEnumerable<T> Append<T>( this IEnumerable<T> @this, params T[] items ) => @this.Concat( items );

		public static IEnumerable<T> Append<T>( this IEnumerable<T> @this, [Optional]T element )
		{
			foreach ( var element1 in @this )
				yield return element1;
			yield return element;
		}

		public static IEnumerable<T> Prepend<T>( this T @this, params T[] second ) => @this.Prepend( second.AsEnumerable() );
		public static IEnumerable<T> Prepend<T>( this T @this, IEnumerable<T> second ) => @this.Prepend_( second );

		static IEnumerable<T> Prepend_<T>( this T @this, IEnumerable<T> second )
		{
			foreach ( var item in second )
				yield return item;
			yield return @this;
		}

		public static IEnumerable<T> Prepend<T>( this IEnumerable<T> @this, params T[] items ) => items.Concat( @this );

		public static IEnumerable<ValueTuple<T1, T2>> Tuple<T1, T2>( this IEnumerable<T1> target, IEnumerable<T2> other ) => target.Zip( other, ValueTuple.Create ).ToArray();

		public static T FirstAssigned<T>( this IEnumerable<T> @this ) => @this.WhereAssigned().FirstOrDefault();

		// public static TTo FirstAssigned<TFrom, TTo>( this ImmutableArray<TFrom> @this, Func<TFrom, TTo> projection ) => @this.ToArray().FirstAssigned( projection );

		public static TTo FirstAssigned<TFrom, TTo>( this IEnumerable<TFrom> @this, Func<TFrom, TTo> projection ) => @this.WhereAssigned().Select( projection ).FirstAssigned();

		public static IEnumerable<T> WhereAssigned<T>( this ImmutableArray<T> target ) => target.AsEnumerable().WhereAssigned();
		public static IEnumerable<T> WhereAssigned<T>( this IEnumerable<T> target )
		{
			foreach ( var item in target )
			{
				if ( Where<T>.Assigned( item ) )
				{
					yield return item;
				}
			}
		}

		public static IEnumerable<TResult> SelectAssigned<TSource, TResult>( this ImmutableArray<TSource> @this, Func<TSource, TResult> select ) => @this.AsEnumerable().SelectAssigned( select );
		public static IEnumerable<TResult> SelectAssigned<TSource, TResult>( this IEnumerable<TSource> @this, Func<TSource, TResult> select ) => @this.Select( select ).WhereAssigned();

		public static T FirstOrDefaultOfType<T>( this IEnumerable enumerable ) => enumerable.OfType<T>().FirstOrDefault();

		public static T PeekOrDefault<T>( this System.Collections.Generic.Stack<T> @this ) => @this.Any() ? @this.Peek() : default(T);

		static class Support<T>
		{
			public static Func<T, IPriorityAware> PriorityLocator { get; } = PriorityAwareLocator<T>.Default.ToSourceDelegate();
		}
	}
}


text:
import {createProjectFromAsset} from '../../../utils/assets';
import {exec} from '../../../utils/process';
import {expectFileSizeToBeUnder} from '../../../utils/fs';

export default function(skipCleaning: () => void) {
  if (process.platform.startsWith('win')) {
    // Disable the test on Windows.
    return Promise.resolve();
  }

  return Promise.resolve()
    .then(() => createProjectFromAsset('webpack/test-app'))
    .then(() => exec('node_modules/.bin/webpack', '-p'))
    .then(() => expectFileSizeToBeUnder('dist/app.main.js', 400000))
    .then(() => expectFileSizeToBeUnder('dist/0.app.main.js', 40000))
    .then(() => skipCleaning());
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: NumericalRev< T ></title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>

OR-Tools
    9.4

Public Member Functions |
List of all members

NumericalRev< T >

Detailed Description

template<class T>

class operations_research::NumericalRev< T >

Subclass of Rev<T> which adds numerical operations.

Definition at line 3804 of file constraint_solver.h.

Public Member Functions

 	NumericalRev (const T &val)

void 	Add (Solver *const s, const T &to_add)

void 	Incr (Solver *const s)

void 	Decr (Solver *const s)

const T & 	Value () const

void 	SetValue (Solver *const s, const T &val)

Constructor & Destructor Documentation

◆ NumericalRev()

          NumericalRev
          (
          const T &
          val	)

inlineexplicit

Definition at line 3806 of file constraint_solver.h.

Member Function Documentation

◆ Add()

          void Add
          (
          Solver *const
          s,

          const T &
          to_add

          )

inline

Definition at line 3808 of file constraint_solver.h.

◆ Decr()

          void Decr
          (
          Solver *const
          s	)

inline

Definition at line 3814 of file constraint_solver.h.

◆ Incr()

          void Incr
          (
          Solver *const
          s	)

inline

Definition at line 3812 of file constraint_solver.h.

◆ SetValue()

          void SetValue
          (
          Solver *const
          s,

          const T &
          val

          )

inlineinherited

Definition at line 3787 of file constraint_solver.h.

◆ Value()

          const T & Value
          (
          	)
           const

inlineinherited

Definition at line 3785 of file constraint_solver.h.

The documentation for this class was generated from the following file:

constraint_solver.h

operations_research

NumericalRev

Generated by

     1.9.4


text:
require "faraday"
require "json"

ENV["DS3_ENDPOINT"] = ENV["DS3_ENDPOINT"] || "sm2u-11"

# Has to be to https and not http.
connection = Faraday.new(:url =>  "https://#{ENV["DS3_ENDPOINT"]}-mgmt.eng.sldomain.com",
                                            # Don't worry about verifying the SSL certificate.
                                            :ssl => { :verify => false }) do |conn|
  conn.request(:basic_auth, "spectra", "spectra")
  # User Ruby's net/http library
  conn.adapter(:net_http)
  # Setup for JSON requests and responses.
  conn.headers = { "Accept" => "application/json",
                   "Content-Type" => "application/json" }
end

# List all users
response = connection.get("/api/users")
# All GET responses are under a root "data"
users = JSON.parse(response.body)["data"]

spectra_user = {}
users.each do | user_entry |
  spectra_user = user_entry if user_entry["name"].eql?("Spectra")
end

# None of the "/api/users" responses include the S3 keys.  For that, you have to
# make a separate "/api/ds3/keys" request which is setup to return an array
# of DS3 authid/secretkey pairs in case we ever allow more than one pair per
# user.
response = connection.get("/api/ds3/keys?user_id=#{spectra_user["id"]}")
spectra_user_keys = JSON.parse(response.body)["data"][0]
abort("Spectra User Keys not found.") if spectra_user.keys.nil?

ENV["DS3_ENDPOINT"] = "#{ENV['DS3_ENDPOINT']}.eng.sldomain.com"
ENV["DS3_SECRET_KEY"] = spectra_user_keys["secret_key"]
ENV["DS3_ACCESS_KEY"] = spectra_user_keys["auth_id"]
puts "DS3_ENDPOINT #{ENV["DS3_ENDPOINT"]}"
puts "DS3_SECRET_KEY #{ENV["DS3_SECRET_KEY"]}"
puts "DS3_ACCESS_KEY #{ENV["DS3_ACCESS_KEY"]}"

ENV["GIT_REPO"] = ENV["GIT_REPO"] || "https://github.com/SpectraLogic/ds3_python_sdk.git"
ENV["GIT_BRANCH"] = ENV["GIT_BRANCH"] || "master"
puts "GIT_REPO #{ENV["GIT_REPO"] || "default"}"
puts "GIT_BRANCH #{ENV["GIT_BRANCH"]}"

ENV["DOCKER_REPO"] =  ENV["DOCKER_REPO"] || "spectralogic/ds3_python_docker_test:latest"
puts "DOCKER_REPO #{ENV["DOCKER_REPO"]}"

# Close the git repo
puts `git clone #{ENV["GIT_REPO"]} --branch #{ENV["GIT_BRANCH"]} --single-branch`

# Build latest docker image
puts "docker build -t #{ENV['DOCKER_REPO']} ./ds3_python_sdk/docker/"
docker_build_output = `docker build -t #{ENV["DOCKER_REPO"]} ./ds3_python_sdk/docker/`
docker_build_status = $?
puts docker_build_output
puts "docker build status[#{docker_build_status}][#{docker_build_status.exitstatus}]"

# Run the tests in the updated docker container
puts "docker run -e DS3_ENDPOINT -e DS3_SECRET_KEY -e DS3_ACCESS_KEY -e GIT_REPO -e GIT_BRANCH --dns=10.1.0.9 #{ENV["DOCKER_REPO"]}"
output = `docker run -e DS3_ENDPOINT -e DS3_SECRET_KEY -e DS3_ACCESS_KEY -e GIT_REPO -e GIT_BRANCH --dns=10.1.0.9 #{ENV["DOCKER_REPO"]}`

docker_status = $?

puts output
puts "docker status[#{docker_status}][#{docker_status.exitstatus}]"

# clean up git repo
puts `rm -rf ds3_python_sdk`

exit docker_status.exitstatus


text:
package com.sabre.oss.conf4j.processor;

import java.util.Objects;

import static java.util.Objects.requireNonNull;

/**
 * Specialized {@link ConfigurationValueProcessor} responsible for decrypting configuration value.
 * It delegates value decryption to {@link ConfigurationValueDecrypter}.
 *
 * @see ConfigurationValueDecrypter
 * @see ConfigurationValueProcessor
 */
public class ConfigurationValueDecryptingProcessor implements ConfigurationValueProcessor {
    protected ConfigurationValueDecrypter decrypter;

    /**
     * Constructs a class using  {@link NoOpConfigurationValueDecrypter}.
     * Use {@link #setDecrypter(ConfigurationValueDecrypter)} to set proper decrypter latter.
     */
    public ConfigurationValueDecryptingProcessor() {
        this.decrypter = new NoOpConfigurationValueDecrypter();
    }

    /**
     * Constructs a class and set {@code decrypter}.
     *
     * @param decrypter configuration value decrypter.
     * @throws NullPointerException when {@code decrypter} is {@code null}.
     */
    public ConfigurationValueDecryptingProcessor(ConfigurationValueDecrypter decrypter) {
        this.decrypter = requireNonNull(decrypter, "decrypter cannot be null");
    }

    /**
     * Set configuration value decrypter.
     *
     * @param decrypter configuration value decrypter.
     * @throws NullPointerException when {@code decrypter} is {@code null}.
     */
    public void setDecrypter(ConfigurationValueDecrypter decrypter) {
        this.decrypter = requireNonNull(decrypter, "decrypter cannot be null");
    }

    /**
     * Decrypts configuration value when {@link ConfigurationValue#isEncrypted()} returns {@code true}
     * and {@link ConfigurationValue#getEncryptionProvider()} equals {@link ConfigurationValueDecrypter#getName()}.
     * After decryption the configuration value is updated in {@link ConfigurationValue#setDecryptedValue(String)}.
     *
     * @param value value retrieved form the configuration. It may change as a part of processing.
     * @return object provided in {@code value} parameter.
     * @throws IllegalArgumentException when {@code value} is {@code null}.
     * @throws IllegalStateException    when {@link #decrypter} is not set.
     */
    @Override
    public ConfigurationValue process(ConfigurationValue value) {
        requireNonNull(value, "value cannot be null");

        if (value.isEncrypted() && Objects.equals(value.getEncryptionProvider(), decrypter.getName())) {
            String encrypted = value.getValue();
            String decrypted = decrypter.decrypt(encrypted);
            value.setDecryptedValue(decrypted);
        }
        return value;
    }
}


text:
<META http-equiv="Content-Type" content="text/html">
<title>Design Rule Verification Report</title>

Design Rule Verification Report

Date:

11/14/16

Time:

2:24:24 PM

Elapsed Time:

00:00:02

Filename:

<acronym title="\\Mac\Home\Desktop\Duke\BME464\Electronics\Main.PcbDoc">\\Mac\Home\Desktop\Duke\BME464\Electronics\Main.PcbDoc</acronym>

Warnings:

0

Rule Violations:

0

Summary

Warnings
Count

Total
0

Rule Violations
Count

Room Filtering1 (Bounding Region = (995mil, 1235mil, 2765mil, 1825mil) (InComponentClass('Filtering1'))
0

Room Filtering2 (Bounding Region = (993.89mil, 2101mil, 2763.89mil, 2691mil) (InComponentClass('Filtering2'))
0

SMD Neck-Down Constraint (Percent=100%) (All)
0

Short-Circuit Constraint (Allowed=No) (All),(All)
0

Un-Routed Net Constraint ( (All) )
0

Clearance Constraint (Gap=7.5mil) (All),(All)
0

Power Plane Connect Rule(Direct Connect )(Expansion=20mil) (Conductor Width=10mil) (Air Gap=10mil) (Entries=4) (All)
0

Width Constraint (Min=10mil) (Max=20mil) (Preferred=10mil) (All)
0

Height Constraint (Min=0mil) (Max=1000mil) (Prefered=500mil) (All)
0

Hole Size Constraint (Min=1mil) (Max=150mil) (All)
0

Hole To Hole Clearance (Gap=10mil) (All),(All)
0

Minimum Solder Mask Sliver (Gap=1mil) (All),(All)
0

Silk To Solder Mask (Clearance=5mil) (Disabled)(IsPad),(All)
0

Silk to Silk (Clearance=2mil) (All),(All)
0

Net Antennae (Tolerance=0mil) (All)
0

Modified Polygon (Allow modified: No), (Allow shelved: No)
0

Room Digital (Bounding Region = (1604.121mil, 1610.879mil, 2374.121mil, 2380.879mil) (InComponentClass('Digital'))
0

Room Drive (Bounding Region = (1748.15mil, 2360mil, 2253.15mil, 2769mil) (InComponentClass('Drive'))
0

Room Input1 (Bounding Region = (2310mil, 2416.85mil, 2630mil, 2901.85mil) (InComponentClass('Input1'))
0

Room Input2 (Bounding Region = (1370mil, 2425mil, 1690mil, 2910mil) (InComponentClass('Input2'))
0

Room Main (Bounding Region = (3030mil, 2094mil, 3070mil, 2812mil) (InComponentClass('Main'))
0

Room Neg (Bounding Region = (1410mil, 1225mil, 1945mil, 1570mil) (InComponentClass('Neg'))
0

Room Pos (Bounding Region = (1015mil, 1302.323mil, 1392mil, 1719mil) (InComponentClass('Pos'))
0

Total
0


text:
module Volt
  # Contains all of the methods on a model that make it behave like a hash.
  # Moving this into a module cleans up the main Model class for things that
  # make it behave like a model.
  module ModelHashBehaviour
    def delete(name)
      name = name.to_sym

      value = @attributes.delete(name)

      @size_dep.changed!
      @deps.delete(name)

      @persistor.removed(name) if @persistor

      value
    end

    def size
      @size_dep.depend
      @attributes.size
    end

    # Returns all of the keys, skipping over nil models
    # TODO: We should store nil-models elsewhere so we don't have
    # to skip.
    def keys
      @size_dep.depend

      keys = []

      each_pair do |k, v|
        keys << k
      end

      keys
    end

    def nil?
      @attributes.nil?
    end

    def empty?
      @size_dep.depend
      !@attributes || @attributes.size == 0
    end

    def false?
      @attributes.false?
    end

    def true?
      @attributes.true?
    end

    def clear
      @attributes.each_pair do |key, _|
        delete(key)
      end

      # @attributes.clear
      @size_dep.changed!
      #
      # @persistor.removed(nil) if @persistor
    end

    def each_with_object(*args, &block)
      (@attributes || {}).each_with_object(*args, &block)
    end

    def each(&block)
      # TODO: We shouldn't need to check the size for this to work
      size
      @array.each(&block)
    end

    def each_pair
      @attributes.each_pair do |k, v|
        yield(k, v) unless v.is_a?(Model) && v.nil?
      end
    end

    def key?(key)
      @attributes && @attributes.key?(key)
    end

    # Convert the model to a hash all of the way down.
    def to_h
      @size_dep.depend

      if @attributes.nil?
        nil
      else
        hash = {}
        @attributes.each_pair do |key, value|
          hash[key] = deep_unwrap(value)
        end
        hash
      end
    end
  end
end


text:
/* ContentPane
 *
 * .duiContentPane
 * 	set padding for basic content pane
 *
 * Nested layouts:
 *
 * .duiTabContainerTop-duiContentPane,
 * .duiTabContainerLeft-duiContentPane,
 * .duiTabContainerBottom-duiContentPane,
 * .duiTabContainerRight-duiContentPane
 * 	set background-color and padding of ContentPanes nested within TabContainer (can do top, left, bottom, or right) or Accordion Container
 *
 * .duiAccordionContainer-duiContentPane
 * 	set background-color and padding of ContentPane nested within Accordion
 *
 * .duiSplitContainer-duiContentPane,
 *	set background-color and padding of ContentPane nested within a SplitContainer
 *
 * .duiBorderContainer-duiContentPane
 *	set background-color and padding of ContentPane nested within a BorderContainer
 */
.duiContentPane {
  display: block;
  overflow: auto;
  /* if we don't have this (or overflow:hidden), then Widget.resizeTo() doesn't make sense for ContentPane */

  -webkit-overflow-scrolling: touch;
}
.duiContentPaneSingleChild {
  /*
	 * if the ContentPane holds a single layout widget child which is being sized to match the content pane,
	 * then the ContentPane should never get a scrollbar (but it does due to browser bugs, see #9449
	 */

  overflow: hidden;
}
.duiContentPaneLoading .duiIconLoading,
.duiContentPaneError .duiIconError {
  margin-right: 9px;
}
.claro .duiContentPane {
  padding: 8px;
}
/* nested layouts */
.claro .duiTabContainerTop-duiContentPane,
.claro .duiTabContainerLeft-duiContentPane,
.claro .duiTabContainerBottom-duiContentPane,
.claro .duiTabContainerRight-duiContentPane,
.claro .duiAccordionContainer-duiContentPane {
  background-color: #ffffff;
  padding: 8px;
}
.claro .duiSplitContainer-duiContentPane,
.claro .duiBorderContainer-duiContentPane {
  background-color: #ffffff;
  padding: 8px;
}


text:
@class RUAttributesDictionaryBuilder;

@interface UILabel (RUAttributesDictionaryBuilder)

-(void)ru_absorbPropertiesFromAttributesDictionaryBuilder:(RUAttributesDictionaryBuilder*)attributesDictionaryBuilder;

@end


text:
package org.spanna;

import org.spanna.asm.inject.InjectionRegistry;
import org.spanna.reflect.ReflectionRegistry;
import org.spanna.reflect.ReflectiveClass;
import org.spanna.util.Util;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
//Very Important part of Spanna!
public class Main {

    private static SpannaClassLoader classLoader;

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            System.err.println("Arguments: <vanilla JAR file>");
            return;
        }

        File jarFile = new File(args[0]);
        if (!jarFile.exists()) {
            System.err.println("[\/]Specified JAR file " + jarFile.getName() + " does not exist, exiting.");
            return;
        }

        classLoader = new RTClassLoader(new URL[]{jarFile.toURI().toURL()}, ClassLoader.getSystemClassLoader());

        System.out.println("Beginning startup process. This will most likely take a long time, please wait...");
        System.out.println("Initializing reflection registry...");
        ReflectionRegistry.registerAll();
        Map<String, byte[]> classes = new HashMap<>();
        try (ZipInputStream zip = new ZipInputStream(new FileInputStream(jarFile))) {
            System.out.println("Reading JAR file...");

            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                if (entry.getName().endsWith(".class")) {
                    System.out.println("Reading class " + Util.toBinaryClassName(entry.getName()) + "...");
                    byte[] clazz = ByteStreams.toByteArray(zip);
                    classes.put(Util.toBinaryClassName(entry.getName()), clazz);

                    ClassReader reader = new ClassReader(clazz);
                    ReflectionRegistry.locateClassesUsingBytecode(reader);
                } else if (entry.getName().equals("log4j2.xml")) {
                    System.out.println("Copying log4j2.xml...");
                    File file = new File("log4j2.xml");
                    FileOutputStream fos = new FileOutputStream(file);
                    ByteStreams.copy(zip, fos);
                    fos.flush();
                    fos.close();
                    System.setProperty("log4j.configurationFile", file.toURI().toURL().toString());
                }
            }
        }

        // TODO: Really don't want to have to do multiple location attempts,
        // but we need to unless we find a better solution for load order...
        System.out.println("Performing second location attempt for accuracy...");
        for (byte[] b : classes.values()) {
            ClassReader reader = new ClassReader(b);
            ReflectionRegistry.locateClassesUsingBytecode(reader);
        }

        System.out.println("Initializing injection registry...");
        InjectionRegistry.registerAll();
        System.out.println("Injecting classes...");
        List<String> injected = new ArrayList<>();
        for (String s : InjectionRegistry.getReflectiveClassNames()) {
            ReflectiveClass rc = ReflectiveClass.get(s);
            if (rc != null && rc.getObfuscatedName() != null && classes.containsKey(rc.getObfuscatedName())) {
                System.out.println("Injecting " + rc + "...");
                ClassReader cr = new ClassReader(classes.get(rc.getObfuscatedName()));
                ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
                InjectionRegistry.injectClass(rc.getName(), cr, cw);

                System.out.println("Defining " + rc.getObfuscatedName() + "...");
                byte[] data = cw.toByteArray();
                classLoader.defineClass0(rc.getObfuscatedName(), data, 0, data.length);
                injected.add(rc.getObfuscatedName());
            }
        }

        System.out.println("Initializing reflective references...");
        ReflectionRegistry.initializeReferences();

        System.out.println("----------[ CLASS LOCATION RESULTS ]----------");
        for (ReflectiveClass rc : ReflectionRegistry.getReflectiveClasses().values()) {
            System.out.println(rc);
        }

        System.out.println("Starting Minecraft server running Spanna...");
        Class mainClass = Class.forName("net.minecraft.server.MinecraftServer", true, classLoader);
        Method mainMethod = mainClass.getMethod("main", new Class[]{String[].class});
        mainMethod.invoke(null, (Object) args);
    }

    public static SpannaClassLoader getClassLoader() {
        return classLoader;
    }
}


text:
from subprocess import CalledProcessError
import os
import re

from vee import log
from vee.cli import style_note, style_warning, style_error, style
from vee.environment import Environment
from vee.exceptions import CliMixin
from vee.git import GitRepo
from vee.packageset import PackageSet
from vee.requirements import Requirements, Header
from vee.utils import cached_property, makedirs

class EnvironmentRepo(GitRepo):

    def __init__(self, dbrow, home):
        super(EnvironmentRepo, self).__init__(
            work_tree=dbrow['path'] or home._abs_path('repos', dbrow['name']),
            remote_name=dbrow['remote'],
            branch_name=dbrow['branch'],
        )
        self.id = dbrow['id']
        self.name = dbrow['name']
        self.home = home
        self._req_path = os.path.join(self.work_tree, 'requirements.txt')

    def fetch(self):
        return super(EnvironmentRepo, self).fetch(self.remote_name, self.branch_name)

    def checkout(self, force=False):
        super(EnvironmentRepo, self).checkout(
            revision='%s/%s' % (self.remote_name, self.branch_name),
            branch=self.branch_name,
            force=force
        )

    def get_environment(self):
        return Environment(repo=self, home=self.home)

    def load_requirements(self, revision=None):
        reqs = Requirements(env_repo=self, home=self.home)
        if revision is not None:
            contents = self.show(revision, 'requirements.txt')
            if contents:
                reqs.parse_file(contents.splitlines())
        else:
            if os.path.exists(self._req_path):
                reqs.parse_file(self._req_path)
        return reqs

    def dump_requirements(self, req_set):
        tmp = self._req_path + '.tmp'
        with open(tmp, 'wb') as fh:
            for line in req_set.iter_dump():
                fh.write(line)
        os.rename(tmp, self._req_path)

    def commit(self, message, semver_level=None):

        self.git('add', self._req_path, silent=True)

        status = list(self.status())
        if not status:
            raise RuntimeError('nothing to commit')

        # Make sure there are no other changes.
        for idx, tree, name in status:
            if tree.strip():
                raise RuntimeError('work-tree is dirty')

        req_set = self.load_requirements()

        version_header = req_set.headers.get('Version')
        if not version_header:
            version_header = req_set.add_header('Version', '0.0.0')

        if semver_level is not None:
            version = []
            for i, x in enumerate(re.split(r'[.-]', version_header.value)):
                try:
                    version.append(int(x))
                except ValueError:
                    version.append(x)
            while len(version) <= semver_level:
                version.append(0)

            version[semver_level] = version[semver_level] + 1
            for i in xrange(semver_level + 1, len(version)):
                version[i] = 0

            version_header.value = '.'.join(str(x) for x in version)

        from vee import __about__ as about
        req_set.set_header('Vee-Revision', about.__version__ + '+' + about.__revision__)

        self.dump_requirements(req_set)

        self.git('add', self._req_path, silent=True)
        self.git('commit', '-m', message, silent=True)

    def update(self, force=False):

        log.info(style_note('Updating repo', self.name))

        self.clone_if_not_exists()

        if self.remote_name not in self.remotes():
            log.warning(style_warning('"%s" does not have remote "%s"' % (self.name, self.remote_name)))
            return True

        rev = self.fetch()

        if not force and not self.check_ff_safety(rev):
            log.error('Cannot fast-forward; skipping.')
            return False

        self.checkout(force=force)
        return True

    def upgrade(self, dirty=False, subset=None, reinstall=False, relink=False,
        no_deps=False, force_branch_link=True
    ):

        self.clone_if_not_exists()

        try:
            head = self.head
        except CalledProcessError:
            log.warning(style_warning('no commits in repository'))
            head = None

        try:
            remote_head = self.rev_parse('%s/%s' % (self.remote_name, self.branch_name))
        except ValueError:
            log.warning(style_warning('tracked %s/%s does not exist in self' % (self.remote_name, self.branch_name)))
            remote_head = None

        if remote_head and head != remote_head:
            log.warning(style_warning('%s repo not checked out to %s/%s' % (
                self.name, self.remote_name, self.branch_name)))

        dirty = bool(list(self.status()))
        if not dirty and self.is_dirty():
            log.error('%s repo is dirty; force with --dirty' % self.name)
            return False

        env = self.get_environment()

        req_set = self.load_requirements()
        pkg_set = PackageSet(env=env, home=self.home)

        # Register the whole set, so that dependencies are pulled from here instead
        # of weakly resolved from installed packages.
        # TODO: This blanket reinstalls things, even if no_deps is set.
        pkg_set.resolve_set(req_set, check_existing=not reinstall)

        # Install and/or link.
        pkg_set.install(subset or None, link_env=env, reinstall=reinstall, relink=relink, no_deps=no_deps)

        if pkg_set._errored and not force_branch_link:
            log.warning(style_warning("Not creating branch or version links; force with --force-branch-link"))
            return False

        # Create a symlink by branch.
        path_by_branch = self.home._abs_path('environments', self.name, self.branch_name)
        if os.path.lexists(path_by_branch):
            os.unlink(path_by_branch)
        makedirs(os.path.dirname(path_by_branch))
        os.symlink(env.path, path_by_branch)

        # Create a symlink by version.
        version = req_set.headers.get('Version')
        if version:
            path_by_version = self.home._abs_path('environments', self.name, 'versions', version.value + ('-dirty' if dirty else ''))
            if os.path.lexists(path_by_version):
                os.unlink(path_by_version)
            makedirs(os.path.dirname(path_by_version))
            os.symlink(env.path, path_by_version)

        return True


text:
package com.xcc.advancedday13.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.xcc.advancedday13.R;
import com.xcc.advancedday13.adapters.MainViewPagerAdapter;
import com.xcc.advancedday13.base.BaseActivity;
import com.xcc.advancedday13.ui.fragments.MyFragment;
import com.xcc.advancedday13.ui.fragments.StrategyFragment;
import com.xcc.advancedday13.ui.fragments.TravelsFragment;

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

public class MainActivity extends BaseActivity implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener, View.OnClickListener {

    private TabLayout mTablayout;
    private ViewPager mViewPager;
    private MainViewPagerAdapter adapter;
    private String[] text={"攻略","游记","行程单","我的"};
    private int[] imageArray={R.mipmap.icon_tab_home,R.mipmap.icon_tab_trip,R.mipmap.icon_tab_plan,R.mipmap.icon_tab_my};
    private TextView mTvSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mTablayout = (TabLayout) findViewById(R.id.main_tab);
        mTvSearch = (TextView) findViewById(R.id.tv_main_search);

        for (int i = 0; i < 4; i++) {
            View tabItem= LayoutInflater.from(this).inflate(R.layout.tab_item, null);
            TextView title = (TextView) tabItem.findViewById(R.id.tab_item_title);
            ImageView image = (ImageView) tabItem.findViewById(R.id.tab_item_image);
            title.setText(text[i]);
            image.setImageResource(imageArray[i]);
            TabLayout.Tab tab = mTablayout.newTab();
            tab.setCustomView(tabItem);
            mTablayout.addTab(tab);
            if (i==0) {
                title.setVisibility(View.GONE);
                image.setVisibility(View.VISIBLE);
            }
        }

        mTvSearch.setOnClickListener(this);
        mViewPager = (ViewPager) findViewById(R.id.main_vp);
        adapter = new MainViewPagerAdapter(getSupportFragmentManager(),getData());
        mViewPager.setAdapter(adapter);

        //mTablayout.setupWithViewPager(mViewPager);
        //mTablayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTablayout));
        mTablayout.setOnTabSelectedListener(this);

        mViewPager.addOnPageChangeListener(this);
    }

    private List<Fragment> getData() {
        List<Fragment> data=new ArrayList<>();
        //第一个Fragment
        StrategyFragment strategyFragment = new StrategyFragment();
        data.add(strategyFragment);

        //第二个Fragment
        TravelsFragment travelsFragment = new TravelsFragment();
        data.add(travelsFragment);

        //第三个Fragment
        MyFragment myFragment1 = new MyFragment();
        data.add(myFragment1);

        //第四个Fragment
        MyFragment myFragment = new MyFragment();
        data.add(myFragment);
        return data;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position==0) {
            ImageView image = (ImageView) mTablayout.getTabAt(position).getCustomView().findViewById(R.id.tab_item_image);
             TextView title = (TextView) mTablayout.getTabAt(position).getCustomView().findViewById(R.id.tab_item_title);
            image.setVisibility(View.VISIBLE);
            title.setVisibility(View.GONE);
        }
//

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {

        mViewPager.setCurrentItem(tab.getPosition());
        TextView title = (TextView) tab.getCustomView().findViewById(R.id.tab_item_title);
        ImageView image = (ImageView) tab.getCustomView().findViewById(R.id.tab_item_image);

        image.startAnimation(AnimationUtils.loadAnimation(this,R.anim.image_enter));
        title.startAnimation(AnimationUtils.loadAnimation(this,R.anim.title_exit));
        image.setVisibility(View.VISIBLE);
        title.setVisibility(View.GONE);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        TextView title = (TextView) tab.getCustomView().findViewById(R.id.tab_item_title);
        ImageView image = (ImageView) tab.getCustomView().findViewById(R.id.tab_item_image);

        image.setVisibility(View.GONE);
        title.setVisibility(View.VISIBLE);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_main_search:
                Intent intent = new Intent(this, SearchActivity.class);

                startActivity(intent);
                break;
        }
    }
}


text:
Config = {
	-- GENERAL --
	["name"] = "[FreeCam]",
	["color"] = Color(200, 200, 255),
	["colorError"] = Color(255, 150, 150),
	["activateKey"] = "V",

	-- SPEED --

	-- Setting:
	-- 0: instant speedup
	-- 1: gradually speedup
	["speedSetting"] = 0,

	-- Speedfactor (when using setting 0):
	-- Speedup factor
	["speedUp"] = 8,

	-- Speeddown factor
	["speedDown"] = 4,

	-- MISC --
	-- Teleport player to cam location when quitting
	["teleport"] = true,
	-- Location on the server to save trajectories
	["trajectoryPath"] = "trajectories.txt",
	-- Location on the server to save single positions
	["positionsPath"] = "positions.txt",

	-- Use white list to limit this function
	["useWhiteList"] = true
}


text:
using CycleSales.CycleSalesModel;
using CycleSales.WarrantyModel;
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CycleSalesInternalApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            CycleSales.CycleSalesModel.DatabaseBootstrapper.EnsureInitialized();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}


text:
    using System;
    using System.Net;
    using Amazon.ElasticMapReduce.Model;
    using Amazon.Runtime;
    using Amazon.Runtime.Internal;
    using Amazon.Runtime.Internal.Transform;

    namespace Amazon.ElasticMapReduce.Model.Internal.MarshallTransformations
    {
      /// <summary>
      /// Response Unmarshaller for AddJobFlowSteps operation
      /// </summary>
      internal class AddJobFlowStepsResponseUnmarshaller : JsonResponseUnmarshaller
      {
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
          AddJobFlowStepsResponse response = new AddJobFlowStepsResponse();

          return response;
        }

        public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
        {
          ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);

          if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException"))
          {
            InternalServerErrorException ex = new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);

            return ex;
          }

          return new AmazonElasticMapReduceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
        }

        private static AddJobFlowStepsResponseUnmarshaller instance;
        public static AddJobFlowStepsResponseUnmarshaller GetInstance()
        {
          if (instance == null)
          {
            instance = new AddJobFlowStepsResponseUnmarshaller();
          }
          return instance;
        }

      }
    }


text:
#import <Mail/MFEWSResponseOperation.h>

@interface MFEWSSyncFolderHierarchyResponseOperation : MFEWSResponseOperation
{
    id _createBlock;
    id _updateBlock;
    id _deleteBlock;
}

@property(copy, nonatomic) id deleteBlock; // @synthesize deleteBlock=_deleteBlock;
@property(copy, nonatomic) id updateBlock; // @synthesize updateBlock=_updateBlock;
@property(copy, nonatomic) id createBlock; // @synthesize createBlock=_createBlock;
- (void)executeOperation;
- (void)prepareToExecuteWithResponse:(id)arg1 forRequestOperation:(id)arg2;
- (void)dealloc;

@end


text:
/*****************************************************************************
 *                               linequs2-impl.h
 *
 * Implementation for solving overdetermined and underdetermined linear
 * equations.
 *
 * Zhang Ming, 2010-07 (revised 2010-12), Xi'an Jiaotong University.
 *****************************************************************************/

/**
 * Overdetermined linear equationequations solution by Least Squares
 * Generalized Inverse.
 * A  --->  The m-by-n(m>n) coefficient matrix(Full Column Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 least squares solution vector.
 */
template <typename Type>
Vector<Type> lsSolver( const Matrix<Type> &A, const Vector<Type> &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() > A.cols() );

    Cholesky<Type> cho;
    cho.dec( trMult(A,A) );
    if( cho.isSpd() )
        return cho.solve( trMult(A,b) );
    else
        return luSolver( trMult(A,A), trMult(A,b) );
}

/**
 * Overdetermined linear equationequations solution by QR Decomposition.
 * A  --->  The m-by-n(m>n) coefficient matrix(Full Column Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 least squares solution vector.
 */
template <typename Real>
Vector<Real> qrLsSolver( const Matrix<Real> &A, const Vector<Real> &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() > A.cols() );

    QRD<Real> qr;
    qr.dec( A );
    if( !qr.isFullRank() )
    {
        cerr << "The matrix A is not Full Rank!" << endl;
        return Vector<Real>();
    }
    else
        return qr.solve( b );
}

/**
 * Overdetermined linear equationequations solution by SVD Decomposition.
 * A  --->  The m-by-n(m>n) coefficient matrix(Full Column Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 least squares solution vector.
 */
template<typename Real>
Vector<Real> svdLsSolver( const Matrix<Real> &A, const Vector<Real> &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() > A.cols() );

    SVD<Real> svd;
    svd.dec( A );
    Matrix<Real> U = svd.getU();
    Matrix<Real> V = svd.getV();
    Vector<Real> s = svd.getSV();

//    for( int i=0; i<V.rows(); ++i )
//        for( int k=0; k<s.dim(); ++k )
//            V[i][k] /= s[k];
//
//    return V * trMult(U,b);

    return V * ( trMult(U,b) / s );
}

/**
 * Overdetermined linear equationequations solution by QR Decomposition.
 * A  --->  The m-by-n(m>n) coefficient matrix(Full Column Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 least squares solution vector.
 */
template<typename Type>
Vector<complex<Type> > qrLsSolver( const Matrix<complex<Type> > &A,
                                   const Vector<complex<Type> > &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() > A.cols() );

    CQRD<Type> qr;
    qr.dec( A );
    if( !qr.isFullRank() )
    {
        cerr << "The matrix A is not Full Rank!" << endl;
        return Vector<complex<Type> >();
    }
    else
        return qr.solve( b );
}

/**
 * Overdetermined linear equationequations solution by SVD Decomposition.
 * A  --->  The m-by-n(m>n) coefficient matrix(Full Column Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 least squares solution vector.
 */
template<typename Type>
Vector<complex<Type> > svdLsSolver( const Matrix<complex<Type> > &A,
                                    const Vector<complex<Type> > &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() > A.cols() );

    CSVD<Type> svd;
    svd.dec( A );
    Matrix<complex<Type> > U = svd.getU();
    Matrix<complex<Type> > V = svd.getV();
    Vector<Type> s = svd.getSV();

//    for( int i=0; i<V.rows(); ++i )
//        for( int k=0; k<s.dim(); ++k )
//            V[i][k] /= s[k];
//
//    return V * trMult(U,b);

    return V * ( trMult(U,b) / complexVector(s) );
}

/**
 * Undetermined linear equationequations solution by Minimum Norm
 * Generalized Inverse.
 * A  --->  The m-by-n(m<n) coefficient matrix(Full Row Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 minimum norm solution vector.
 */
template <typename Type>
Vector<Type> lnSolver( const Matrix<Type> &A, const Vector<Type> &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() < A.cols() );

    Cholesky<Type> cho;
    cho.dec( multTr(A,A) );
    if( cho.isSpd() )
        return trMult( A, cho.solve(b) );
    else
        return trMult( A, luSolver(multTr(A,A),b) );
}

/**
 * Undetermined linear equationequations solution by QR Decomposition.
 * A  --->  The m-by-n(m<n) coefficient matrix(Full Row Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 minimum norm solution vector.
 */
template <typename Real>
Vector<Real> qrLnSolver( const Matrix<Real> &A, const Vector<Real> &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() < A.cols() );

    Matrix<Real> At( trT( A ) );
    QRD<Real> qr;
    qr.dec( At );
    if( !qr.isFullRank() )
    {
        cerr << "The matrix A is not Full Rank!" << endl;
        return Vector<Real>();
    }
    else
    {
        Matrix<Real> Q, R;
        Q = qr.getQ();
        R = qr.getR();
        Vector<Real> y( ltSolver( trT( R ), b ) );
        return Q * y;
    }
}

/**
 * Undetermined complex linear equationequations solution by SVD
 * Decomposition.
 * A  --->  The m-by-n(m<n) coefficient matrix(Full Row Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 minimum norm solution vector.
 */
template<typename Real>
Vector<Real> svdLnSolver( const Matrix<Real> &A, const Vector<Real> &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() < A.cols() );

    SVD<Real> svd;
    svd.dec( A );
    Matrix<Real> U = svd.getU();
    Matrix<Real> V = svd.getV();
    Vector<Real> s = svd.getSV();

//    for( int i=0; i<V.rows(); ++i )
//        for( int k=0; k<s.dim(); ++k )
//            V[i][k] /= s[k];
//
//    return V * trMult(U,b);

    return V * ( trMult(U,b) / s );
}

/**
 * Undetermined complex linear equationequations solution by QR
 * Decomposition.
 * A  --->  The m-by-n(m<n) coefficient matrix(Full Row Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 minimum norm solution vector.
 */
template<typename Type>
Vector<complex<Type> > qrLnSolver( const Matrix<complex<Type> > &A,
                                   const Vector<complex<Type> > &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() < A.cols() );

    Matrix<complex<Type> > At( trH( A ) );
    CQRD<Type> qr;
    qr.dec( At );
    if( !qr.isFullRank() )
    {
        cerr << "The matrix A is not Full Rank!" << endl;
        return Vector<complex<Type> >();
    }
    else
    {
        Matrix<complex<Type> > Q, R;
        Q = qr.getQ();
        R = qr.getR();
        Vector<complex<Type> > y( ltSolver( trH( R ), b ) );
        return Q * y;
    }
}

/**
 * Undetermined complex linear equationequations solution by SVD
 * Decomposition.
 * A  --->  The m-by-n(m<n) coefficient matrix(Full Row Rank);
 * b  --->  The n-by-1 right-hand side vector;
 * x  --->  The n-by-1 minimum norm solution vector.
 */
template<typename Type>
Vector<complex<Type> > svdLnSolver( const Matrix<complex<Type> > &A,
                                    const Vector<complex<Type> > &b )
{
    assert( A.rows() == b.size() );
    assert( A.rows() < A.cols() );

    CSVD<Type> svd;
    svd.dec( A );
    Matrix<complex<Type> > U = svd.getU();
    Matrix<complex<Type> > V = svd.getV();
    Vector<Type> s = svd.getSV();

//    for( int i=0; i<V.rows(); ++i )
//        for( int k=0; k<s.dim(); ++k )
//            V[i][k] /= s[k];
//
//    return V * trMult(U,b);

    return V * ( trMult(U,b) / complexVector(s) );
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mem. Amer. Acad. Arts 16: 12 (1931)

#### Original name
Dichomyces bicolor Thaxt.

### Remarks
null


text:
namespace Macabresoft.Macabre2D.Framework;

using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework;

/// <summary>
/// Represents a dynamic physics body, which can be moved and start collisions with other
/// bodies. It handles interactions with <see cref="Collider" />.
/// </summary>
public interface IDynamicPhysicsBody : IPhysicsBody {
    /// <summary>
    /// Gets or sets a value indicating whether this instance is kinematic.
    /// </summary>
    /// <value><c>true</c> if this instance is kinematic; otherwise, <c>false</c>.</value>
    bool IsKinematic { get; set; }

    /// <summary>
    /// Gets or sets the mass.
    /// </summary>
    /// <value>The mass.</value>
    float Mass { get; set; }

    /// <summary>
    /// Gets or sets the velocity. This is always axis aligned.
    /// </summary>
    /// <value>The velocity.</value>
    Vector2 Velocity { get; set; }
}

/// <summary>
/// A dynamic body.
/// </summary>
[Display(Name = "Dynamic Physics Body")]
public sealed class DynamicPhysicsBody : SimplePhysicsBody, IDynamicPhysicsBody {
    private bool _isKinematic;
    private float _mass = 1f;
    private Vector2 _velocity;

    /// <inheritdoc />
    [DataMember(Name = "Kinematic")]
    public bool IsKinematic {
        get => this._isKinematic;

        set => this.Set(ref this._isKinematic, value);
    }

    /// <inheritdoc />
    [DataMember]
    public float Mass {
        get => this._mass;

        set => this.Set(ref this._mass, value);
    }

    /// <inheritdoc />
    [DataMember]
    public Vector2 Velocity {
        get => this._velocity;

        set => this.Set(ref this._velocity, value);
    }
}


text:
package com.gejiahui.androidpractice.customview.bottomsheet;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Created by gejiahui on 2016/7/7.
 */
public class BottomSheetLayout extends FrameLayout {
    private static final int MARGIN_TOP = 300;
    private int marginTop = MARGIN_TOP;
    private int childCount = 0;
    private ViewGroup mContent;
    private ViewGroup mDrawer;
    private int mHeight;
    private int mDrawerHeight;

    public BottomSheetLayout(Context context) {
        super(context);
    }

    public BottomSheetLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public BottomSheetLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        init();
        super.onFinishInflate();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mHeight = getHeight();
        mDrawerHeight = mDrawer.getHeight();
        mDrawer.setTranslationY(mDrawerHeight);

    }

    private void init(){
        childCount = getChildCount();
        if(childCount != 2){
            throw new IllegalArgumentException("the child views must be 2 ! there is "+ childCount +" child views");
        }

        mContent = (ViewGroup) getChildAt(0);
        mDrawer = (ViewGroup) getChildAt(1);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)mDrawer.getLayoutParams();
        params.topMargin = marginTop;
        mDrawer.setLayoutParams(params);

    }

    public void showSheet() {
        mDrawer.animate().translationY(0).setDuration(500).start();
    }

    public void closeSheet(){
        mDrawer.animate().translationY(mDrawerHeight).setDuration(500).start();
    }

}


text:
package com.alibaba.rocketmq.common.filter.impl;

/**
 * @auther lansheng.zj@taobao.com
 */
public class Operand extends Op {

    public Operand(String symbol) {
        super(symbol);
    }

}


text:
import Component from '@ember/component';
import { computed } from '@ember/object';
import { setupRenderingTest } from 'ember-mocha';
import { describe, it, beforeEach } from 'mocha';
import { expect } from 'chai';
import hbs from 'htmlbars-inline-precompile';
import { click, render } from '@ember/test-helpers';
import hasEmberVersion from 'ember-test-helpers/has-ember-version';

const PrettyColor = Component.extend({
  classNames: ['pretty-color'],
  attributeBindings: ['style'],
  style: computed('name', function() {
    return 'color: ' + this.get('name') + ';';
  }),
  actions: {
    paintItBlack() { this.set('name', 'black'); }
  }
});

function setupRegistry(owner) {
  owner.register('component:x-foo', Component.extend());
  owner.register('component:pretty-color', PrettyColor);
  owner.register('template:components/pretty-color', hbs`Pretty Color: <button {{action "paintItBlack"}}><span class="color-name">{{name}}</span></button>`);
}

describe('setupRenderingTest', function() {
  if (!hasEmberVersion(2, 4)) {
    return;
  }

  describe('pretty-color', function() {
    setupRenderingTest();

    beforeEach(function() {
      setupRegistry(this.owner);
    });

    it('renders with color', async function() {
      this.set('name', 'green');
      await render(hbs`{{pretty-color name=name}}`);
      expect(this.element.textContent.trim()).to.equal('Pretty Color: green');
    });

    it('renders when using standard setters', async function() {
      this.name = 'red';
      await render(hbs`{{pretty-color name=name}}`);
      expect(this.element.textContent.trim()).to.equal('Pretty Color: red');
    });

    it('renders a second time without', async function() {
      await render(hbs`{{pretty-color name=name}}`);
      expect(this.element.textContent.trim()).to.equal('Pretty Color:');
    });

    it('renders a third time with', async function() {
      this.set('name', 'blue');
      expect(this.get('name')).to.equal('blue');
      await render(hbs`{{pretty-color name=name}}`);
      expect(this.element.textContent.trim()).to.equal('Pretty Color: blue');
    });

    it('picks up changes to variables set on the context', async function() {
       this.set('name', 'pink');
       await render(hbs`{{pretty-color name=name}}`);
       await click('button');
       expect(this.element.textContent.trim()).to.equal('Pretty Color: black');
       expect(this.get('name')).to.equal('black');
       expect(this.name).to.equal('black');
     });

     it('picks up changes to variables set on the context with a standard setter', async function() {
       this.name = 'pink';
       await render(hbs`{{pretty-color name=name}}`);
       await click('button');
       expect(this.element.textContent.trim()).to.equal('Pretty Color: black');
       expect(this.name).to.equal('black');
     });
  });

  describe('hooks API', function() {

    let hooks = setupRenderingTest();

    it('returns hooks API', function() {
      expect(hooks)
        .to.respondTo('beforeEach')
        .and.to.respondTo('afterEach');
    });
  });
});


text:
{% extends 'basic.html' %}
{% block content %}

  {% include 'booking/menu.html' %}

{% endblock %}


text:
package st.redline.bootstrap;

import st.redline.core.PrimContext;
import st.redline.core.PrimObject;

public class InitializeMethod extends PrimObject {
    public PrimObject invoke(PrimObject receiver, PrimContext primContext) {
        return receiver;
    }
}


text:
// Karma configuration
// Generated on Wed Sep 23 2015 17:24:52 GMT+0000 (UTC)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'sinon'],

    // list of files / patterns to load in the browser
    files: [
      'app/vendor/jquery-2.1.4.min.js',
      'app/vendor/lodash.min.js',
      'app/vendor/backbone-min.js',
      'app/vendor/**/*.js',
      'app/templates/**/*.js',
      'app/js/**/*.js',
      'test/support/namespaces.js',
      'test/support/vendor/**/*.js',
      'test/factories/**/*.js',
      'test/routes/routes.js',
      'test/routes/**/*.js',
      'test/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  })
}


text:
module ActivityStreams
  class Object::Image < Object
    attr_optional :full_image

    def validate_attributes!
      super
      validate_attribute! :full_image, MediaLink
    end
  end
end