text:
typedef uint_least16_t char16_t;
typedef uint_least32_t char32_t;
# endif
typedef float swift_float2  __attribute__((__ext_vector_type__(2)));
typedef float swift_float3  __attribute__((__ext_vector_type__(3)));
typedef float swift_float4  __attribute__((__ext_vector_type__(4)));
typedef double swift_double2  __attribute__((__ext_vector_type__(2)));
typedef double swift_double3  __attribute__((__ext_vector_type__(3)));
typedef double swift_double4  __attribute__((__ext_vector_type__(4)));
typedef int swift_int2  __attribute__((__ext_vector_type__(2)));
typedef int swift_int3  __attribute__((__ext_vector_type__(3)));
typedef int swift_int4  __attribute__((__ext_vector_type__(4)));
typedef unsigned int swift_uint2  __attribute__((__ext_vector_type__(2)));
typedef unsigned int swift_uint3  __attribute__((__ext_vector_type__(3)));
typedef unsigned int swift_uint4  __attribute__((__ext_vector_type__(4)));
#endif

#if !defined(SWIFT_PASTE)
# define SWIFT_PASTE_HELPER(x, y) x##y
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
#endif
#if !defined(SWIFT_METATYPE)
# define SWIFT_METATYPE(X) Class
#endif
#if !defined(SWIFT_CLASS_PROPERTY)
# if __has_feature(objc_class_property)
#  define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__
# else
#  define SWIFT_CLASS_PROPERTY(...)
# endif
#endif

#if __has_attribute(objc_runtime_name)
# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))
#else
# define SWIFT_RUNTIME_NAME(X)
#endif
#if __has_attribute(swift_name)
# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X)))
#else
# define SWIFT_COMPILE_NAME(X)
#endif
#if __has_attribute(objc_method_family)
# define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X)))
#else
# define SWIFT_METHOD_FAMILY(X)
#endif
#if __has_attribute(noescape)
# define SWIFT_NOESCAPE __attribute__((noescape))
#else
# define SWIFT_NOESCAPE
#endif
#if __has_attribute(warn_unused_result)
# define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define SWIFT_WARN_UNUSED_RESULT
#endif
#if __has_attribute(noreturn)
# define SWIFT_NORETURN __attribute__((noreturn))
#else
# define SWIFT_NORETURN
#endif
#if !defined(SWIFT_CLASS_EXTRA)
# define SWIFT_CLASS_EXTRA
#endif
#if !defined(SWIFT_PROTOCOL_EXTRA)
# define SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_ENUM_EXTRA)
# define SWIFT_ENUM_EXTRA
#endif
#if !defined(SWIFT_CLASS)
# if __has_attribute(objc_subclassing_restricted)
#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA
#  define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# else
#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
#  define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# endif
#endif

#if !defined(SWIFT_PROTOCOL)
# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
#endif

#if !defined(SWIFT_EXTENSION)
# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)
#endif

#if !defined(OBJC_DESIGNATED_INITIALIZER)
# if __has_attribute(objc_designated_initializer)
#  define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
# else
#  define OBJC_DESIGNATED_INITIALIZER
# endif
#endif
#if !defined(SWIFT_ENUM_ATTR)
# if defined(__has_attribute) && __has_attribute(enum_extensibility)
#  define SWIFT_ENUM_ATTR __attribute__((enum_extensibility(open)))
# else
#  define SWIFT_ENUM_ATTR
# endif
#endif
#if !defined(SWIFT_ENUM)
# define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_ATTR SWIFT_ENUM_EXTRA _name : _type
# if __has_feature(generalized_swift_name)
#  define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR SWIFT_ENUM_EXTRA _name : _type
# else
#  define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) SWIFT_ENUM(_type, _name)
# endif
#endif
#if !defined(SWIFT_UNAVAILABLE)
# define SWIFT_UNAVAILABLE __attribute__((unavailable))
#endif
#if !defined(SWIFT_UNAVAILABLE_MSG)
# define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg)))
#endif
#if !defined(SWIFT_AVAILABILITY)
# define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__)))
#endif
#if !defined(SWIFT_DEPRECATED)
# define SWIFT_DEPRECATED __attribute__((deprecated))
#endif
#if !defined(SWIFT_DEPRECATED_MSG)
# define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__)))
#endif
#if __has_feature(attribute_diagnose_if_objc)
# define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning")))
#else
# define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg)
#endif
#if __has_feature(modules)
@import Foundation;
@import ObjectiveC;
#endif

#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"
#pragma clang diagnostic ignored "-Wduplicate-method-arg"
#if __has_warning("-Wpragma-clang-attribute")
# pragma clang diagnostic ignored "-Wpragma-clang-attribute"
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wnullability"

#if __has_attribute(external_source_symbol)
# pragma push_macro("any")
# undef any
# pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="Alamofire",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol))
# pragma pop_macro("any")
#endif

@class NSURLSession;
@class NSURLSessionTask;
@class NSHTTPURLResponse;
@class NSURLAuthenticationChallenge;
@class NSURLCredential;
@class NSInputStream;

/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
SWIFT_CLASS("_TtC9Alamofire12TaskDelegate")
@interface TaskDelegate : NSObject
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task willPerformHTTPRedirection:(NSHTTPURLResponse * _Nonnull)response newRequest:(NSURLRequest * _Nonnull)request completionHandler:(void (^ _Nonnull)(NSURLRequest * _Nullable))completionHandler;
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didReceiveChallenge:(NSURLAuthenticationChallenge * _Nonnull)challenge completionHandler:(void (^ _Nonnull)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler;
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task needNewBodyStream:(void (^ _Nonnull)(NSInputStream * _Nullable))completionHandler;
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didCompleteWithError:(NSError * _Nullable)error;
- (nonnull instancetype)init SWIFT_UNAVAILABLE;
+ (nonnull instancetype)new SWIFT_DEPRECATED_MSG("-init is unavailable");
@end

@class NSURLSessionDataTask;
@class NSURLResponse;
@class NSURLSessionDownloadTask;
@class NSCachedURLResponse;

SWIFT_CLASS("_TtC9Alamofire16DataTaskDelegate")
@interface DataTaskDelegate : TaskDelegate <NSURLSessionDataDelegate>
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask didReceiveResponse:(NSURLResponse * _Nonnull)response completionHandler:(void (^ _Nonnull)(NSURLSessionResponseDisposition))completionHandler;
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask;
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask didReceiveData:(NSData * _Nonnull)data;
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask willCacheResponse:(NSCachedURLResponse * _Nonnull)proposedResponse completionHandler:(void (^ _Nonnull)(NSCachedURLResponse * _Nullable))completionHandler;
@end

SWIFT_CLASS("_TtC9Alamofire20DownloadTaskDelegate")
@interface DownloadTaskDelegate : TaskDelegate <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession * _Nonnull)session downloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask didFinishDownloadingToURL:(NSURL * _Nonnull)location;
- (void)URLSession:(NSURLSession * _Nonnull)session downloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
- (void)URLSession:(NSURLSession * _Nonnull)session downloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes;
@end

/// Responsible for handling all delegate callbacks for the underlying session.
SWIFT_CLASS("_TtC9Alamofire15SessionDelegate")
@interface SessionDelegate : NSObject
/// Initializes the SessionDelegate instance.
///
/// returns:
/// The new SessionDelegate instance.
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
/// Returns a Bool indicating whether the SessionDelegate implements or inherits a method that can respond
/// to a specified message.
/// \param selector A selector that identifies a message.
///
///
/// returns:
/// true if the receiver implements or inherits a method that can respond to selector, otherwise false.
- (BOOL)respondsToSelector:(SEL _Nonnull)selector SWIFT_WARN_UNUSED_RESULT;
@end

@interface SessionDelegate (SWIFT_EXTENSION(Alamofire)) <NSURLSessionDownloadDelegate>
/// Tells the delegate that a download task has finished downloading.
/// \param session The session containing the download task that finished.
///
/// \param downloadTask The download task that finished.
///
/// \param location A file URL for the temporary file. Because the file is temporary, you must either
/// open the file for reading or move it to a permanent location in your app's sandbox
/// container directory before returning from this delegate method.
///
- (void)URLSession:(NSURLSession * _Nonnull)session downloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask didFinishDownloadingToURL:(NSURL * _Nonnull)location;
/// Periodically informs the delegate about the download's progress.
/// \param session The session containing the download task.
///
/// \param downloadTask The download task.
///
/// \param bytesWritten The number of bytes transferred since the last time this delegate
/// method was called.
///
/// \param totalBytesWritten The total number of bytes transferred so far.
///
/// \param totalBytesExpectedToWrite The expected length of the file, as provided by the Content-Length
/// header. If this header was not provided, the value is
/// NSURLSessionTransferSizeUnknown.
///
- (void)URLSession:(NSURLSession * _Nonnull)session downloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
/// Tells the delegate that the download task has resumed downloading.
/// \param session The session containing the download task that finished.
///
/// \param downloadTask The download task that resumed. See explanation in the discussion.
///
/// \param fileOffset If the file's cache policy or last modified date prevents reuse of the
/// existing content, then this value is zero. Otherwise, this value is an
/// integer representing the number of bytes on disk that do not need to be
/// retrieved again.
///
/// \param expectedTotalBytes The expected length of the file, as provided by the Content-Length header.
/// If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
///
- (void)URLSession:(NSURLSession * _Nonnull)session downloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes;
@end

@interface SessionDelegate (SWIFT_EXTENSION(Alamofire)) <NSURLSessionDelegate>
/// Tells the delegate that the session has been invalidated.
/// \param session The session object that was invalidated.
///
/// \param error The error that caused invalidation, or nil if the invalidation was explicit.
///
- (void)URLSession:(NSURLSession * _Nonnull)session didBecomeInvalidWithError:(NSError * _Nullable)error;
/// Requests credentials from the delegate in response to a session-level authentication request from the
/// remote server.
/// \param session The session containing the task that requested authentication.
///
/// \param challenge An object that contains the request for authentication.
///
/// \param completionHandler A handler that your delegate method must call providing the disposition
/// and credential.
///
- (void)URLSession:(NSURLSession * _Nonnull)session didReceiveChallenge:(NSURLAuthenticationChallenge * _Nonnull)challenge completionHandler:(void (^ _Nonnull)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler;
/// Tells the delegate that all messages enqueued for a session have been delivered.
/// \param session The session that no longer has any outstanding requests.
///
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession * _Nonnull)session;
@end

@class NSURLSessionStreamTask;
@class NSOutputStream;

SWIFT_AVAILABILITY(tvos,introduced=9.0) SWIFT_AVAILABILITY(macos,introduced=10.11) SWIFT_AVAILABILITY(ios,introduced=9.0)
@interface SessionDelegate (SWIFT_EXTENSION(Alamofire)) <NSURLSessionStreamDelegate>
/// Tells the delegate that the read side of the connection has been closed.
/// \param session The session.
///
/// \param streamTask The stream task.
///
- (void)URLSession:(NSURLSession * _Nonnull)session readClosedForStreamTask:(NSURLSessionStreamTask * _Nonnull)streamTask;
/// Tells the delegate that the write side of the connection has been closed.
/// \param session The session.
///
/// \param streamTask The stream task.
///
- (void)URLSession:(NSURLSession * _Nonnull)session writeClosedForStreamTask:(NSURLSessionStreamTask * _Nonnull)streamTask;
/// Tells the delegate that the system has determined that a better route to the host is available.
/// \param session The session.
///
/// \param streamTask The stream task.
///
- (void)URLSession:(NSURLSession * _Nonnull)session betterRouteDiscoveredForStreamTask:(NSURLSessionStreamTask * _Nonnull)streamTask;
/// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
/// \param session The session.
///
/// \param streamTask The stream task.
///
/// \param inputStream The new input stream.
///
/// \param outputStream The new output stream.
///
- (void)URLSession:(NSURLSession * _Nonnull)session streamTask:(NSURLSessionStreamTask * _Nonnull)streamTask didBecomeInputStream:(NSInputStream * _Nonnull)inputStream outputStream:(NSOutputStream * _Nonnull)outputStream;
@end

@interface SessionDelegate (SWIFT_EXTENSION(Alamofire)) <NSURLSessionDataDelegate>
/// Tells the delegate that the data task received the initial reply (headers) from the server.
/// \param session The session containing the data task that received an initial reply.
///
/// \param dataTask The data task that received an initial reply.
///
/// \param response A URL response object populated with headers.
///
/// \param completionHandler A completion handler that your code calls to continue the transfer, passing a
/// constant to indicate whether the transfer should continue as a data task or
/// should become a download task.
///
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask didReceiveResponse:(NSURLResponse * _Nonnull)response completionHandler:(void (^ _Nonnull)(NSURLSessionResponseDisposition))completionHandler;
/// Tells the delegate that the data task was changed to a download task.
/// \param session The session containing the task that was replaced by a download task.
///
/// \param dataTask The data task that was replaced by a download task.
///
/// \param downloadTask The new download task that replaced the data task.
///
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask * _Nonnull)downloadTask;
/// Tells the delegate that the data task has received some of the expected data.
/// \param session The session containing the data task that provided data.
///
/// \param dataTask The data task that provided data.
///
/// \param data A data object containing the transferred data.
///
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask didReceiveData:(NSData * _Nonnull)data;
/// Asks the delegate whether the data (or upload) task should store the response in the cache.
/// \param session The session containing the data (or upload) task.
///
/// \param dataTask The data (or upload) task.
///
/// \param proposedResponse The default caching behavior. This behavior is determined based on the current
/// caching policy and the values of certain received headers, such as the Pragma
/// and Cache-Control headers.
///
/// \param completionHandler A block that your handler must call, providing either the original proposed
/// response, a modified version of that response, or NULL to prevent caching the
/// response. If your delegate implements this method, it must call this completion
/// handler; otherwise, your app leaks memory.
///
- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nonnull)dataTask willCacheResponse:(NSCachedURLResponse * _Nonnull)proposedResponse completionHandler:(void (^ _Nonnull)(NSCachedURLResponse * _Nullable))completionHandler;
@end

@class NSURLSessionTaskMetrics;

@interface SessionDelegate (SWIFT_EXTENSION(Alamofire)) <NSURLSessionTaskDelegate>
/// Tells the delegate that the remote server requested an HTTP redirect.
/// \param session The session containing the task whose request resulted in a redirect.
///
/// \param task The task whose request resulted in a redirect.
///
/// \param response An object containing the server's response to the original request.
///
/// \param request A URL request object filled out with the new location.
///
/// \param completionHandler A closure that your handler should call with either the value of the request
/// parameter, a modified URL request object, or NULL to refuse the redirect and
/// return the body of the redirect response.
///
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task willPerformHTTPRedirection:(NSHTTPURLResponse * _Nonnull)response newRequest:(NSURLRequest * _Nonnull)request completionHandler:(void (^ _Nonnull)(NSURLRequest * _Nullable))completionHandler;
/// Requests credentials from the delegate in response to an authentication request from the remote server.
/// \param session The session containing the task whose request requires authentication.
///
/// \param task The task whose request requires authentication.
///
/// \param challenge An object that contains the request for authentication.
///
/// \param completionHandler A handler that your delegate method must call providing the disposition
/// and credential.
///
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didReceiveChallenge:(NSURLAuthenticationChallenge * _Nonnull)challenge completionHandler:(void (^ _Nonnull)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler;
/// Tells the delegate when a task requires a new request body stream to send to the remote server.
/// \param session The session containing the task that needs a new body stream.
///
/// \param task The task that needs a new body stream.
///
/// \param completionHandler A completion handler that your delegate method should call with the new body stream.
///
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task needNewBodyStream:(void (^ _Nonnull)(NSInputStream * _Nullable))completionHandler;
/// Periodically informs the delegate of the progress of sending body content to the server.
/// \param session The session containing the data task.
///
/// \param task The data task.
///
/// \param bytesSent The number of bytes sent since the last time this delegate method was called.
///
/// \param totalBytesSent The total number of bytes sent so far.
///
/// \param totalBytesExpectedToSend The expected length of the body data.
///
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
/// Tells the delegate that the session finished collecting metrics for the task.
/// \param session The session collecting the metrics.
///
/// \param task The task whose metrics have been collected.
///
/// \param metrics The collected metrics.
///
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics * _Nonnull)metrics SWIFT_AVAILABILITY(tvos,introduced=10.0) SWIFT_AVAILABILITY(macos,introduced=10.12) SWIFT_AVAILABILITY(ios,introduced=10.0);
/// Tells the delegate that the task finished transferring data.
/// \param session The session containing the task whose request finished transferring data.
///
/// \param task The task whose request finished transferring data.
///
/// \param error If an error occurred, an error object indicating how the transfer failed, otherwise nil.
///
- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didCompleteWithError:(NSError * _Nullable)error;
@end

SWIFT_CLASS("_TtC9Alamofire18UploadTaskDelegate")
@interface UploadTaskDelegate : DataTaskDelegate
@end

#if __has_attribute(external_source_symbol)
# pragma clang attribute pop
#endif
#pragma clang diagnostic pop


text:
<?php
/**
 * @Author: Leandro Henrique Reis <emtudo@gmail.com>
 * @Date:   2016-05-06 22:00:25
 * @Last Modified by:   Leandro Henrique Reis
 * @Last Modified time: 2016-06-04 19:50:49
 */

namespace Domain\Classroom;

use Carbon\Carbon;
use Domain\Classroom\Classroom;
use Domain\Matter\Matter;
use Domain\Schedule\Schedule;
use Domain\Student\Student;
use Domain\Teacher\Teacher;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ClassroomTest extends \TestCase
{
    use DatabaseTransactions;

    public function test_create_classroom()
    {
        $classroom = factory(Classroom::class)->create();

        $this->assertInstanceOf(Classroom::class, $classroom);

        $this->assertInstanceOf(Teacher::class, $classroom->teacher);

        $this->assertInstanceOf(Schedule::class, $classroom->schedule);

        $this->assertInstanceOf(Carbon::class, $classroom->created_at);
        $this->assertInstanceOf(Carbon::class, $classroom->updated_at);

        $this->seeInDatabase('classrooms', [
            'name' => $classroom->name,
        ]);
    }

    public function test_create_classroom_with_students()
    {
        $classroom = factory(Classroom::class)->create();

        $student = factory(Student::class)->create();

        $classroom->students()->attach($student);

        $this->assertInstanceOf(Student::class, $classroom->students->first());
    }

    public function test_create_classroom_with_matters()
    {
        $classroom = factory(Classroom::class)->create();

        $matter = factory(Matter::class)->create();

        $classroom->matters()->attach($matter);

        $this->assertInstanceOf(Matter::class, $classroom->matters->first());
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import { Link } from 'react-router'

import { VisitPrimaryLink } from '../index'

import styles from './VisitPrimaryLinksList.css'
import Icon from '../../../components/Icon/Icon'

const VisitPrimaryLinksList = (props) => {
  return (
    <div className={styles.visitPrimaryLinks}>
      {props.primaryLinks.map((link, index) => (
        <VisitPrimaryLink
          key={index}
          title={link.title}
          path={link.path}
          index={index}
          inlineEditing={props.inlineEditing}
          icon={link.icon}
          action={props.action}
        />
      ))}
    </div>
  )
}

VisitPrimaryLinksList.propTypes = {
  inlineEditing: React.PropTypes.bool.isRequired,
  primaryLinks: React.PropTypes.array.isRequired,
  action: React.PropTypes.func.isRequired,
}

export default VisitPrimaryLinksList


text:
using EspaceClient.BackOffice.Silverlight.ViewModels.Administration.Edition;
using EspaceClient.BackOffice.Silverlight.ViewModels.Administration.Edition.Tabs;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;

namespace EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.Administration.Edition
{
    public interface IModelBuilderDetails
    {
        DetailsViewModel Build(EditionEntityViewModel editionEntityViewModel, TabViewModel tabViewModel);
    }
}


text: from datadog.dogstatsd.base import statsd  # noqa


text:
'use strict';

import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import { Builder, $ } from 'vs/base/browser/builder';
import URI from 'vs/base/common/uri';
import { ThrottledDelayer } from 'vs/base/common/async';
import errors = require('vs/base/common/errors');
import labels = require('vs/base/common/labels');
import paths = require('vs/base/common/paths');
import glob = require('vs/base/common/glob');
import { Action, IAction } from 'vs/base/common/actions';
import { prepareActions } from 'vs/workbench/browser/actions';
import { memoize } from 'vs/base/common/decorators';
import { ITree } from 'vs/base/parts/tree/browser/tree';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { IFilesConfiguration, ExplorerFolderContext, FilesExplorerFocusedContext, ExplorerFocusedContext, SortOrderConfiguration, SortOrder } from 'vs/workbench/parts/files/common/files';
import { FileOperation, FileOperationEvent, IResolveFileOptions, FileChangeType, FileChangesEvent, IFileService } from 'vs/platform/files/common/files';
import { RefreshViewExplorerAction, NewFolderAction, NewFileAction } from 'vs/workbench/parts/files/browser/fileActions';
import { FileDragAndDrop, FileFilter, FileSorter, FileController, FileRenderer, FileDataSource, FileViewletState, FileAccessibilityProvider } from 'vs/workbench/parts/files/browser/views/explorerViewer';
import { toResource } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import * as DOM from 'vs/base/browser/dom';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { CollapsibleView, IViewletViewOptions, IViewOptions } from 'vs/workbench/browser/parts/views/views';
import { FileStat, Model } from 'vs/workbench/parts/files/common/explorerModel';
import { IListService } from 'vs/platform/list/browser/listService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IPartService } from 'vs/workbench/services/part/common/partService';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ResourceContextKey, ResourceGlobMatcher } from 'vs/workbench/common/resources';
import { IWorkbenchThemeService, IFileIconTheme } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { isLinux } from 'vs/base/common/platform';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { attachListStyler } from 'vs/platform/theme/common/styler';
import { ViewSizing } from 'vs/base/browser/ui/splitview/splitview';

export interface IExplorerViewOptions extends IViewletViewOptions {
	viewletState: FileViewletState;
}

export class ExplorerView extends CollapsibleView {

	public static ID: string = 'workbench.explorer.fileView';
	private static EXPLORER_FILE_CHANGES_REACT_DELAY = 500; // delay in ms to react to file changes to give our internal events a chance to react first
	private static EXPLORER_FILE_CHANGES_REFRESH_DELAY = 100; // delay in ms to refresh the explorer from disk file changes
	private static EXPLORER_IMPORT_REFRESH_DELAY = 300; // delay in ms to refresh the explorer from imports

	private static MEMENTO_LAST_ACTIVE_FILE_RESOURCE = 'explorer.memento.lastActiveFileResource';
	private static MEMENTO_EXPANDED_FOLDER_RESOURCES = 'explorer.memento.expandedFolderResources';

	public readonly id: string = ExplorerView.ID;

	private explorerViewer: ITree;
	private filter: FileFilter;
	private viewletState: FileViewletState;

	private explorerRefreshDelayer: ThrottledDelayer<void>;
	private explorerImportDelayer: ThrottledDelayer<void>;

	private resourceContext: ResourceContextKey;
	private folderContext: IContextKey<boolean>;

	private filesExplorerFocusedContext: IContextKey<boolean>;
	private explorerFocusedContext: IContextKey<boolean>;

	private fileEventsFilter: ResourceGlobMatcher;

	private shouldRefresh: boolean;
	private autoReveal: boolean;
	private sortOrder: SortOrder;
	private settings: object;

	constructor(
		initialSize: number,
		options: IExplorerViewOptions,
		@IMessageService private messageService: IMessageService,
		@IContextMenuService contextMenuService: IContextMenuService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IEditorGroupService private editorGroupService: IEditorGroupService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IProgressService private progressService: IProgressService,
		@IListService private listService: IListService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IFileService private fileService: IFileService,
		@IPartService private partService: IPartService,
		@IKeybindingService keybindingService: IKeybindingService,
		@IContextKeyService contextKeyService: IContextKeyService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IWorkbenchThemeService private themeService: IWorkbenchThemeService,
		@IEnvironmentService private environmentService: IEnvironmentService
	) {
		super(initialSize, { ...(options as IViewOptions), ariaHeaderLabel: nls.localize('explorerSection', "Files Explorer Section"), sizing: ViewSizing.Flexible }, keybindingService, contextMenuService);

		this.settings = options.viewletSettings;
		this.viewletState = options.viewletState;
		this.actionRunner = options.actionRunner;
		this.autoReveal = true;

		this.explorerRefreshDelayer = new ThrottledDelayer<void>(ExplorerView.EXPLORER_FILE_CHANGES_REFRESH_DELAY);
		this.explorerImportDelayer = new ThrottledDelayer<void>(ExplorerView.EXPLORER_IMPORT_REFRESH_DELAY);

		this.resourceContext = instantiationService.createInstance(ResourceContextKey);
		this.folderContext = ExplorerFolderContext.bindTo(contextKeyService);

		this.filesExplorerFocusedContext = FilesExplorerFocusedContext.bindTo(contextKeyService);
		this.explorerFocusedContext = ExplorerFocusedContext.bindTo(contextKeyService);

		this.fileEventsFilter = instantiationService.createInstance(ResourceGlobMatcher, (root: URI) => this.getFileEventsExcludes(root), (expression: glob.IExpression) => glob.parse(expression));
	}

	private getFileEventsExcludes(root?: URI): glob.IExpression {
		const scope = root ? { resource: root } : void 0;
		const configuration = this.configurationService.getConfiguration<IFilesConfiguration>(undefined, scope);

		return (configuration && configuration.files && configuration.files.exclude) || Object.create(null);
	}

	public renderHeader(container: HTMLElement): void {
		const titleDiv = $('div.title').appendTo(container);
		const titleSpan = $('span').appendTo(titleDiv);
		const setHeader = () => {
			const workspace = this.contextService.getWorkspace();
			const title = workspace.folders.map(folder => labels.getPathLabel(folder.fsPath, void 0, this.environmentService)).join();
			titleSpan.text(this.name).title(title);
		};
		this.toDispose.push(this.contextService.onDidChangeWorkspaceName(() => setHeader()));
		setHeader();

		super.renderHeader(container);
	}

	public get name(): string {
		return this.contextService.getWorkspace().name;
	}

	public set name(value) {
		// noop
	}

	public renderBody(container: HTMLElement): void {
		this.treeContainer = super.renderViewTree(container);
		DOM.addClass(this.treeContainer, 'explorer-folders-view');
		DOM.addClass(this.treeContainer, 'show-file-icons');

		this.tree = this.createViewer($(this.treeContainer));

		if (this.toolBar) {
			this.toolBar.setActions(prepareActions(this.getActions()), this.getSecondaryActions())();
		}

		const onFileIconThemeChange = (fileIconTheme: IFileIconTheme) => {
			DOM.toggleClass(this.treeContainer, 'align-icons-and-twisties', fileIconTheme.hasFileIcons && !fileIconTheme.hasFolderIcons);
		};

		this.toDispose.push(this.themeService.onDidFileIconThemeChange(onFileIconThemeChange));
		this.toDispose.push(this.contextService.onDidChangeWorkspaceFolders(() => this.refreshFromEvent()));
		onFileIconThemeChange(this.themeService.getFileIconTheme());
	}

	public getActions(): IAction[] {
		const actions: Action[] = [];

		actions.push(this.instantiationService.createInstance(NewFileAction, this.getViewer(), null));
		actions.push(this.instantiationService.createInstance(NewFolderAction, this.getViewer(), null));
		actions.push(this.instantiationService.createInstance(RefreshViewExplorerAction, this, 'explorer-action refresh-explorer'));
		actions.push(this.instantiationService.createInstance(CollapseAction, this.getViewer(), true, 'explorer-action collapse-explorer'));

		// Set Order
		for (let i = 0; i < actions.length; i++) {
			const action = actions[i];
			action.order = 10 * (i + 1);
		}

		return actions;
	}

	public create(): TPromise<void> {

		// Update configuration
		const configuration = this.configurationService.getConfiguration<IFilesConfiguration>();
		this.onConfigurationUpdated(configuration);

		// Load and Fill Viewer
		return this.doRefresh().then(() => {

			// When the explorer viewer is loaded, listen to changes to the editor input
			this.toDispose.push(this.editorGroupService.onEditorsChanged(() => this.onEditorsChanged()));

			// Also handle configuration updates
			this.toDispose.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(this.configurationService.getConfiguration<IFilesConfiguration>(), true)));
		});
	}

	private onEditorsChanged(): void {
		if (!this.autoReveal) {
			return; // do not touch selection or focus if autoReveal === false
		}

		let clearSelection = true;
		let clearFocus = false;

		// Handle files
		const activeFile = this.getActiveFile();
		if (activeFile) {

			// Always remember last opened file
			this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE] = activeFile.toString();

			// Select file if input is inside workspace
			if (this.isVisible() && this.contextService.isInsideWorkspace(activeFile)) {
				const selection = this.hasSelection(activeFile);
				if (!selection) {
					this.select(activeFile).done(null, errors.onUnexpectedError);
				}

				clearSelection = false;
			}
		}

		// Handle closed or untitled file (convince explorer to not reopen any file when getting visible)
		const activeInput = this.editorService.getActiveEditorInput();
		if (!activeInput || toResource(activeInput, { supportSideBySide: true, filter: 'untitled' })) {
			this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE] = void 0;
			clearFocus = true;
		}

		// Otherwise clear
		if (clearSelection) {
			this.explorerViewer.clearSelection();
		}

		if (clearFocus) {
			this.explorerViewer.clearFocus();
		}
	}

	private onConfigurationUpdated(configuration: IFilesConfiguration, refresh?: boolean): void {
		if (this.isDisposed) {
			return; // guard against possible race condition when config change causes recreate of views
		}

		this.autoReveal = configuration && configuration.explorer && configuration.explorer.autoReveal;

		// Push down config updates to components of viewer
		let needsRefresh = false;
		if (this.filter) {
			needsRefresh = this.filter.updateConfiguration();
		}

		const configSortOrder = configuration && configuration.explorer && configuration.explorer.sortOrder || 'default';
		if (this.sortOrder !== configSortOrder) {
			this.sortOrder = configSortOrder;
			needsRefresh = true;
		}

		// Refresh viewer as needed
		if (refresh && needsRefresh) {
			this.doRefresh().done(null, errors.onUnexpectedError);
		}
	}

	public focusBody(): void {
		let keepFocus = false;

		// Make sure the current selected element is revealed
		if (this.explorerViewer) {
			if (this.autoReveal) {
				const selection = this.explorerViewer.getSelection();
				if (selection.length > 0) {
					this.reveal(selection[0], 0.5).done(null, errors.onUnexpectedError);
				}
			}

			// Pass Focus to Viewer
			this.explorerViewer.DOMFocus();
			keepFocus = true;
		}

		// Open the focused element in the editor if there is currently no file opened
		const activeFile = this.getActiveFile();
		if (!activeFile) {
			this.openFocusedElement(keepFocus);
		}
	}

	public setVisible(visible: boolean): TPromise<void> {
		return super.setVisible(visible).then(() => {

			// Show
			if (visible) {

				// If a refresh was requested and we are now visible, run it
				let refreshPromise = TPromise.as<void>(null);
				if (this.shouldRefresh) {
					refreshPromise = this.doRefresh();
					this.shouldRefresh = false; // Reset flag
				}

				if (!this.autoReveal) {
					return refreshPromise; // do not react to setVisible call if autoReveal === false
				}

				// Always select the current navigated file in explorer if input is file editor input
				// unless autoReveal is set to false
				const activeFile = this.getActiveFile();
				if (activeFile) {
					return refreshPromise.then(() => {
						return this.select(activeFile);
					});
				}

				// Return now if the workbench has not yet been created - in this case the workbench takes care of restoring last used editors
				if (!this.partService.isCreated()) {
					return TPromise.as(null);
				}

				// Otherwise restore last used file: By lastActiveFileResource
				let lastActiveFileResource: URI;
				if (this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE]) {
					lastActiveFileResource = URI.parse(this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE]);
				}

				if (lastActiveFileResource && this.isCreated && this.model.findClosest(lastActiveFileResource)) {
					this.editorService.openEditor({ resource: lastActiveFileResource, options: { revealIfVisible: true } }).done(null, errors.onUnexpectedError);

					return refreshPromise;
				}

				// Otherwise restore last used file: By Explorer selection
				return refreshPromise.then(() => {
					this.openFocusedElement();
				});
			}

			return void 0;
		});
	}

	private openFocusedElement(preserveFocus?: boolean): void {
		const stat: FileStat = this.explorerViewer.getFocus();
		if (stat && !stat.isDirectory) {
			this.editorService.openEditor({ resource: stat.resource, options: { preserveFocus, revealIfVisible: true } }).done(null, errors.onUnexpectedError);
		}
	}

	private getActiveFile(): URI {
		const input = this.editorService.getActiveEditorInput();

		// ignore diff editor inputs (helps to get out of diffing when returning to explorer)
		if (input instanceof DiffEditorInput) {
			return null;
		}

		// check for files
		return toResource(input, { supportSideBySide: true, filter: 'file' });
	}

	private get isCreated(): boolean {
		return !!(this.explorerViewer && this.explorerViewer.getInput());
	}

	@memoize
	private get model(): Model {
		return this.instantiationService.createInstance(Model);
	}

	public createViewer(container: Builder): ITree {
		const dataSource = this.instantiationService.createInstance(FileDataSource);
		const renderer = this.instantiationService.createInstance(FileRenderer, this.viewletState);
		const controller = this.instantiationService.createInstance(FileController, this.viewletState);
		const sorter = this.instantiationService.createInstance(FileSorter);
		this.filter = this.instantiationService.createInstance(FileFilter);
		const dnd = this.instantiationService.createInstance(FileDragAndDrop);
		const accessibilityProvider = this.instantiationService.createInstance(FileAccessibilityProvider);

		this.explorerViewer = new Tree(container.getHTMLElement(), {
			dataSource,
			renderer,
			controller,
			sorter,
			filter: this.filter,
			dnd,
			accessibilityProvider
		}, {
				autoExpandSingleChildren: true,
				ariaLabel: nls.localize('treeAriaLabel', "Files Explorer"),
				twistiePixels: 12,
				showTwistie: false,
				keyboardSupport: false
			});

		// Theme styler
		this.toDispose.push(attachListStyler(this.explorerViewer, this.themeService));

		// Register to list service
		this.toDispose.push(this.listService.register(this.explorerViewer, [this.explorerFocusedContext, this.filesExplorerFocusedContext]));

		// Update Viewer based on File Change Events
		this.toDispose.push(this.fileService.onAfterOperation(e => this.onFileOperation(e)));
		this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));

		// Update resource context based on focused element
		this.toDispose.push(this.explorerViewer.addListener('focus', (e: { focus: FileStat }) => {
			this.resourceContext.set(e.focus && e.focus.resource);
			this.folderContext.set(e.focus && e.focus.isDirectory);
		}));

		// Open when selecting via keyboard
		this.toDispose.push(this.explorerViewer.addListener('selection', event => {
			if (event && event.payload && event.payload.origin === 'keyboard') {
				const element = this.tree.getSelection();

				if (Array.isArray(element) && element[0] instanceof FileStat) {
					if (element[0].isDirectory) {
						this.explorerViewer.toggleExpansion(element[0]);
					}

					controller.openEditor(element[0], { pinned: false, sideBySide: false, preserveFocus: false });
				}
			}
		}));

		return this.explorerViewer;
	}

	public getOptimalWidth(): number {
		const parentNode = this.explorerViewer.getHTMLElement();
		const childNodes = [].slice.call(parentNode.querySelectorAll('.explorer-item > a'));

		return DOM.getLargestChildWidth(parentNode, childNodes);
	}

	private onFileOperation(e: FileOperationEvent): void {
		if (!this.isCreated) {
			return; // ignore if not yet created
		}

		// Add
		if (e.operation === FileOperation.CREATE || e.operation === FileOperation.IMPORT || e.operation === FileOperation.COPY) {
			const addedElement = e.target;
			const parentResource = URI.file(paths.dirname(addedElement.resource.fsPath));
			const parents = this.model.findAll(parentResource);

			if (parents.length) {

				// Add the new file to its parent (Model)
				parents.forEach(p => {
					// We have to check if the parent is resolved #29177
					(p.isDirectoryResolved ? TPromise.as(null) : this.fileService.resolveFile(p.resource)).then(stat => {
						if (stat) {
							const modelStat = FileStat.create(stat, p.root);
							FileStat.mergeLocalWithDisk(modelStat, p);
						}

						const childElement = FileStat.create(addedElement, p.root);
						p.removeChild(childElement); // make sure to remove any previous version of the file if any
						p.addChild(childElement);
						// Refresh the Parent (View)
						this.explorerViewer.refresh(p).then(() => {
							return this.reveal(childElement, 0.5).then(() => {

								// Focus new element
								this.explorerViewer.setFocus(childElement);
							});
						}).done(null, errors.onUnexpectedError);
					});
				});
			}
		}

		// Move (including Rename)
		else if (e.operation === FileOperation.MOVE) {
			const oldResource = e.resource;
			const newElement = e.target;

			const oldParentResource = URI.file(paths.dirname(oldResource.fsPath));
			const newParentResource = URI.file(paths.dirname(newElement.resource.fsPath));

			// Only update focus if renamed/moved element is selected
			let restoreFocus = false;
			const focus: FileStat = this.explorerViewer.getFocus();
			if (focus && focus.resource && focus.resource.toString() === oldResource.toString()) {
				restoreFocus = true;
			}

			// Handle Rename
			if (oldParentResource && newParentResource && oldParentResource.toString() === newParentResource.toString()) {
				const modelElements = this.model.findAll(oldResource);
				modelElements.forEach(modelElement => {
					// Rename File (Model)
					modelElement.rename(newElement);

					// Update Parent (View)
					this.explorerViewer.refresh(modelElement.parent).done(() => {

						// Select in Viewer if set
						if (restoreFocus) {
							this.explorerViewer.setFocus(modelElement);
						}
					}, errors.onUnexpectedError);
				});
			}

			// Handle Move
			else if (oldParentResource && newParentResource) {
				const newParents = this.model.findAll(newParentResource);
				const modelElements = this.model.findAll(oldResource);

				if (newParents.length && modelElements.length) {

					// Move in Model
					modelElements.forEach((modelElement, index) => {
						const oldParent = modelElement.parent;
						modelElement.move(newParents[index], (callback: () => void) => {
							// Update old parent
							this.explorerViewer.refresh(oldParent).done(callback, errors.onUnexpectedError);
						}, () => {
							// Update new parent
							this.explorerViewer.refresh(newParents[index], true).done(() => this.explorerViewer.expand(newParents[index]), errors.onUnexpectedError);
						});
					});
				}
			}
		}

		// Delete
		else if (e.operation === FileOperation.DELETE) {
			const modelElements = this.model.findAll(e.resource);
			modelElements.forEach(element => {
				if (element.parent) {
					const parent = element.parent;
					// Remove Element from Parent (Model)
					parent.removeChild(element);

					// Refresh Parent (View)
					const restoreFocus = this.explorerViewer.isDOMFocused();
					this.explorerViewer.refresh(parent).done(() => {

						// Ensure viewer has keyboard focus if event originates from viewer
						if (restoreFocus) {
							this.explorerViewer.DOMFocus();
						}
					}, errors.onUnexpectedError);
				}
			});
		}
	}

	private onFileChanges(e: FileChangesEvent): void {

		// Ensure memento state does not capture a deleted file (we run this from a timeout because
		// delete events can result in UI activity that will fill the memento again when multiple
		// editors are closing)
		setTimeout(() => {
			const lastActiveResource: string = this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE];
			if (lastActiveResource && e.contains(URI.parse(lastActiveResource), FileChangeType.DELETED)) {
				this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE] = null;
			}
		});

		// Check if an explorer refresh is necessary (delayed to give internal events a chance to react first)
		// Note: there is no guarantee when the internal events are fired vs real ones. Code has to deal with the fact that one might
		// be fired first over the other or not at all.
		setTimeout(() => {
			if (!this.shouldRefresh && this.shouldRefreshFromEvent(e)) {
				this.refreshFromEvent();
			}
		}, ExplorerView.EXPLORER_FILE_CHANGES_REACT_DELAY);
	}

	private shouldRefreshFromEvent(e: FileChangesEvent): boolean {

		// Filter to the ones we care
		e = this.filterFileEvents(e);

		if (!this.isCreated) {
			return false;
		}

		if (e.gotAdded()) {
			const added = e.getAdded();

			// Check added: Refresh if added file/folder is not part of resolved root and parent is part of it
			const ignoredPaths: { [fsPath: string]: boolean } = <{ [fsPath: string]: boolean }>{};
			for (let i = 0; i < added.length; i++) {
				const change = added[i];
				if (!this.contextService.isInsideWorkspace(change.resource)) {
					continue; // out of workspace file
				}

				// Find parent
				const parent = paths.dirname(change.resource.fsPath);

				// Continue if parent was already determined as to be ignored
				if (ignoredPaths[parent]) {
					continue;
				}

				// Compute if parent is visible and added file not yet part of it
				const parentStat = this.model.findClosest(URI.file(parent));
				if (parentStat && parentStat.isDirectoryResolved && !this.model.findClosest(change.resource)) {
					return true;
				}

				// Keep track of path that can be ignored for faster lookup
				if (!parentStat || !parentStat.isDirectoryResolved) {
					ignoredPaths[parent] = true;
				}
			}
		}

		if (e.gotDeleted()) {
			const deleted = e.getDeleted();

			// Check deleted: Refresh if deleted file/folder part of resolved root
			for (let j = 0; j < deleted.length; j++) {
				const del = deleted[j];
				if (!this.contextService.isInsideWorkspace(del.resource)) {
					continue; // out of workspace file
				}

				if (this.model.findClosest(del.resource)) {
					return true;
				}
			}
		}

		if (this.sortOrder === SortOrderConfiguration.MODIFIED && e.gotUpdated()) {
			const updated = e.getUpdated();

			// Check updated: Refresh if updated file/folder part of resolved root
			for (let j = 0; j < updated.length; j++) {
				const upd = updated[j];
				if (!this.contextService.isInsideWorkspace(upd.resource)) {
					continue; // out of workspace file
				}

				if (this.model.findClosest(upd.resource)) {
					return true;
				}
			}
		}

		return false;
	}

	private filterFileEvents(e: FileChangesEvent): FileChangesEvent {
		return new FileChangesEvent(e.changes.filter(change => {
			if (!this.contextService.isInsideWorkspace(change.resource)) {
				return false; // exclude changes for resources outside of workspace
			}

			if (this.fileEventsFilter.matches(change.resource)) {
				return false; // excluded via files.exclude setting
			}

			return true;
		}));
	}

	private refreshFromEvent(): void {
		if (this.isVisible()) {
			this.explorerRefreshDelayer.trigger(() => {
				if (!this.explorerViewer.getHighlight()) {
					return this.doRefresh();
				}

				return TPromise.as(null);
			}).done(null, errors.onUnexpectedError);
		} else {
			this.shouldRefresh = true;
		}
	}

	/**
	 * Refresh the contents of the explorer to get up to date data from the disk about the file structure.
	 */
	public refresh(): TPromise<void> {
		if (!this.explorerViewer || this.explorerViewer.getHighlight()) {
			return TPromise.as(null);
		}

		// Focus
		this.explorerViewer.DOMFocus();

		// Find resource to focus from active editor input if set
		let resourceToFocus: URI;
		if (this.autoReveal) {
			resourceToFocus = this.getActiveFile();
			if (!resourceToFocus) {
				const selection = this.explorerViewer.getSelection();
				if (selection && selection.length === 1) {
					resourceToFocus = (<FileStat>selection[0]).resource;
				}
			}
		}

		return this.doRefresh().then(() => {
			if (resourceToFocus) {
				return this.select(resourceToFocus, true);
			}

			return TPromise.as(null);
		});
	}

	private doRefresh(): TPromise<void> {
		const targetsToResolve: { root: FileStat, resource: URI, options: { resolveTo: URI[] } }[] = [];
		this.model.roots.forEach(root => {
			const rootAndTargets = { root, resource: root.resource, options: { resolveTo: [] } };
			targetsToResolve.push(rootAndTargets);
		});

		let targetsToExpand: URI[] = [];
		if (this.settings[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES]) {
			targetsToExpand = this.settings[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES].map((e: string) => URI.parse(e));
		} else if (this.model.roots.length === 1) {
			targetsToExpand = this.model.roots.map(root => root.resource); // always expand if there is just one root
		}

		// First time refresh: Receive target through active editor input or selection and also include settings from previous session
		if (!this.isCreated) {
			const activeFile = this.getActiveFile();
			if (activeFile) {
				const workspaceFolder = this.contextService.getWorkspaceFolder(activeFile);
				if (workspaceFolder) {
					const found = targetsToResolve.filter(t => t.root.resource.toString() === workspaceFolder.toString()).pop();
					found.options.resolveTo.push(activeFile);
				}
			}

			targetsToExpand.forEach(toExpand => {
				const workspaceFolder = this.contextService.getWorkspaceFolder(toExpand);
				if (workspaceFolder) {
					const found = targetsToResolve.filter(ttr => ttr.resource.toString() === workspaceFolder.toString()).pop();
					found.options.resolveTo.push(toExpand);
				}
			});
		}

		// Subsequent refresh: Receive targets through expanded folders in tree
		else {
			targetsToResolve.forEach(t => {
				this.getResolvedDirectories(t.root, t.options.resolveTo);
			});
		}

		// Load Root Stat with given target path configured
		const promise = this.fileService.resolveFiles(targetsToResolve).then(results => {
			// Convert to model
			const modelStats = results.map((result, index) => {
				if (result.success) {
					return FileStat.create(result.stat, targetsToResolve[index].root, targetsToResolve[index].options.resolveTo);
				}

				return FileStat.create({
					resource: targetsToResolve[index].resource,
					name: paths.basename(targetsToResolve[index].resource.fsPath),
					mtime: 0,
					etag: undefined,
					isDirectory: true,
					hasChildren: false
				}, targetsToResolve[index].root);
			});
			// Subsequent refresh: Merge stat into our local model and refresh tree
			modelStats.forEach((modelStat, index) => FileStat.mergeLocalWithDisk(modelStat, this.model.roots[index]));

			const input = this.contextService.getWorkbenchState() === WorkbenchState.FOLDER ? this.model.roots[0] : this.model;
			if (input === this.explorerViewer.getInput()) {
				return this.explorerViewer.refresh();
			}

			// Preserve expanded elements if tree input changed.
			// If it is a brand new tree just expand elements from memento
			const expanded = this.explorerViewer.getExpandedElements();
			const statsToExpand = expanded.length ? [this.model.roots[0]].concat(expanded) :
				targetsToExpand.map(expand => this.model.findClosest(expand));

			// Display roots only when multi folder workspace
			// Make sure to expand all folders that where expanded in the previous session
			return this.explorerViewer.setInput(input).then(() => this.explorerViewer.expandAll(statsToExpand));
		}, e => TPromise.wrapError(e));

		this.progressService.showWhile(promise, this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */);

		return promise;
	}

	/**
	 * Given a stat, fills an array of path that make all folders below the stat that are resolved directories.
	 */
	private getResolvedDirectories(stat: FileStat, resolvedDirectories: URI[]): void {
		if (stat.isDirectoryResolved) {
			if (!stat.isRoot) {

				// Drop those path which are parents of the current one
				for (let i = resolvedDirectories.length - 1; i >= 0; i--) {
					const resource = resolvedDirectories[i];
					if (paths.isEqualOrParent(stat.resource.fsPath, resource.fsPath, !isLinux /* ignorecase */)) {
						resolvedDirectories.splice(i);
					}
				}

				// Add to the list of path to resolve
				resolvedDirectories.push(stat.resource);
			}

			// Recurse into children
			for (let i = 0; i < stat.children.length; i++) {
				const child = stat.children[i];
				this.getResolvedDirectories(child, resolvedDirectories);
			}
		}
	}

	/**
	 * Selects and reveal the file element provided by the given resource if its found in the explorer. Will try to
	 * resolve the path from the disk in case the explorer is not yet expanded to the file yet.
	 */
	public select(resource: URI, reveal: boolean = this.autoReveal): TPromise<void> {

		// Require valid path
		if (!resource) {
			return TPromise.as(null);
		}

		// If path already selected, just reveal and return
		const selection = this.hasSelection(resource);
		if (selection) {
			return reveal ? this.reveal(selection, 0.5) : TPromise.as(null);
		}

		// First try to get the stat object from the input to avoid a roundtrip
		if (!this.isCreated) {
			return TPromise.as(null);
		}

		const fileStat = this.model.findClosest(resource);
		if (fileStat) {
			return this.doSelect(fileStat, reveal);
		}

		// Stat needs to be resolved first and then revealed
		const options: IResolveFileOptions = { resolveTo: [resource] };
		const rootUri = this.contextService.getWorkspaceFolder(resource) || this.model.roots[0].resource;
		return this.fileService.resolveFile(rootUri, options).then(stat => {

			// Convert to model
			const root = this.model.roots.filter(r => r.resource.toString() === rootUri.toString()).pop();
			const modelStat = FileStat.create(stat, root, options.resolveTo);
			// Update Input with disk Stat
			FileStat.mergeLocalWithDisk(modelStat, root);

			// Select and Reveal
			return this.explorerViewer.refresh(root).then(() => this.doSelect(root.find(resource), reveal));

		}, e => { this.messageService.show(Severity.Error, e); });
	}

	private hasSelection(resource: URI): FileStat {
		const currentSelection: FileStat[] = this.explorerViewer.getSelection();

		for (let i = 0; i < currentSelection.length; i++) {
			if (currentSelection[i].resource.toString() === resource.toString()) {
				return currentSelection[i];
			}
		}

		return null;
	}

	private doSelect(fileStat: FileStat, reveal: boolean): TPromise<void> {
		if (!fileStat) {
			return TPromise.as(null);
		}

		// Special case: we are asked to reveal and select an element that is not visible
		// In this case we take the parent element so that we are at least close to it.
		if (!this.filter.isVisible(this.tree, fileStat)) {
			fileStat = fileStat.parent;
			if (!fileStat) {
				return TPromise.as(null);
			}
		}

		// Reveal depending on flag
		let revealPromise: TPromise<void>;
		if (reveal) {
			revealPromise = this.reveal(fileStat, 0.5);
		} else {
			revealPromise = TPromise.as(null);
		}

		return revealPromise.then(() => {
			if (!fileStat.isDirectory) {
				this.explorerViewer.setSelection([fileStat]); // Since folders can not be opened, only select files
			}

			this.explorerViewer.setFocus(fileStat);
		});
	}

	public shutdown(): void {

		// Keep list of expanded folders to restore on next load
		if (this.isCreated) {
			const expanded = this.explorerViewer.getExpandedElements()
				.filter(e => e instanceof FileStat)
				.map((e: FileStat) => e.resource.toString());

			if (expanded.length) {
				this.settings[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES] = expanded;
			} else {
				delete this.settings[ExplorerView.MEMENTO_EXPANDED_FOLDER_RESOURCES];
			}
		}

		// Clean up last focused if not set
		if (!this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE]) {
			delete this.settings[ExplorerView.MEMENTO_LAST_ACTIVE_FILE_RESOURCE];
		}

		super.shutdown();
	}

	public dispose(): void {
		if (this.toolBar) {
			this.toolBar.dispose();
		}

		super.dispose();
	}
}


text:
using System;
using System.Collections;
using System.Reflection;
using NUnit.Core;
using NUnit.Core.Extensibility;

namespace NUnit.Util
{
	/// <summary>
	/// Summary description for AddinRegistry.
	/// </summary>
	public class AddinRegistry : MarshalByRefObject, IAddinRegistry, IService
    {
        #region Instance Fields
        private ArrayList addins = new ArrayList();
		#endregion

		#region IAddinRegistry Members

		public void Register(Addin addin)
		{
			addins.Add( addin );
		}

		public  IList Addins
		{
			get
			{
				return addins;
			}
		}

        public bool IsAddinRegistered(string name)
        {
            return FindAddinByName(name) != null;
        }

		public void SetStatus( string name, AddinStatus status, string message )
		{
            Addin addin = FindAddinByName(name);
            if (addin != null)
            {
                addin.Status = status;
                addin.Message = message;
            }
        }

        private Addin FindAddinByName(string name)
        {
            foreach (Addin addin in addins)
                if (addin.Name == name)
                    return addin;

            return null;
        }
		#endregion

		#region IService Members
		public void InitializeService()
		{
		}

		public void UnloadService()
		{
		}
		#endregion

        #region InitializeLifetimeService
        public override object InitializeLifetimeService()
        {
            return null;
        }
        #endregion
    }
}


text:
package com.questionnaire.ssm.module.userManage.controller;

import com.questionnaire.ssm.module.global.constant.CONSTANT;
import com.questionnaire.ssm.module.global.util.DownloadPicUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by 郑晓辉 on 2017/5/4.
 * Description:
 */
@Controller
@RequestMapping(value = "/userPic")
public class UserPicController {

    @GetMapping("/getUserPic")

    public ResponseEntity<byte[]> getUserPic(String userPicAddr) throws Exception {
        return DownloadPicUtil.download(CONSTANT.getUserPicturePath(), userPicAddr);
    }
}


text:
package cmd

import (
	"flag"
	"fmt"
	"os"

	"github.com/driusan/dgit/git"
)

func Clone(c *git.Client, args []string) error {
	flags := flag.NewFlagSet("clone", flag.ExitOnError)
	flags.SetOutput(flag.CommandLine.Output())
	flags.Usage = func() {
		flag.Usage()
		fmt.Fprintf(flag.CommandLine.Output(), "\n\nOptions:\n")
		flags.PrintDefaults()
	}

	opts := git.CloneOptions{}
	initOpts := git.InitOptions{}
	flags.BoolVar(&initOpts.Quiet, "quiet", false, "Operate quietly")
	flags.BoolVar(&initOpts.Quiet, "q", false, "Alias for --quiet")
	flags.BoolVar(&initOpts.Bare, "bare", false, "Make a bare Git repository.")
	template := ""
	flags.StringVar(&template, "template", "", "Specify the directory from which templates will be used.")

	// These flags can be moved out of these lists and below as proper flags as they are implemented
	for _, bf := range []string{"l", "s", "no-hardlinks", "n", "mirror", "dissociate", "single-branch", "no-single-branch", "no-tags", "shallow-submodules", "no-shallow-submodules"} {
		flags.Var(newNotimplBoolValue(), bf, "Not implemented")
	}
	for _, sf := range []string{"o", "b", "u", "reference", "separate-git-dir", "depth", "recurse-submodules", "jobs"} {
		flags.Var(newNotimplStringValue(), sf, "Not implemented")
	}

	flags.Parse(args)

	if template != "" {
		initOpts.Template = git.File(template)
	}

	opts.InitOptions = initOpts
	var repoid git.Remote
	var dirName git.File
	// TODO: This argument parsing should be smarter and more
	// in line with how cgit does it.
	switch flags.NArg() {
	case 0:
		flags.Usage()
		os.Exit(2)
	case 1:
		repoid = git.Remote(flags.Arg(0))
	case 2:
		repoid = git.Remote(flags.Arg(0))
		dirName = git.File(flags.Arg(1))
	default:
		repoid = git.Remote(flags.Arg(0))
		dirName = git.File(flags.Arg(1))
	}
	return git.Clone(opts, repoid, dirName)
}


text:
package com.adaptris.core.jms.activemq;

import static com.adaptris.core.PortManager.nextUnusedPort;
import static com.adaptris.core.PortManager.release;
import static com.adaptris.core.jms.JmsConfig.DEFAULT_PAYLOAD;
import static com.adaptris.core.jms.JmsConfig.DEFAULT_TTL;
import static com.adaptris.core.jms.JmsConfig.HIGHEST_PRIORITY;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.naming.Context;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.jndi.ActiveMQInitialContextFactory;
import org.apache.activemq.store.memory.MemoryPersistenceAdapter;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.AdaptrisMessageFactory;
import com.adaptris.core.jms.FailoverJmsConnection;
import com.adaptris.core.jms.JmsConnection;
import com.adaptris.core.jms.JmsConstants;
import com.adaptris.core.jms.jndi.StandardJndiImplementation;
import com.adaptris.core.stubs.ExternalResourcesHelper;
import com.adaptris.util.GuidGenerator;
import com.adaptris.util.IdGenerator;
import com.adaptris.util.KeyValuePair;
import com.adaptris.util.PlainIdGenerator;

public class EmbeddedActiveMq {

  private static final String DEF_URL_PREFIX = "tcp://localhost:";
  private static Logger log = Logger.getLogger(EmbeddedActiveMq.class);
  private BrokerService broker = null;
  private String brokerName;
  private File brokerDataDir;
  private Integer port;

  private static IdGenerator nameGenerator;
  static {
    try {
      nameGenerator = new GuidGenerator();
    }
    catch (Exception e) {
      nameGenerator = new PlainIdGenerator("-");
    }
  }

  public EmbeddedActiveMq() throws Exception {
    brokerName = createSafeUniqueId(this);
    port = nextUnusedPort(61616);
  }

  public String getName() {
    return brokerName;
  }

  public void start() throws Exception {
    brokerDataDir = createTempFile(true);
    broker = createBroker();
    broker.start();
    while (!broker.isStarted()) {
      Thread.sleep(100);
    }
  }

  public BrokerService createBroker() throws Exception {
    BrokerService br = new BrokerService();
    br.setBrokerName(brokerName);
    br.addConnector(DEF_URL_PREFIX + port);
    br.setUseJmx(false);
    br.setDeleteAllMessagesOnStartup(true);
    br.setDataDirectoryFile(brokerDataDir);
    br.setPersistent(false);
    br.setPersistenceAdapter(new MemoryPersistenceAdapter());
    br.getSystemUsage().getMemoryUsage().setLimit(1024L * 1024 * 20);
    br.getSystemUsage().getTempUsage().setLimit(1024L * 1024 * 20);
    br.getSystemUsage().getStoreUsage().setLimit(1024L * 1024 * 20);
    br.getSystemUsage().getJobSchedulerUsage().setLimit(1024L * 1024 * 20);
    return br;
  }

  private File createTempFile(boolean isDir) throws IOException {
    File result = File.createTempFile("AMQ-", "");
    result.delete();
    if (isDir) {
      result.mkdirs();
    }
    return result;
  }

  public void destroy() {
    new Thread(new Runnable() {

      @Override
      public void run() {
        try {
          stop();
          release(port);
        }
        catch (Exception e) {

        }
      }
    }).start();
  }

  public void stop() throws Exception {
    if (broker != null) {
      broker.stop();
      broker.waitUntilStopped();
      FileUtils.deleteDirectory(brokerDataDir);
    }
  }

  public JmsConnection getJmsConnection() {
    return applyCfg(new JmsConnection(), new BasicActiveMqImplementation(), false);
  }

  public JmsConnection getJmsConnection(BasicActiveMqImplementation impl) {
    return applyCfg(new JmsConnection(), impl, false);
  }

  public JmsConnection getJmsConnection(BasicActiveMqImplementation impl, boolean useTcp) {
    return applyCfg(new JmsConnection(), impl, useTcp);
  }

  private JmsConnection applyCfg(JmsConnection con, BasicActiveMqImplementation impl, boolean useTcp) {
    if (useTcp) {
      impl.setBrokerUrl("tcp://localhost:" + port);
    }
    else {
      impl.setBrokerUrl("vm://" + getName());
    }
    con.setClientId(createSafeUniqueId(impl));
    con.setVendorImplementation(impl);
    return con;
  }

  public FailoverJmsConnection getFailoverJmsConnection(boolean isPtp) throws Exception {
    FailoverJmsConnection result = new FailoverJmsConnection();
    if (!isPtp) {
      JmsConnection c = new JmsConnection(new BasicActiveMqImplementation(DEF_URL_PREFIX + "9999"));
      result.addConnection(c);
      result.addConnection(getJmsConnection(new BasicActiveMqImplementation(), true));
    }
    else {
      JmsConnection c = new JmsConnection(new BasicActiveMqImplementation(DEF_URL_PREFIX + "9999"));
      result.addConnection(c);
      result.addConnection(getJmsConnection(new BasicActiveMqImplementation(), true));
    }
    return result;
  }

  public JmsConnection getJndiPasConnection(StandardJndiImplementation jv, boolean useJndiOnly, String queueName, String topicName) {
    JmsConnection result = new JmsConnection();
    StandardJndiImplementation jndi = applyCfg(jv, useJndiOnly, queueName, topicName);
    jndi.setJndiName("topicConnectionFactory");
    result.setVendorImplementation(jndi);
    result.setClientId(createSafeUniqueId(jndi));

    return result;
  }

  public JmsConnection getJndiPtpConnection(StandardJndiImplementation jv, boolean useJndiOnly, String queueName, String topicName) {
    JmsConnection result = new JmsConnection();
    StandardJndiImplementation jndi = applyCfg(jv, useJndiOnly, queueName, topicName);
    jndi.setJndiName("queueConnectionFactory");
    result.setVendorImplementation(jndi);
    result.setClientId(createSafeUniqueId(jndi));
    return result;
  }

  private StandardJndiImplementation applyCfg(StandardJndiImplementation jndi, boolean useJndiOnly, String queueName,
                                              String topicName) {
    jndi.getJndiParams().addKeyValuePair(new KeyValuePair(Context.PROVIDER_URL, DEF_URL_PREFIX + port));
    jndi.getJndiParams().addKeyValuePair(
        new KeyValuePair(Context.INITIAL_CONTEXT_FACTORY, ActiveMQInitialContextFactory.class.getName()));
    jndi.getJndiParams().addKeyValuePair(
        new KeyValuePair("connectionFactoryNames", "connectionFactory, queueConnectionFactory, topicConnectionFactory"));
    jndi.getJndiParams().addKeyValuePair(new KeyValuePair("queue." + queueName, queueName));
    jndi.getJndiParams().addKeyValuePair(new KeyValuePair("topic." + topicName, topicName));
    if (useJndiOnly) {
      jndi.setUseJndiForQueues(true);
      jndi.setUseJndiForTopics(true);
    }
    return jndi;
  }

  public static AdaptrisMessage createMessage(AdaptrisMessageFactory fact) {
    AdaptrisMessage msg = fact == null ? AdaptrisMessageFactory.getDefaultInstance().newMessage(DEFAULT_PAYLOAD) : fact
        .newMessage(DEFAULT_PAYLOAD);
    msg.addMetadata(JmsConstants.JMS_PRIORITY, String.valueOf(HIGHEST_PRIORITY));
    msg.addMetadata(JmsConstants.JMS_DELIVERY_MODE, String.valueOf(DeliveryMode.NON_PERSISTENT));
    msg.addMetadata(JmsConstants.JMS_EXPIRATION, String.valueOf(DEFAULT_TTL));
    return msg;
  }

  public static AdaptrisMessage addBlobUrlRef(AdaptrisMessage msg, String key) {
    msg.addMetadata(key, ExternalResourcesHelper.createUrl());
    return msg;
  }

  public ActiveMQConnection createConnection() throws JMSException {
    ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory("vm://" + getName());
    return (ActiveMQConnection) fact.createConnection();
  }

  public long messagesOnQueue(String queueName) throws Exception {
    Broker b = broker.getBroker();

    Map<ActiveMQDestination, Destination> map = b.getDestinationMap();
    for (ActiveMQDestination dest : map.keySet()) {
      if (dest.isQueue() && dest.getPhysicalName().equals(queueName)) {
        Destination queueDest = map.get(dest);
        return queueDest.getDestinationStatistics().getMessages().getCount();
        // return queueDest.browse().length;
      }
    }
    return -1;
  }

  public static String createSafeUniqueId(Object o) {
    return nameGenerator.create(o).replaceAll(":", "").replaceAll("-", "");
  }

}


text:
#import "common.h"
#import "IFSM3UPlaylist.h"
#import "NSObject+FUSEOFS.h"
#import "IFSiTunesPlaylist.h"
#import "IFSiTunesTrack.h"
#import "IFSFormatter.h"

@implementation IFSM3UPlaylist

static BOOL useM3U8 = NO;
static NSString *fileExt = nil;

+ (void)initialize {
	static BOOL didInit = NO;
	if (didInit) return;
	didInit = YES;

	NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
	useM3U8 = [ud boolForKey:@"UseM3U8"];
	fileExt = [ud stringForKey:@"M3UPlaylistFileExtension"];
}

- (id)initWithPlaylist:(IFSiTunesPlaylist *)_playlist
  useRelativePaths:(BOOL)_useRelativePaths
{
	self = [super init];
	if (self) {
		self->playlist = [_playlist retain];
		self->useRelativePaths = _useRelativePaths;
	}
	return self;
}

- (void)dealloc {
	[self->playlist release];
	[super dealloc];
}

/* Properties */

- (NSString *)name {
	return [self->playlist name];
}
- (NSString *)fileName {
	return [[[self name] stringByAppendingPathExtension:[self fileExtension]]
			             properlyEscapedFSRepresentation];
}
- (NSString *)fileExtension {
	if (fileExt)
		return fileExt;
	return useM3U8 ? @"m3u8" : @"m3u";
}
- (NSStringEncoding)fileEncoding {
	return useM3U8 ? NSUTF8StringEncoding : NSWindowsCP1252StringEncoding;
}

- (NSArray *)tracks {
	return self->useRelativePaths ? [self->playlist tracks]
	                              : [self->playlist allTracks];
}

/* FUSEOFS */

- (BOOL)isContainer {
	return NO;
}
- (BOOL)isMutable {
	return NO;
}

- (NSDictionary *)fileAttributes {
	NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithCapacity:5];
	[attrs setObject:[self->playlist modificationDate]
		   forKey:NSFileCreationDate];
	[attrs setObject:[self->playlist modificationDate]
		   forKey:NSFileModificationDate];
	[attrs setObject:NSFileTypeRegular forKey:NSFileType];
	NSNumber *perm = [NSNumber numberWithInt:[self isMutable] ? 0666 : 0444];
	[attrs setObject:perm forKey:NSFilePosixPermissions];
	return attrs;
}

- (NSData *)fileContents {
	NSString *fmt = [[NSUserDefaults standardUserDefaults]
									  stringForKey:@"M3UTrackFormat"];
	IFSFormatter *formatter = [[IFSFormatter alloc]
									                    initWithFormatString:fmt];

	NSMutableString *rep = [[NSMutableString alloc] init];
	[rep appendString:@"#EXTM3U\n"];

	NSArray *tracks = [self tracks];
	NSUInteger i, count = [tracks count];
	for (i = 0; i < count; i++) {
		IFSiTunesTrack *track =  [tracks objectAtIndex:i];
		NSString *title = [formatter stringValueByFormattingObject:track];
		[rep appendFormat:@"#EXTINF:-1,%@\n", title];

		NSURL *url = [track url];
		NSString *location;

		if ([url isFileURL]) {
			if (!self->useRelativePaths)
				location = [url path];
			else
				location = [[self->playlist trackNames] objectAtIndex:i];
		}
		else {
			location = [url description];
		}
		[rep appendString:location];
		[rep appendString:@"\n"];
	}
	NSData *d = [rep dataUsingEncoding:[self fileEncoding]];
	[rep release];
	[formatter release];
	return d;
}

@end


text:
/**
 * \file GeometryCore.cpp
 *
 * \author Volker Ahlers\n
 *         volker.ahlers@hs-hannover.de
 */

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

#include <cassert>
#include "GeometryCore.h"
#include "RenderState.h"
#include "scg_utilities.h"

namespace scg {

GeometryCore::GeometryCore(GLenum primitiveType, DrawMode drawMode)
    : primitiveType_(primitiveType), drawMode_(drawMode), vao_(0),
      vboIndex_(0), nElements_(0) {
  switch(drawMode_) {
  case DrawMode::ARRAYS:
    drawFunc_ = std::bind(&glDrawArrays, std::placeholders::_1, 0, std::placeholders::_2);
    break;
  case DrawMode::ELEMENTS:
    drawFunc_ = std::bind(&glDrawElements, std::placeholders::_1, std::placeholders::_2,
        GL_UNSIGNED_INT, static_cast<const GLvoid*>(nullptr));
    break;
  default:
    assert(!"Unknown drawMode [GeometryCore::GeometryCore()]");
    break;
  }
  glGenVertexArrays(1, &vao_);

  assert(!checkGLError());
}

GeometryCore::~GeometryCore() {
  if (isGLContextActive()) {
    for (auto vbo : vboAttributes_) {
      glDeleteBuffers(1, &vbo);
    }
    glDeleteBuffers(1, &vboIndex_);
    glDeleteVertexArrays(1, &vao_);
  }
}

GeometryCoreSP GeometryCore::create(GLenum primitiveType, DrawMode drawMode) {
  return std::make_shared<GeometryCore>(primitiveType, drawMode);
}

GeometryCore* GeometryCore::addAttributeData(GLuint location, const GLfloat* data, GLsizeiptr size, GLint dim, GLenum usage) {
  glBindVertexArray(vao_);
  assert(glIsVertexArray(vao_));
  GLuint vbo = 0;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  assert(glIsBuffer(vbo));
  vboAttributes_.push_back(vbo);
  glBufferData(GL_ARRAY_BUFFER, size, data, usage);
  if (drawMode_ == DrawMode::ARRAYS && nElements_ == 0) {
    nElements_ = size / (dim * sizeof(GLfloat));
  }
  glVertexAttribPointer(location, dim, GL_FLOAT, GL_FALSE, 0, static_cast<const GLvoid*>(0));
  glEnableVertexAttribArray(location);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);

  assert(!checkGLError());
  return this;
}

GeometryCore* GeometryCore::setElementIndexData(const GLuint* data, GLsizeiptr size, GLenum usage) {
  glBindVertexArray(vao_);
  assert(glIsVertexArray(vao_));
  glGenBuffers(1, &vboIndex_);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIndex_);
  assert(glIsBuffer(vboIndex_));
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, usage);
  if (drawMode_ == DrawMode::ELEMENTS) {
    nElements_ = size / sizeof(GLuint);
  }
  // Note: GL_ELEMENT_ARRAY_BUFFER has to be kept bound
  glBindVertexArray(0);

  assert(!checkGLError());
  return this;
}

int GeometryCore::getNTriangles() const {
  int result;
  switch (primitiveType_) {
  case GL_TRIANGLES:
    result = nElements_ / 3;
    break;
  case GL_TRIANGLE_FAN:
  case GL_TRIANGLE_STRIP:
    result = nElements_ - 2;
    break;
  default:
    result = 0;
    break;
  }
  return result;
}

void GeometryCore::render(RenderState* renderState) {
  // pass matrices and other state variables to shader
  renderState->passToShader();

  // draw primitives
  glBindVertexArray(vao_);
  assert(glIsVertexArray(vao_));
  assert(drawFunc_ != nullptr);
  drawFunc_(primitiveType_, nElements_);
  glBindVertexArray(0);

  assert(!checkGLError());
}

} /* namespace scg */


text:
layout:  post
title:  Code Quality Basics - What Is Code Coverage?
date:    2019-11-14 12:31:19
summary: In this article, we find out what code coverage is, and how we keep track of it.
categories: SwCodeQuality
permalink:  /code-quality-what-is-code-coverage
image: /images/design-category.png
---

In this article, we find out what code coverage is, and how we keep track of it.

### You will learn
- What Is Code Coverage?
- How do you measure Code Coverage?
- How can you ensure that you have great unit tests?
- How do you ensure that you have great asserts in tests in addition to code coverage?
- How can ensure that Code Coverage standards are Adhered to?

### Article Series

This is fifth article in a series of 6 articles on important code quality terminology:
- [1 - What Is Technical Debt?](/introduction-to-technical-debt){:target='_blank'}
- [2 - What Is Readability Of Code?](/code-quality-basics-introduction-to-readability-of-code){:target='_blank'}
- [3 - What Is Code Complexity?](/code-quality-what-is-code-complexity){:target='_blank'}
- [4 - What Is Code Duplication?](/code-quality-what-is-code-duplication){:target='_blank'}
- [5 - What Is Code Coverage?](/code-quality-what-is-code-coverage){:target='_blank'}
- [6 - What Is Legacy Code?](/introduction-to-legacy-code){:target='_blank'}

### What Is Code Coverage?

#### Unit Tests Are Important

A prerequisite for great code is having a set of great unit tests.

Adhering to test driven development leads us to create great code.

TDD ensures we have great low level design, and the set of unit tests we write tend to be reliable.

#### Understanding Code Coverage

The result of great unit tests is great **code coverage**. Code coverage is a measure of what percentage of the lines of source code that are covered by unit tests.

For example, if your project has 1000 lines of source code, unit tests cover 900 lines, then the code coverage of your application is 90%. Typically, 85-90% is considered to be good code coverage.

### Exploring Code Coverage

Have a look at the snapshot of the SonarQube Dashboard:

![image info](images/Capture-074-02.png)

The project being analyzed is being reported to have a code coverage of 97.1%. This means 97.1% of the source code is being covered by unit tests execution. That's awesome.

You can also see a ring beside the number estimate, as well as a shaded graph as the background. The project started off with approximately 80% coverage, and slowly built it up to the present figure.

When you click on the link, you can see several source files, and their individual coverage:

![image info](images/Capture-074-03.png)

You can see that a few of the files do not have any unit test written for them at all. These are the files with 0% coverage.

Let's pick the file ListTreeImpl.java as an example:
![image info](images/Capture-074-04.png)

This file has a coverage of around 72.1%. When you look at the code inside the file, you will see several vertical green bars. These indicate block of code that are fully covered by unit tests. The lines in red indicate those code blocks that are not covered by unit tests:
![image info](images/Capture-074-05.png)

### Why Is Code Coverage Important?

Good unit tests can catch defects that could arise out of buggy code, even in the future! They are a kind of insurance policy for developers. These tests are automated, and keep running every time code is changed.

Code coverage is a good measure to identify if all scenarios are being unit tested.

#### Find Defects Early

The more number of tests you write, the less defects you will have in the future. Having great unit tests, gives you the confidence to refactor your code. Refactoring helps improve the design of the code over a period of time.

### Challenges With Code Coverage

Here are a few challenges one has to face while dealing with code coverage.

#### Writing Tests Just For Coverage

Many project teams make the mistake of having code coverage as a direct measure. If the focus is only on the number of lines covered by unit tests, the quality of tests could get neglected.

Code coverage needs to be treated just as a result of great unit tests.

Having great code coverage does not mean you have great unit tests. If you end up writing tests that don't check the business logic, but only increase the lines of code covered, the purpose is defeated.

The focus needs to be on a combination of the quality of the unit tests written, plus the number of lines of code covered.

#### Dealing With Legacy Code

In general, legacy code components are not loosely coupled, and hence writing unit tests for them becomes quite a challenge. You might need to refactor code to enable you to write unit tests.

Most of the old frameworks - mainly the web and database ones - are not designed to be unit tested.

### Measuring Code Coverage

#### Use Sonar

SonarQube is one of the most popular static analysis tools that is used to measure code coverage.

It is also possible to connect to SonarQube from an Eclipse plugin, and look at the measures from an Eclipse view itself.

#### Use IDE Plugins

You can use Eclipse IDE plugins such as Cobertura and EclEmma to measure code coverage.

The IntelliJ IDE has in-built support to measure an application's code coverage.

### Best Practices For Code Coverage

#### Include Coverage In Definition Of Done

Make sure that you constantly review your code coverage measures at the end of each sprint. Also ensure that the quality of asserts are reviewed.

#### Measure Coverage From Day One

You need to be committed to measuring code coverage from the day of inception of the project. For that, you write unit tests for your code from the point where you start the prototype, and when you start developing the vertical slice as well.

Do check out our video on the same topic:

[![image info](images/Capture-074-01.png)](https://www.youtube.com/watch?v=Ra42js3AXIQ)

### Summary

Code coverage measures the lines of code covered by unit tests. Having good unit tests is important for any project, as they act as a safety net against defects in the future. Code Coverage can be measured by tools such as SonarQube, or common IDE plugins.


text:
/**
 *
 */
package com.gemstone.gemfire.internal.cache;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.TXJUnitTest;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.EntryNotFoundException;
import com.gemstone.gemfire.cache.PartitionAttributesFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.query.QueryException;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.InternalRegionArguments;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;

/**
 * @author sbawaska
 *
 */
@Category(IntegrationTest.class)
public class PRTXJUnitTest extends TXJUnitTest {

  /* (non-Javadoc)
   * @see com.gemstone.gemfire.TXTest#createRegion()
   */
  @Override
  protected void createRegion() throws Exception {
    AttributesFactory af = new AttributesFactory();
    af.setConcurrencyChecksEnabled(false);  // test validation expects this behavior
    af.setPartitionAttributes(new PartitionAttributesFactory()
      .setTotalNumBuckets(3).create());
    //this.region = this.cache.createRegion("PRTXJUnitTest", af.create());
    this.region = new PRWithLocalOps("PRTXJUnitTest", af.create(),
        null, this.cache, new InternalRegionArguments()
        .setDestroyLockFlag(true).setRecreateFlag(false)
        .setSnapshotInputStream(null).setImageTarget(null));
    ((PartitionedRegion)this.region).initialize(null, null, null);
    ((PartitionedRegion)this.region).postCreateRegion();
    this.cache.setRegionByPath(this.region.getFullPath(), (LocalRegion)this.region);
  }
  /* (non-Javadoc)
   * @see com.gemstone.gemfire.TXTest#checkUserAttributeConflict(com.gemstone.gemfire.internal.cache.TXManagerImpl)
   */
  @Override
  protected void checkUserAttributeConflict(CacheTransactionManager txMgrImpl) {
  }

  /* (non-Javadoc)
   * @see com.gemstone.gemfire.TXTest#checkSubRegionCollecection(com.gemstone.gemfire.internal.cache.LocalRegion)
   */
  @Override
  protected void checkSubRegionCollecection(Region reg1) {
  }
  @Override
  @Ignore
  @Test
  public void testTXAndQueries() throws CacheException, QueryException {
    // TODO fix this?
  }
  @Override
  @Ignore
  @Test
  public void testCollections() throws CacheException {
    // TODO make PR iterators tx aware
  }
  @Override
  @Ignore
  @Test
  public void testTxAlgebra() throws CacheException {
    // TODO Auto-generated method stub
  }
  @Test
  public void testTxId() {
    AttributesFactory<Integer, String> af = new AttributesFactory<Integer, String>();
    af.setPartitionAttributes(new PartitionAttributesFactory<String, Integer>()
        .setTotalNumBuckets(2).create());
    Region<String, Integer> r = this.cache.createRegion("testTxId", af.create());
    r.put("one", 1);
    CacheTransactionManager mgr = this.cache.getTxManager();
    mgr.begin();
    r.put("two", 2);
    mgr.getTransactionId();
    mgr.rollback();
  }

  private static class PRWithLocalOps extends PartitionedRegion {

    /**
     * @param regionname
     * @param ra
     * @param parentRegion
     * @param cache
     * @param internalRegionArgs
     */
    public PRWithLocalOps(String regionname, RegionAttributes ra,
        LocalRegion parentRegion, GemFireCacheImpl cache,
        InternalRegionArguments internalRegionArgs) {
      super(regionname, ra, parentRegion, cache, internalRegionArgs);
    }

    /* (non-Javadoc)
     * @see com.gemstone.gemfire.internal.cache.PartitionedRegion#localDestroy(java.lang.Object, java.lang.Object)
     */
    @Override
    public void localDestroy(Object key, Object callbackArgument)
        throws EntryNotFoundException {
      super.destroy(key, callbackArgument);
    }
    /* (non-Javadoc)
     * @see com.gemstone.gemfire.internal.cache.PartitionedRegion#localInvalidate(java.lang.Object, java.lang.Object)
     */
    @Override
    public void localInvalidate(Object key, Object callbackArgument)
        throws EntryNotFoundException {
      super.invalidate(key, callbackArgument);
    }
    /* (non-Javadoc)
     * @see com.gemstone.gemfire.internal.cache.PartitionedRegion#localInvalidateRegion(java.lang.Object)
     */
    @Override
    public void localInvalidateRegion(Object callbackArgument) {
      super.invalidateRegion(callbackArgument);
    }
  }
}


text:
namespace ImageViewerDll
{
	using System;
	using System.Collections;
	using System.Runtime.Serialization;

	[Serializable]
	public class QuickSaveFolderCollection : CollectionBase, ISerializable
	{
		/// <summary>
		/// Žw'肵'½ƒCƒ"ƒfƒbƒNƒX'Ì—v'f'ðŽæ"¾
		/// </summary>
		public QuickSaveFolderItem this[int index] {
			set {
				List[index] = value;
			}
			get {
				return (QuickSaveFolderItem)List[index];
			}
		}

		/// <summary>
		/// QuickSaveFolderCollectionƒNƒ‰ƒX'̃Cƒ"ƒXƒ^ƒ"ƒX'ð‰Šú‰»
		/// </summary>
		public QuickSaveFolderCollection()
		{
		}

		public QuickSaveFolderCollection(SerializationInfo info, StreamingContext context)
		{
			ArrayList arrayList =
				(ArrayList)info.GetValue(GetType().Name, typeof(ArrayList));

			foreach (object obj in arrayList)
				if (obj != null) InnerList.Add(obj);
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			info.AddValue(GetType().Name, InnerList);
		}

		/// <summary>
		/// item'ðƒRƒŒƒNƒVƒ‡ƒ"'Ì––"ö'ɒljÁ
		/// </summary>
		/// <param name="item"></param>
		/// <returns></returns>
		public int Add(QuickSaveFolderItem item)
		{
			return List.Add(item);
		}

		/// <summary>
		/// item'ðƒRƒŒƒNƒVƒ‡ƒ""à'©'çíœ
		/// </summary>
		/// <param name="item"></param>
		public void Remove(QuickSaveFolderItem item)
		{
			List.Remove(item);
		}
	}
}


text:
ROOT = ../../../../..

DIR = Pegasus/ProviderManager2/CMPIR/tcpcomm

include $(ROOT)/mak/config.mak

ifeq ($(PEGASUS_PLATFORM),ZOS_ZSERIES_IBM)
    CXX = cc
    FLAGS += -W"c,SSCOMM"
endif

EXTRA_INCLUDES = $(SYS_INCLUDES) -I ..

LOCAL_DEFINES = -DPEGASUS_SERVER_INTERNAL -DPEGASUS_INTERNALONLY -DPEGASUS_CMPI_TCP_INTERNAL

LIBRARY = CMPIRTCPComm

LIBRARIES = CMPIRProxyProvider

SOURCES = \
   tcpcomm_proxy.c \
   proxy_attach.c \
   ../serialization.c \
   ../socketcomm.c \
   ../io.c \
   ../ip.c \

include $(ROOT)/mak/library.mak


text:
//  Estimote Fleet Management SDK
//  Copyright © 2015 Estimote. All rights reserved.

#import <Foundation/Foundation.h>
#import "ESTBeaconOperationProtocol.h"
#import "ESTSettingOperation.h"
#import "ESTSettingIBeaconSecureUUIDPeriodScaler.h"

NS_ASSUME_NONNULL_BEGIN

/**
 *  ESTBeaconOperationIBeaconSecureUUIDPeriodScaler allows to create read/write operations for iBeacon SecureUUIDPeriodScaler setting of a device.
 *  The Secure UUID rotation period is equal to 2^scaler seconds.
 */
@interface ESTBeaconOperationIBeaconSecureUUIDPeriodScaler : ESTSettingOperation <ESTBeaconOperationProtocol>

/**
 *  Method allows to create read operation for iBeacon SecureUUIDPeriodScaler setting.
 *
 *  @param completion Block invoked when the operation is complete.
 *
 *  @return Initialized object.
 */
+ (instancetype)readOperationWithCompletion:(ESTSettingIBeaconSecureUUIDPeriodScalerCompletionBlock)completion;

/**
 *  Method allows to create write operation for iBeacon SecureUUIDPeriodScaler setting.
 *
 *  @param setting    Setting to be written to a device.
 *  @param completion Block invoked when the operation is complete.
 *
 *  @return Initialized object.
 */
+ (instancetype)writeOperationWithSetting:(ESTSettingIBeaconSecureUUIDPeriodScaler *)setting completion:(ESTSettingIBeaconSecureUUIDPeriodScalerCompletionBlock)completion;

@end

NS_ASSUME_NONNULL_END


text:
from flask import Blueprint

base = Blueprint('base', __name__, template_folder='templates')


text:
___
Q1: What if I want to use other network backbones, such as ResNet [1], instead of only those provided ones (e.g., Xception)?

A: The users could modify the provided core/feature_extractor.py to support more network backbones.
___
Q2: What if I want to train the model on other datasets?

A: The users could modify the provided dataset/build_{cityscapes,voc2012}_data.py and dataset/segmentation_dataset.py to build their own dataset.
___
Q3: Where can I download the PASCAL VOC augmented training set?

A: The PASCAL VOC augmented training set is provided by Bharath Hariharan et al. [2] Please refer to their [website](http://home.bharathh.info/pubs/codes/SBD/download.html) for details and consider citing their paper if using the dataset.
___
Q4: Why the implementation does not include DenseCRF [3]?

A: We have not tried this. The interested users could take a look at Philipp Krähenbühl's [website](http://graphics.stanford.edu/projects/densecrf/) and [paper](https://arxiv.org/abs/1210.5644) for details.
___
Q5: What if I want to train the model and fine-tune the batch normalization parameters?

A: If given the limited resource at hand, we would suggest you simply fine-tune
from our provided checkpoint whose batch-norm parameters have been trained (i.e.,
train with a smaller learning rate, set `fine_tune_batch_norm = false`, and
employ longer training iterations since the learning rate is small). If
you really would like to train by yourself, we would suggest

1. Set `output_stride = 16` or maybe even `32` (remember to change the flag
`atrous_rates` accordingly, e.g., `atrous_rates = [3, 6, 9]` for
`output_stride = 32`).

2. Use as many GPUs as possible (change the flag `num_clones` in train.py) and
set `train_batch_size` as large as possible.

3. Adjust the `train_crop_size` in train.py. Maybe set it to be smaller, e.g.,
513x513 (or even 321x321), so that you could use a larger batch size.

4. Use a smaller network backbone, such as MobileNet-v2.

___
Q6: How can I train the model asynchronously?

A: In the train.py, the users could set `num_replicas` (number of machines for training) and `num_ps_tasks` (we usually set `num_ps_tasks` = `num_replicas` / 2). See slim.deployment.model_deploy for more details.
___
Q7: I could not reproduce the performance even with the provided checkpoints.

A: Please try running

```bash
# Run the simple test with Xception_65 as network backbone.
sh local_test.sh
```

or

```bash
# Run the simple test with MobileNet-v2 as network backbone.
sh local_test_mobilenetv2.sh
```

First, make sure you could reproduce the results with our provided setting.
After that, you could start to make a new change one at a time to help debug.
___
Q8: What value of `eval_crop_size` should I use?

A: Our model uses whole-image inference, meaning that we need to set `eval_crop_size` equal to `output_stride` * k + 1, where k is an integer and set k so that the resulting `eval_crop_size` is slightly larger the largest
image dimension in the dataset. For example, we have `eval_crop_size` = 513x513 for PASCAL dataset whose largest image dimension is 512. Similarly, we set `eval_crop_size` = 1025x2049 for Cityscapes images whose
image dimension is all equal to 1024x2048.
___

## References

1. **Deep Residual Learning for Image Recognition**

   Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun

   [[link]](https://arxiv.org/abs/1512.03385), In CVPR, 2016.

2. **Semantic Contours from Inverse Detectors**

   Bharath Hariharan, Pablo Arbelaez, Lubomir Bourdev, Subhransu Maji, Jitendra Malik

   [[link]](http://home.bharathh.info/pubs/codes/SBD/download.html), In ICCV, 2011.

3. **Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials**

   Philipp Krähenbühl, Vladlen Koltun

   [[link]](http://graphics.stanford.edu/projects/densecrf/), In NIPS, 2011.