text:
//
//  NSObject+UMShare.m
//  ProjectArchitecture
//
//  Created by ZM on 2018/7/31.
//  Copyright © 2018年 ZM. All rights reserved.
//

#import "NSObject+UMShare.h"
#import "UMShareManager.h"
#import "UMManager.h"
#import "UMConst.h"

@implementation NSObject (UMShare)

#pragma mark ======================"  使用测试  "==============================

- (void)share_Test {

    NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
    NSString* title = @"欢迎使用【友盟+】社会化组件U-Share";
    NSString* descr = @"欢迎使用【友盟+】社会化组件U-Share,SDK包最小,集成成本最低,助力您的产品开发、运营与推广!";

    UMSocialPlatformType platformType;
    //微信朋友圈
    platformType = UMSocialPlatformType_WechatTimeLine;
    //微信好友
    platformType = UMSocialPlatformType_WechatSession;
    //新浪微博
    platformType = UMSocialPlatformType_Sina;
    //qq空间
    platformType = UMSocialPlatformType_Qzone;

    if ([UMManager sharePlatformType:platformType]) { //是否安装对应App
        // 分享LinkCard(网页链接)
        [self shareWebPageToPlatformType:platformType
                              shareTitle:title
                                   descr:descr
                              webpageUrl:UMS_webpageUrl
                               thumImage:thumbURL completion:^(id data, NSError *error) {
                               }];
    }
}

#pragma mark - /************************  分享类型  **************************/

#pragma mark 2.2  分享文本
- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType
                      shareText:(NSString *)text
                     completion:(void (^)(id data, NSError *error) )completion
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = text;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        //回调
        completion(data,error);
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}

#pragma mark 2.3  分享图片
- (void)shareImageToPlatformType:(UMSocialPlatformType)platformType
                       thumImage:(id)thumImage
                      shareImage:(id)shareImage
                      completion:(void (^)(id data, NSError *error) )completion
{
    if ([UMManager sharePlatformType:platformType]) {
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
        //如果有缩略图,则设置缩略图
        shareObject.thumbImage = thumImage;
        [shareObject setShareImage:shareImage];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            //回调
            completion(data,error);
            if (error) {
                NSLog(@"************Share fail with error %@*********",error);
            }else{
                NSLog(@"成功 %@",data);
            }
        }];
    }
}

#pragma mark 2.4  分享图文(新浪支持,微信/QQ仅支持图或文本分享)
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
                              shareText:(NSString *)text
                              thumImage:(id)thumImage
                             shareImage:(id)shareImage
                             completion:(void (^)(id data, NSError *error) )completion
{
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = text;
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图,则设置缩略图
    shareObject.thumbImage = thumImage;
    [shareObject setShareImage:shareImage];
    //设置分享内容对象
    messageObject.shareObject = shareObject;
    __weak typeof(self) WSelf = self;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        //回调
        completion(data,error);
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            //错误处理
            [WSelf errorDeal:error toPlatformType:platformType];
        }else{
            NSLog(@"---> 分享回调_Response= %@ ",data);
            //成功处理
            [WSelf successDeal:data toPlatformType:platformType];
        }
    }];
}

#pragma mark 2.5  分享LinkCard(网页链接)
/**_shareimage 是UIImage格式,分享的图片
 * _contentStr 是NSString格式,分享文字内容
 * _shareurlStr 是NSString格式,分享的链接
 */
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
                        shareTitle:(NSString *)title
                             descr:(NSString *)descr
                        webpageUrl:(NSString *)webpageUrl
                         thumImage:(id)thumImage
                        completion:(void (^)(id data, NSError *error) )completion
{
    //    NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";

    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title
                                                                             descr:descr
                                                                         thumImage:thumImage];
    //设置网页地址
    shareObject.webpageUrl = webpageUrl;
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;

    __weak typeof(self) WSelf = self;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        //回调
        completion(data,error);
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            //错误处理
            [WSelf errorDeal:error toPlatformType:platformType];
        }else{
            NSLog(@"---> 分享回调_Response= %@ ",data);
            //成功处理
            [WSelf successDeal:data toPlatformType:platformType];
        }
    }];
}

#pragma mark 2.6  分享音乐
- (void)shareMusicToPlatformType:(UMSocialPlatformType)platformType
                      shareTitle:(NSString *)title
                           descr:(NSString *)descr
                       thumImage:(id)thumImage
                        musicUrl:(NSString *)musicUrl
                      completion:(UMShareCompletionHandler)completion
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建音乐内容对象
    UMShareMusicObject *shareObject = [UMShareMusicObject shareObjectWithTitle:title
                                                                         descr:descr
                                                                     thumImage:thumImage];
    //设置音乐网页播放地址
    shareObject.musicUrl = musicUrl;
    //shareObject.musicDataUrl = @"这里设置音乐数据流地址(如果有的话,而且也要看所分享的平台支不支持)";
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        //回调
        completion(data,error);
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}

#pragma mark 2.7  分享视频
- (void)shareVedioToPlatformType:(UMSocialPlatformType)platformType
                      shareTitle:(NSString *)title
                           descr:(NSString *)descr
                       thumImage:(id)thumImage
                        videoUrl:(NSString *)videoUrl
                      completion:(UMShareCompletionHandler)completion
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建视频内容对象
    UMShareVideoObject *shareObject = [UMShareVideoObject shareObjectWithTitle:title
                                                                         descr:descr
                                                                     thumImage:thumImage];
    //设置视频网页播放地址
    shareObject.videoUrl = videoUrl;
    //shareObject.videoStreamUrl = @"这里设置视频数据流地址(如果有的话,而且也要看所分享的平台支不支持)";

    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;

    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        //回调
        completion(data,error);
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}

#pragma mark 2.8  分享微信小程序
- (void)shareMiniProgramToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

    //    UMShareMiniProgramObject *shareObject = [UMShareMiniProgramObject shareObjectWithTitle:@"小程序标题" descr:@"小程序内容描述" thumImage:[UIImage imageNamed:@"icon"]];
    //    shareObject.webpageUrl = @"兼容微信低版本网页地址";
    //    shareObject.userName = @"小程序username,如 gh_3ac2059ac66f";
    //    shareObject.path = @"小程序页面路径,如 pages/page10007/page10007";
    //    messageObject.shareObject = shareObject;

    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);

            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        [self alertWithError:error];
    }];
}

#pragma mark 2.9  示例 分享文本到微信:
- (void)shareTextToWechat
{
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    messageObject.text = UM_text;

    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        NSString *message = nil;
        if (!error) {
            message = [NSString stringWithFormat:@"分享成功"];
        } else {
            message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"share"
                                                        message:message delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        [alert show];
    }];
}

#pragma mark - /************************  分享结果处理  **************************/

- (void)errorDeal:(NSError *)error toPlatformType:(UMSocialPlatformType)platformType
{
    NSLog(@"---> platformType=  %ld ",(long)platformType);
    NSLog(@"---> Share_fail_with_error=  %@ ",error);
    NSLog(@"---> localError=  %@ ",[error localizedDescription]);
    NSDictionary *errorDic = [NSDictionary dictionaryWithDictionary:[error userInfo]];
    NSLog(@"---> userInfo=  %@ \n message= %@",[error userInfo], errorDic[@"message"]);

    if ([errorDic[@"message"] isEqualToString:@"APP Not Install"]) {
        if (platformType==UMSocialPlatformType_Sina) {                  UMAlertView(@"未安装 新浪APP ");
        }else if (platformType==UMSocialPlatformType_WechatTimeLine){   UMAlertView(@"未安装 微信APP");
        }else if (platformType==UMSocialPlatformType_WechatSession){    UMAlertView(@"未安装 微信APP");
        }else if (platformType==UMSocialPlatformType_QQ){               UMAlertView(@"未安装 QQAPP");
        }else if (platformType==UMSocialPlatformType_Qzone){            UMAlertView(@"未安装 QQAPP");
        }
    }else if ([errorDic[@"message"] isEqualToString:@"QQ not support api"]) {
        UMAlertView(@"未安装 QQAPP");

    }else if ([errorDic[@"message"] isEqualToString:@"Operation is cancel"]) {
        [HHudProgress hudShowMsg:@"取消分享" delay:1.0 addSubview:nil];
    }else{
        UMAlertView(errorDic[@"message"]);
    }
}
- (void)successDeal:(id)data toPlatformType:(UMSocialPlatformType)platformType
{
    if ([data isKindOfClass:[UMSocialShareResponse class]]) {
        UMSocialShareResponse *resp = data;
        NSString* response = [NSString stringWithFormat:@"%@",resp.originalResponse];
        NSLog(@"---> 分享成功_Response= %@ ",response);
        if ([response isEqualToString:@"0"]) {
            //AlertView(@"分享成功");
        }
        //分享结果消息
        UMSocialLogInfo(@"response message is %@",resp.message);
        //第三方原始返回的数据
        UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
    }else{
        NSLog(@"---> 分享成功_data=  %@ ",data);
        UMSocialLogInfo(@"response data is %@",data);
    }
}

- (void)alertWithError:(NSError *)error
{
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"Share succeed"];
    }else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"Share fail with error code: %d\n%@",(int)error.code, str];
        }else{
            result = [NSString stringWithFormat:@"Share fail"];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"share" message:result delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"sure", @"确定")
                                          otherButtonTitles:nil];
    [alert show];
}

@end


text:
from django.test import TestCase
from django.test.utils import override_settings
from django.conf import settings
import django.contrib.staticfiles.finders
import django

import compressor.utils.staticfiles

from imp import reload

def get_apps_without_staticfiles(apps):
    return [x for x in apps if x != 'django.contrib.staticfiles']

def get_apps_with_staticfiles_using_appconfig(apps):
    return get_apps_without_staticfiles(apps) + [
        'django.contrib.staticfiles.apps.StaticFilesConfig',
    ]

class StaticFilesTestCase(TestCase):

    def test_has_finders_from_staticfiles(self):
        self.assertTrue(compressor.utils.staticfiles.finders is
                        django.contrib.staticfiles.finders)

    def test_has_finders_from_staticfiles_if_configured_per_appconfig(self):
        apps = get_apps_with_staticfiles_using_appconfig(
            settings.INSTALLED_APPS)
        try:
            with override_settings(INSTALLED_APPS=apps):
                reload(compressor.utils.staticfiles)
                self.assertTrue(compressor.utils.staticfiles.finders is
                                django.contrib.staticfiles.finders)
        finally:
            reload(compressor.utils.staticfiles)

    def test_finders_is_none_if_staticfiles_is_not_installed(self):
        apps = get_apps_without_staticfiles(settings.INSTALLED_APPS)
        try:
            with override_settings(INSTALLED_APPS=apps):
                reload(compressor.utils.staticfiles)
                self.assertTrue(compressor.utils.staticfiles.finders is None)
        finally:
            reload(compressor.utils.staticfiles)

redpajama_set_name: RedPajamaGithub


text:
module CLIUtils
  # A Validator to verify whether a Pref answer
  # is not a number.
  class NumberValidator < PrefValidator
    # Runs the Validator against the answer.
    # @param [Object] text The "text" to evaluate
    # @return [String]
    def validate(text)
      @is_valid = text.to_s =~ /\A[-+]?\d*\.?\d+\z/
      @message = "Response is not a number: #{ text }"
    end
  end
end


text:
#include "tensorflow/python/lib/core/float8.h"

#include <array>
#include <cmath>
#include <limits>
#include <locale>

// Place `<locale>` before <Python.h> to avoid a build failure in macOS.
#include <Python.h>

#include "absl/strings/str_cat.h"
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/python/lib/core/custom_float.h"
#include "tensorflow/python/lib/core/numpy.h"

namespace tensorflow {
namespace custom_float_internal {

namespace ufuncs {

template <typename T>
struct CopySignFloat8 {
  T operator()(T a, T b) {
    constexpr uint8_t kSignMask = static_cast<uint8_t>(1)
                                  << (sizeof(T) * 8 - 1);
    return Eigen::numext::bit_cast<T>(static_cast<uint8_t>(
        (Eigen::numext::bit_cast<uint8_t>(a) & ~kSignMask) |
        (Eigen::numext::bit_cast<uint8_t>(b) & kSignMask)));
  }
};

template <>
struct CopySign<float8_e4m3> : CopySignFloat8<float8_e4m3> {};

template <>
struct CopySign<float8_e5m2> : CopySignFloat8<float8_e5m2> {};

template <typename T>
struct NextAfterFloat8 {
  T operator()(T from, T to) {
    if (Eigen::numext::isnan(from) || Eigen::numext::isnan(to)) {
      return std::numeric_limits<T>::quiet_NaN();
    }
    uint8_t from_as_int = Eigen::numext::bit_cast<uint8_t>(from);
    uint8_t to_as_int = Eigen::numext::bit_cast<uint8_t>(to);
    if (from_as_int == to_as_int) {
      return to;
    }

    constexpr uint8_t kSignMask = static_cast<uint8_t>(1)
                                  << (sizeof(T) * 8 - 1);
    uint8_t from_abs = from_as_int & ~kSignMask;
    uint8_t to_abs = to_as_int & ~kSignMask;
    if (from_abs == 0) {
      if (to_abs == 0) {
        return to;
      } else {
        // Smallest subnormal signed like `to`.
        return Eigen::numext::bit_cast<T>(
            static_cast<uint8_t>((to_as_int & kSignMask) | 1));
      }
    }
    uint8_t from_sign = from_as_int & kSignMask;
    uint8_t to_sign = to_as_int & kSignMask;
    uint8_t magnitude_adjustment = (from_abs > to_abs || from_sign != to_sign)
                                       ? static_cast<uint8_t>(-1)
                                       : static_cast<uint8_t>(1);
    uint8_t out_int = from_as_int + magnitude_adjustment;
    return Eigen::numext::bit_cast<T>(out_int);
  }
};

template <>
struct NextAfter<float8_e4m3> : NextAfterFloat8<float8_e4m3> {};

template <>
struct NextAfter<float8_e5m2> : NextAfterFloat8<float8_e5m2> {};

// Since float8_e4m3 doesn't have `inf`, we need to modify to use `max`.
template <>
struct Spacing<float8_e4m3> {
  float8_e4m3 operator()(float8_e4m3 x) {
    CopySign<float8_e4m3> copysign;
    if (Eigen::numext::abs(x) == std::numeric_limits<float8_e4m3>::max()) {
      return copysign(std::numeric_limits<float8_e4m3>::quiet_NaN(), x);
    }
    float8_e4m3 away = copysign(std::numeric_limits<float8_e4m3>::max(), x);
    return NextAfter<float8_e4m3>()(x, away) - x;
  }
};

}  // namespace ufuncs

template <>
struct TypeDescriptor<float8_e4m3>
    : custom_float_internal::CustomFloatTypeDescriptor<float8_e4m3> {
  typedef float8_e4m3 T;
  static constexpr const char* kTypeName = "float8_e4m3";
  static constexpr const char* kTpDoc = "float8_e4m3 floating-point values";
  // We must register float8_e4m3 with a unique kind, because numpy
  // considers two types with the same kind and size to be equal.
  // The downside of this is that NumPy scalar promotion does not work with
  // float8 values.  Using 'V' to mirror bfloat16 vs float16.
  static constexpr char kNpyDescrKind = 'V';
  // TODO(phawkins): there doesn't seem to be a way of guaranteeing a type
  // character is unique.
  static constexpr char kNpyDescrType = '4';
  static constexpr char kNpyDescrByteorder = '=';
};

template <>
struct TypeDescriptor<float8_e5m2>
    : custom_float_internal::CustomFloatTypeDescriptor<float8_e5m2> {
  typedef float8_e5m2 T;
  static constexpr const char* kTypeName = "float8_e5m2";
  static constexpr const char* kTpDoc = "float8_e5m2 floating-point values";
  // Treating e5m2 as the natural "float" type since it is IEEE-754 compliant.
  static constexpr char kNpyDescrKind = 'f';
  // TODO(phawkins): there doesn't seem to be a way of guaranteeing a type
  // character is unique.
  static constexpr char kNpyDescrType = '5';
  static constexpr char kNpyDescrByteorder = '=';
};

}  // namespace custom_float_internal

namespace {

// Initializes the module.
bool Initialize() {
  ImportNumpy();
  import_umath1(false);

  custom_float_internal::Safe_PyObjectPtr numpy_str =
      custom_float_internal::make_safe(PyUnicode_FromString("numpy"));
  if (!numpy_str) {
    return false;
  }
  custom_float_internal::Safe_PyObjectPtr numpy =
      custom_float_internal::make_safe(PyImport_Import(numpy_str.get()));
  if (!numpy) {
    return false;
  }

  if (!custom_float_internal::RegisterNumpyDtype<float8_e4m3>(numpy.get())) {
    return false;
  }
  if (!custom_float_internal::RegisterNumpyDtype<float8_e5m2>(numpy.get())) {
    return false;
  }
  return true;
}

}  // namespace

bool RegisterNumpyFloat8e4m3() {
  if (custom_float_internal::TypeDescriptor<float8_e4m3>::Dtype() !=
      NPY_NOTYPE) {
    // Already initialized.
    return true;
  }
  if (!Initialize()) {
    if (!PyErr_Occurred()) {
      PyErr_SetString(PyExc_RuntimeError, "cannot load float8_e4m3 module.");
    }
    PyErr_Print();
    return false;
  }
  return true;
}

PyObject* Float8e4m3Dtype() {
  return reinterpret_cast<PyObject*>(
      custom_float_internal::TypeDescriptor<float8_e4m3>::type_ptr);
}

int Float8e4m3NumpyType() {
  return custom_float_internal::TypeDescriptor<float8_e4m3>::Dtype();
}

bool RegisterNumpyFloat8e5m2() {
  if (custom_float_internal::TypeDescriptor<float8_e5m2>::Dtype() !=
      NPY_NOTYPE) {
    // Already initialized.
    return true;
  }
  if (!Initialize()) {
    if (!PyErr_Occurred()) {
      PyErr_SetString(PyExc_RuntimeError, "cannot load float8_e5m2 module.");
    }
    PyErr_Print();
    return false;
  }
  return true;
}

PyObject* Float8e5m2Dtype() {
  return reinterpret_cast<PyObject*>(
      custom_float_internal::TypeDescriptor<float8_e5m2>::type_ptr);
}

int Float8e5m2NumpyType() {
  return custom_float_internal::TypeDescriptor<float8_e5m2>::Dtype();
}

}  // namespace tensorflow


text:
package com.android.tools.idea.navigator.nodes;

import com.google.common.collect.Lists;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.nodes.BaseProjectViewDirectoryHelper;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ContentFolder;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import com.intellij.ui.SimpleTextAttributes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.roots.ContentFolderScopes;

import java.util.Collection;
import java.util.List;

public class NonAndroidSourceTypeNode extends ProjectViewNode<Module> implements DirectoryGroupNode {
  private final NonAndroidSourceType mySourceType;

  public NonAndroidSourceTypeNode(@NotNull Project project,
                                  @NotNull Module module,
                                  @NotNull ViewSettings settings,
                                  @NotNull NonAndroidSourceType type) {
    super(project, module, settings);
    mySourceType = type;
  }

  @NotNull
  @Override
  public Collection<? extends AbstractTreeNode> getChildren() {
    List<VirtualFile> sourceFolders = getSourceFolders();
    List<AbstractTreeNode> children = Lists.newArrayListWithExpectedSize(sourceFolders.size());

    PsiManager psiManager = PsiManager.getInstance(myProject);
    for (VirtualFile file : sourceFolders) {
      PsiDirectory dir = psiManager.findDirectory(file);
      if (dir != null) {
        children.addAll(BaseProjectViewDirectoryHelper.getDirectoryChildren(dir, getSettings(), true));
      }
    }

    return children;
  }

  private List<VirtualFile> getSourceFolders() {
    ModuleRootManager rootManager = ModuleRootManager.getInstance(getValue());
    List<VirtualFile> folders = Lists.newArrayList();

    ContentEntry[] contentEntries = rootManager.getContentEntries();
    for (ContentEntry entry : contentEntries) {
      ContentFolder[] sources = entry.getFolders(ContentFolderScopes.of(mySourceType.rootType));
      for (ContentFolder folder : sources) {
        VirtualFile file = folder.getFile();
        if (file != null) {
          folders.add(file);
        }
      }
    }

    return folders;
  }

  @Override
  protected void update(PresentationData presentation) {
    presentation.addText(mySourceType.presentableName, SimpleTextAttributes.REGULAR_ATTRIBUTES);
    presentation.setPresentableText(mySourceType.presentableName);
    presentation.setIcon(mySourceType.icon);
  }

  @Override
  public boolean contains(@NotNull VirtualFile file) {
    for (VirtualFile folder : getSourceFolders()) {
      if (VfsUtilCore.isAncestor(folder, file, false)) {
        return true;
      }
    }

    return false;
  }

  @Nullable
  @Override
  public Comparable getSortKey() {
    return mySourceType;
  }

  @Nullable
  @Override
  public Comparable getTypeSortKey() {
    return mySourceType;
  }

  @Nullable
  @Override
  public String toTestString(@Nullable Queryable.PrintInfo printInfo) {
    return mySourceType.presentableName;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;

    NonAndroidSourceTypeNode that = (NonAndroidSourceTypeNode)o;

    if (mySourceType != that.mySourceType) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = super.hashCode();
    result = 31 * result + mySourceType.hashCode();
    return result;
  }

  @NotNull
  @Override
  public PsiDirectory[] getDirectories() {
    PsiManager psiManager = PsiManager.getInstance(myProject);
    List<VirtualFile> sourceFolders = getSourceFolders();
    List<PsiDirectory> psiDirectories = Lists.newArrayListWithExpectedSize(sourceFolders.size());

    for (VirtualFile f : sourceFolders) {
      PsiDirectory dir = psiManager.findDirectory(f);
      if (dir != null) {
        psiDirectories.add(dir);
      }
    }

    return psiDirectories.toArray(new PsiDirectory[psiDirectories.size()]);
  }
}


text:
var fs = require('fs');

fs.readFile('input.txt', 'utf8', function(error, data) {
  if (error) {
    console.error(error);
    return;
  }

  var lines = data.split("\n");
  var letters = lines.map(line => line.split("").map(letter => ({ [letter]: 1 })));
  var columnCounts = letters.reduce(function(left, right) {
    right.forEach(function(column, index) {
      if (typeof left[index] === 'undefined' || left[index] === null) {
        left[index] = {};
      }

      Object.keys(column).forEach(key => {
        if (left[index][key]) {
          left[index][key] += column[key];
        } else {
          left[index][key] = column[key];
        }
      });
    });

    return left;
  }, letters[0].map(_ => {}));

  var mostPopular = columnCounts.map(function(column) {
    var max = 0, maxKey = null;
    Object.keys(column).forEach(function(key) {
      if (maxKey === null || column[key] > max) max = column[key], maxKey = key;
    });
    return maxKey;
  });

  var leastPopular = columnCounts.map(function(column) {
    var min = 0, minKey = null;
    Object.keys(column).forEach(function(key) {
      if (minKey === null || column[key] < min) min = column[key], minKey = key;
    });
    return minKey;
  });

  console.log(mostPopular.join(""));
  console.log(leastPopular.join(""));
});


text:
#ifndef STATE_CHART_INTERNAL_TESTING_MOCK_EXECUTABLE_CONTENT_H_
#define STATE_CHART_INTERNAL_TESTING_MOCK_EXECUTABLE_CONTENT_H_

#include "statechart/internal/model/executable_content.h"

#include <gmock/gmock.h>

namespace state_chart {

class Runtime;

class MockExecutableContent : public model::ExecutableContent {
 public:
  MockExecutableContent() {
    using ::testing::_;
    using ::testing::Return;
    ON_CALL(*this, Execute(_)).WillByDefault(Return(true));
  }
  MockExecutableContent(const MockExecutableContent&) = delete;
  MockExecutableContent& operator=(const MockExecutableContent&) = delete;
  ~MockExecutableContent() override = default;

  MOCK_CONST_METHOD1(Execute, bool(Runtime*));
};

}  // namespace state_chart

#endif  // STATE_CHART_INTERNAL_TESTING_MOCK_EXECUTABLE_CONTENT_H_


text:
const helpers = require('../../helpers')

module.exports = {
  command: 'get-xunit-report <suite-result-id>',
  desc: 'Fetch an XML report (XUnit v2) for a suite result.',
  builder: {},
  handler: async function (argv) {
    const client = helpers.getClient(argv)
    const result = await client.getSuiteResultXUnit(argv.suiteResultId)
    console.log(result)

    process.exit(0)
  },
}


text:
<?php

namespace _ReSTA\preventwhisper;

use pocketmine\event\Listener;

use pocketmine\event\player\PlayerCommandPreprocessEvent;

use pocketmine\utils\TextFormat;

use pocketmine\Server;

use pocketmine\Player;

class PlayerListener implements Listener
{

	private $api;

	public function __construct(PreventWhisper $api)
	{
		$this->api = $api;
	}

	public function onPlayerCommand(PlayerCommandPreprocessEvent $event)
	{
		$cmd = explode(" ", $event->getMessage());

		$sender = $event->getPlayer();

		if($cmd[0] === "/tell")
		{
			$player = Server::getInstance()->getPlayer($cmd[1]);

			if($player instanceof Player)
			{

				if(!$event->isCancelled() && $this->api->isAdded($player))
				{
					$sender->sendMessage(TextFormat::RED . "You can't send whisper messages to " . $player->getName() . ". `" . $this->api->getMessage($player) . "`");

					$event->setCancelled();
				}
			}
		}
	}
}

?>


text:
import itertools
from srilm import *
import string
from clean_test_corpus import Clean

class NgramTest:
    def __init__(self, model_file, test_file):
        self.model_file = model_file
        self.test_file = test_file
        self.puncationlist = ["espsilon", ",COMMA", ".PERIOD"]
        self.n = initLM(4)
        self.fw=open("output.txt","w+")

    def length_of_sentence(self, sentence):
        count = len(sentence.split())
        return count

    def create_combinations(self, bigram):
        list1 = [bigram[0]]
        list1.append(bigram[1])
        list1.extend(self.puncationlist)
        combination_list = list(itertools.permutations(list1))
        #print combination_list

    def get_probability(self, ngram):

        length = self.length_of_sentence(ngram)

        if length>5:
            raise ValueError('The n value specified is greater than 5')
        p6 = getNgramProb(self.n, ngram,length)
        #p6 = getSentenceProb(self.n, ngram, length)
        print ngram
        print p6
        return p6

    def max_in_list(self,prob_list):

        maxValue=-9999999.0000000
        for key in prob_list.keys():
            floatvalue=key

            if floatvalue>maxValue:
                maxValue=floatvalue

        if maxValue>=0:

            raise ValueError('The prob vallues are not correct')

        return maxValue

    def punctuate(self,string_list):

        #print string_list

        string11=str(string_list[0]+" "+",COMMA"+" "+string_list[1]+" .PERIOD")

        string21 = str(string_list[0] + " " + ".PERIOD" + " " + string_list[1] + " ,COMMA")

        string31 = str(string_list[0] + " " + "epsilon " + string_list[1] + " .PERIOD")

        string41 = str(string_list[0] + " " + ",COMMA" + " " + string_list[1]+" "+"epsilon ")

        string5 = str(string_list[0] + " " + "epsilon "+ string_list[1] + " ,COMMA")

        string6 = str(string_list[0] + " " + ".PERIOD" + " " + string_list[1]+" "+"epsilon")

        string7 = str(string_list[0] + " "+"epsilon " + string_list[1]+" epsilon")

        string8 = str(string_list[0] + " " + ".PERIOD " + string_list[1] + " .PERIOD")

        string9 = str(string_list[0] + " " + ",COMMA " + string_list[1] + " ,COMMA")

        prob11=ngram.get_probability(string11)

        prob21 = ngram.get_probability(string21)

        prob31 = ngram.get_probability(string31)

        prob41 = ngram.get_probability(string41)

        prob5 = ngram.get_probability(string5)
        prob6 = ngram.get_probability(string6)
        prob7 = ngram.get_probability(string7)
        prob8 = ngram.get_probability(string8)
        prob9 = ngram.get_probability(string9)

        prob_list={}
        prob_list[float(prob11)]=string11

        prob_list[float(prob21)] = string21

        prob_list[float(prob31)] = string31

        prob_list[float(prob41)] = string41

        prob_list[float(prob5)] = string5
        prob_list[float(prob6)] = string6
        prob_list[float(prob7)] = string7
        prob_list[float(prob8)] = string8
        prob_list[float(prob9)] = string9
        #print prob_list

        maxValue=self.max_in_list(prob_list)
        print maxValue
        return prob_list[maxValue]

        '''

        ngram.get_probability("Niederlage ,COMMA Deutschlands .PERIOD")
        ngram.get_probability("Niederlage Deutschlands")
        ngram.get_probability("Niederlage .PERIOD Deutschlands")
        ngram.get_probability("Niederlage ,COMMA Deutschlands")
        ngram.get_probability("Niederlage Deutschlands ,COMMA")
        ngram.get_probability("Niederlage Deutschlands .PERIOD")
        '''

    def parse(self):
        fp=open(self.test_file)
        for line in fp:
            string=line.split()

            for i in range(0,len(string),2):
                if i+1<len(string):
                    list=[]
                    list.append(string[i])
                    list.append(string[i+1])
                    #print "before"
                    #print list

                    stringnew=self.punctuate(list)

                    print stringnew
                    self.fw.write(stringnew+" ")

                else:
                    #print string[i]
                    self.fw.write(string[i] + " .PERIOD ")
            self.fw.write("\n")
        self.fw.close()

if __name__ == "__main__":
    clean = Clean("uncleaned_test_data.txt", "test_corpus.txt")
    ngram = NgramTest("newmodel.lm", "test_corpus.txt")

    readLM(ngram.n, "newmodel.lm")

    ngram.parse()


text:
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { ReportWeek } from './week.component';
import { BTModule } from '../../business-tab/bt.module';

// async components must be named routes for WebpackAsyncRoute
export const routes = [
  { path: '', component: ReportWeek, pathMatch: 'full' }
];

@NgModule({
  declarations: [
    // Components / Directives/ Pipes
    ReportWeek
  ],
  imports: [
    CommonModule,
    FormsModule,
    RouterModule.forChild(routes),
    BTModule,
  ]
})
export default class ReportWeekModule {
  static routes = routes;
}


text:
<!--
  #%L
  Java Tool
  %%
  Copyright (C) 2014 - 2021 OSGL (Open Source General Library)
  %%
  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.
  #L%
  -->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <foo>abc</foo>

    <cache name="charityCache"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="2" timeToLiveSeconds="20"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="charityTagsCache"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="20" timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyCache"
           maxEntriesLocalHeap="100"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="officeCache"
           maxEntriesLocalHeap="100"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyThemeModuleCache"
           maxEntriesLocalHeap="100"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyDefaultOfficeCache"
           maxEntriesLocalHeap="100"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyCharityConfigCache"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="2" timeToLiveSeconds="10"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="campaignsByCompany"
           maxEntriesLocalHeap="500"
           eternal="false"
           timeToIdleSeconds="60" timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="userById"
           maxEntriesLocalHeap="5000"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="userByEmail"
           maxEntriesLocalHeap="5000"
           eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="120"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="userByEmailWithData"
           maxEntriesLocalHeap="5000"
           eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="userByExternalIdCache"
           maxEntriesLocalHeap="5000"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="userByIdWithCompany"
           maxEntriesLocalHeap="5000"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="accessToken"
           maxEntriesLocalHeap="5000"
           eternal="false"
           timeToIdleSeconds="360" timeToLiveSeconds="360"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="baseEmailTemplate"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="defaultBaseEmailTemplate"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="emailTheme"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="defaultEmailTheme"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="emailContentByCompany"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="defaultEmailContentTemplate"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyDonationsArchive"
           maxEntriesLocalHeap="50"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyContributions"
           maxEntriesLocalHeap="50"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyDonationStatisticsCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="60" timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyDonationSummariesCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="60" timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="eventRegistrationStatistics"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="60" timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="events"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="120"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="eventsById"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="120"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="eventstermsconditions"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="6000" timeToLiveSeconds="6000"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="eventLocations"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="eventGivingOpportunities"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="10" timeToLiveSeconds="60"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="myDonationSummary"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="120"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="moduleCache"
           maxEntriesLocalHeap="100"
           eternal="false"
           timeToIdleSeconds="30" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="matchingSchemesDescriptions"
           maxEntriesLocalHeap="100"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="countryCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="86400" timeToLiveSeconds="86400"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="systemSettingsCache"
           maxEntriesLocalHeap="20"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="maxSyncDateCache"
           maxEntriesLocalHeap="1"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="exchangeRateBySyncDateCache"
           maxEntriesLocalHeap="300"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="exchangeRateByPublishDateCache"
           maxEntriesLocalHeap="300"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="defaultContentCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="86400" timeToLiveSeconds="86400"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyContentCache"
           maxEntriesLocalHeap="50"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyHomepageConfigCache"
           maxEntriesLocalHeap="50"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="employeeTypeCache"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="600" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companySamlConfigCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="3600" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="companyIdSamlConfigCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="3600" timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

    <cache name="homepageOpportunities"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="300" timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="none" />
    </cache>

</ehcache>


text:
<component name="libraryTable">
  <library name="constraint-layout-solver-1.0.0-beta4">
    <CLASSES>
      <root url="jar://D:/ProgramFiles/AS_SDK/android-sdk-full/sdk/extras/m2repository/com/android/support/constraint/constraint-layout-solver/1.0.0-beta4/constraint-layout-solver-1.0.0-beta4.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
public class main {

	public static void main(String[] args) {
		Servidor servidor1, servidor2, servidor3, servidor4, servidor5;
		FabricaServidor fabrica = new FabricaServidor();
		servidor1 = fabrica.novoServidor();
		servidor2 = fabrica.novoServidor();
		servidor3 = fabrica.novoServidor();
		servidor5 = fabrica.novoServidor();
		servidor4 = fabrica.novoServidor();
		servidor1.visualizar();
		servidor2.visualizar();
		servidor1.salvar();
		servidor3.visualizar();
		servidor4.visualizar();
		servidor5.visualizar();
	}

}


text:
<title>PJ-Dependent - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Machine-Dependencies.html#Machine-Dependencies" title="Machine Dependencies">
<link rel="prev" href="PDP_002d11_002dDependent.html#PDP_002d11_002dDependent" title="PDP-11-Dependent">
<link rel="next" href="PPC_002dDependent.html#PPC_002dDependent" title="PPC-Dependent">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: PPC-Dependent,
Previous: PDP-11-Dependent,
Up: Machine Dependencies

9.34 picoJava Dependent Features

PJ Options:               Options

PJ Syntax:                PJ Syntax


text:
package org.basex.query.up.primitives.db;

import static org.basex.query.QueryError.*;

import java.util.*;
import java.util.Map.Entry;

import org.basex.data.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.up.primitives.*;
import org.basex.util.*;

/**
 * Update primitive for the {@link Function#_DB_RENAME} function.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Christian Gruen
 */
public final class DBRename extends DBUpdate {
  /** Source and target paths. */
  private final HashMap<String, String> map = new HashMap<>();

  /**
   * Constructor.
   * @param data target data
   * @param src source path
   * @param trg target path
   * @param info input info
   */
  public DBRename(final Data data, final String src, final String trg, final InputInfo info) {
    super(UpdateType.DBRENAME, data, info);
    map.put(src, trg);
  }

  @Override
  public void merge(final Update update) throws QueryException {
    for(final Entry<String, String> e : ((DBRename) update).map.entrySet()) {
      final String src = e.getKey();
      if(map.containsKey(src)) throw UPPATHREN_X.get(info, src);
      map.put(src, e.getValue());
    }
  }

  @Override
  public void apply() {
    for(final Entry<String, String> op : map.entrySet()) {
      final IOFile src = new IOFile(op.getKey());
      final IOFile trg = new IOFile(op.getValue());
      if(src.exists()) {
        if(trg.exists()) {
          trg.delete();
        } else {
          trg.parent().md();
        }
        src.rename(trg);
      }
    }
  }

  @Override
  public int size() {
    return map.size();
  }

  @Override
  public void prepare() { }
}


text:
package com.panoramagl.structs;

public class PLRGBA implements PLIStruct<PLRGBA>
{
	/**member variables*/

	public float red, green, blue, alpha;

	/**init methods*/

	public PLRGBA()
	{
		this(0.0f, 0.0f, 0.0f, 1.0f);
	}

	public PLRGBA(PLRGBA rgba)
	{
		this(rgba.red, rgba.green, rgba.blue, rgba.alpha);
	}

	public PLRGBA(float red, float green, float blue, float alpha)
	{
		super();
		this.red = red;
		this.green = green;
		this.blue = blue;
		this.alpha = alpha;
	}

	public static PLRGBA PLRGBAMake()
	{
		return new PLRGBA();
	}

	public static PLRGBA PLRGBAMake(PLRGBA rgba)
	{
		return new PLRGBA(rgba);
	}

	public static PLRGBA PLRGBAMake(float red, float green, float blue, float alpha)
	{
		return new PLRGBA(red, green, blue, alpha);
	}

	/**reset methods*/

	@Override
	public boolean isResetted()
	{
		return (red == 0.0f && green == 0.0f && blue == 0.0f && alpha == 1.0f);
	}

	@Override
	public PLRGBA reset()
	{
		red = green = blue = 0.0f;
		alpha = 1.0f;
		return this;
	}

	/**set methods*/

	@Override
	public PLRGBA setValues(PLRGBA rgba)
	{
		red = rgba.red;
		green = rgba.green;
		blue = rgba.blue;
		alpha = rgba.alpha;
		return this;
	}

	public PLRGBA setValues(float red, float green, float blue, float alpha)
	{
		this.red = red;
		this.green = green;
		this.blue = blue;
		this.alpha = alpha;
		return this;
	}

	/**clone methods*/

	@Override
	public PLRGBA clone()
	{
		return new PLRGBA(red, green, blue, alpha);
	}

	/**native methods*/

	@Override
	public boolean equals(Object o)
	{
		if(o != null && o instanceof PLRGBA)
		{
			if(this == o)
				return true;
			PLRGBA rgba = (PLRGBA)o;
			return (red == rgba.red && green == rgba.green && blue == rgba.blue && alpha == rgba.alpha);
		}
		return false;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="vertical"
    >

    <com.ebaotech.salesplatform.commons.widget.echeckbox.EnhancedCheckbox
        android:id="@+id/parentCheckbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:text="Összes típus"
        android:visibility="visible" />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="@android:color/darker_gray"
        android:orientation="vertical">

    </LinearLayout>

    <com.ebaotech.salesplatform.commons.widget.SimpleListView
        android:id="@+id/childListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
package com.ktl.moment.manager;

import android.graphics.Bitmap;
import android.view.View;

import com.ktl.moment.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ImageManager {
	public interface ImgLoadCallback {
		public void OnComplete(String imageUri, Bitmap loadedImage);

		public void OnError(FailReason failReason);
	}

	private ImgLoadCallback mImgLoadCallback;
	private static ImageManager instance = null;

	private ImageManager() {
	}

	/**
	 * 获取一个实例
	 *
	 * @return
	 */
	public static ImageManager getInstance() {
		if (instance == null) {
			instance = new ImageManager();
		}
		return instance;
	}

	public void setmImgLoadCallback(ImgLoadCallback mImgLoadCallback) {
		this.mImgLoadCallback = mImgLoadCallback;
	}

	/**
	 *
	 * @param imageUri
	 */
	public void loadImg(String imageUri) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheOnDisk(true)
				.cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
				.considerExifParams(true).build();

		ImageLoader.getInstance().loadImage(imageUri, null, options,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						// Do whatever you want with Bitmap
						mImgLoadCallback.OnComplete(imageUri, loadedImage);
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						// TODO Auto-generated method stub
						super.onLoadingFailed(imageUri, view, failReason);
						mImgLoadCallback.OnError(failReason);
					}
				});
	}

	public DisplayImageOptions getDisplayImageOptions() {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_img)
				.showImageForEmptyUri(R.drawable.default_img)
				.showImageOnFail(R.drawable.default_img).cacheOnDisk(true)
				.cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
				.considerExifParams(true).build();
		return options;
	}

	public Bitmap loadImageSync(String filePath){
		return ImageLoader.getInstance().loadImageSync(filePath, getDisplayImageOptions());
	}
}


text:
package io.neft.renderer.handlers;

import io.neft.client.Reader;
import io.neft.renderer.Item;

public abstract class NoArgsItemActionHandler<T extends Item> implements ItemActionHandler<T> {
    public abstract void accept(T item);

    public final void accept(T item, Reader reader) {
        accept(item);
    }
}


text:
@interface KHolder ()

// 正在进行归档的状态位
@property (assign, atomic)      BOOL                        archiving;
@property (assign, atomic)      BOOL                        cleaning;
@property (strong, nonatomic)   NSFileManager               *fileManager;
@property (strong, atomic)      NSMutableArray              *keys;
@property (assign, nonatomic)   NSUInteger                  size;
@property (strong, nonatomic)   NSMutableDictionary         *objects;
@property (strong, nonatomic)   NSString                    *path;
@property (strong, atomic)      NSConditionLock             *lock;

// 把数据写到磁盘
- (void)doArchive;
- (void)archiveData;
- (void)archiveAllData;

- (void)doClean;
- (void)cleanExpiredObjects;

@end

@implementation KHolder

@synthesize archiving   = _archiving;
@synthesize cleaning    = _cleaning;

@synthesize fileManager = _fileManager;
// 缓存Key列表
@synthesize keys        = _keys;
// 缓存大小
@synthesize size        = _size;
// 缓存内容
@synthesize objects     = _objects;

@synthesize path        = _path;

#pragma mark - init

- (id)init
{
    self = [self initWithToken:@"_KacheDefault"];
    if (self) {
        return self;
    }

    return nil;
}

- (id)initWithToken:(NSString *)token
{
    self = [super init];
    if (self) {
        self.objects = [[NSMutableDictionary alloc] init];
        self.keys = [[NSMutableArray alloc] init];
        self.size = 0;
        self.lock = [[NSConditionLock alloc] initWithCondition:DATA_OPERATING];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *libDirectory = [paths objectAtIndex:0];
        self.path = [libDirectory stringByAppendingPathComponent:[Kache_Objects_Disk_Path stringByAppendingPathExtension:token]];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            [self doArchive];
        });
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            [self doClean];
        });

        return self;
    }

    return nil;
}

#pragma mark - private

- (NSFileManager *)fileManager
{
    return [NSFileManager defaultManager];
}

- (void)doArchive
{
    NSTimer *archivingTimer = [NSTimer timerWithTimeInterval:10.f target:self selector:@selector(archiveData) userInfo:nil repeats:YES];
    NSRunLoop *archivingRunloop = [NSRunLoop currentRunLoop];
    [archivingRunloop addTimer:archivingTimer forMode:NSDefaultRunLoopMode];
    while (YES) {
        [archivingRunloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:2.f]];
    }
}

- (void)archiveData
{
    self.archiving = YES;
    NSLog(@"archiging...");
       if (0 < ARCHIVING_THRESHOLD
           && ARCHIVING_THRESHOLD < self.size) {
           BOOL isDirectory = NO;
           if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
               [self.fileManager createDirectoryAtPath:self.self.path
                           withIntermediateDirectories:YES
                                            attributes:nil
                                                 error:nil];
           }
           [self.lock lockWhenCondition:DATA_FREE];
           NSMutableArray *copiedKeys = [self.keys mutableCopy];
           while (0 < [copiedKeys count]) {
               // 归档至阈值一半的数据
               if ((ARCHIVING_THRESHOLD / 2) >= self.size) {
                   break;
               }
               NSString *key = [copiedKeys lastObject];
               NSString *filePath = [self.path stringByAppendingPathComponent:key];

               NSData *data = [self.objects objectForKey:key];
               [data writeToFile:filePath atomically:YES];
               self.size -= data.length;
               [copiedKeys removeLastObject];
               [self.objects removeObjectForKey:key];
           }
           copiedKeys = nil;
           [self.lock unlockWithCondition:DATA_FREE];
       }
    self.archiving = NO;
}

- (void)archiveAllData
{
    self.archiving = YES;
    BOOL isDirectory = NO;
    if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
        [self.fileManager createDirectoryAtPath:self.self.path
                    withIntermediateDirectories:YES
                                     attributes:nil
                                          error:nil];
    }
    NSMutableArray *copiedKeys = [self.keys mutableCopy];
    while (0 < [copiedKeys count]) {
        NSString *key = [copiedKeys lastObject];
        NSString *filePath = [self.path stringByAppendingPathComponent:key];

        NSData *data = [self.objects objectForKey:key];
        [data writeToFile:filePath atomically:YES];
        self.size -= data.length;
        [copiedKeys removeLastObject];
        [self.objects removeObjectForKey:key];
    }
    copiedKeys = nil;
    self.archiving = NO;
}

- (void)doClean
{
    NSTimer *cleaningTimer = [NSTimer timerWithTimeInterval:30.f target:self selector:@selector(cleanExpiredObjects) userInfo:nil repeats:YES];
    NSRunLoop *cleaningRunloop = [NSRunLoop currentRunLoop];
    [cleaningRunloop addTimer:cleaningTimer forMode:NSDefaultRunLoopMode];
    while (YES) {
        [cleaningRunloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:2.f]];
    }
}

- (void)cleanExpiredObjects
{
    NSLog(@"cleaning...");
    self.cleaning = YES;
    if (self.keys && 0 < [self.keys count]) {
        [self.lock lock];
        for (int i = 0; i < [self.keys count] - 1; i ++) {
            NSString *tmpKey = [self.keys objectAtIndex:i];
            KObject *leftObject = [self objectForKey:tmpKey];
            if ([leftObject expiredTimestamp] < [KUtil nowTimestamp]) {
                [self removeObjectForKey:tmpKey];
            }
            else {
                break;
            }
        }
        [self.lock unlockWithCondition:DATA_FREE];
    }
    self.cleaning = NO;
}

#pragma mark - public

- (void)removeObjectForKey:(NSString *)key {
    [self.keys removeObject:key];
    if ([[self.objects allKeys] containsObject:key]) {
        [self.objects removeObjectForKey:key];
    }
    else {
        NSString *filePath = [self.path stringByAppendingPathComponent:key];
        [self.fileManager removeItemAtPath:filePath error:nil];
    }
}

- (void)setValue:(id)value forKey:(NSString *)key expiredAfter:(NSInteger)duration
{
    KObject *object = [[KObject alloc] initWithData:value andLifeDuration:duration];

    if (self.archiving) {
        NSString *filePath = [self.path stringByAppendingPathComponent:key];
        [object.data writeToFile:filePath atomically:YES];
    }
    else {
        [self.objects setValue:object.data forKey:key];
        self.size += [object size];
    }

    // TODO sort the key by expired time.
    [self.keys removeObject:key];

    [self.lock lockWhenCondition:DATA_FREE];
    for (int i = [self.keys count] - 1; i >= 0; i --) {
        NSString *tmpKey = [self.keys objectAtIndex:i];
        KObject *leftObject = [self objectForKey:tmpKey];
        // 过期时间越晚
        if ([leftObject expiredTimestamp] <= [object expiredTimestamp]) {
            if (([self.keys count] - 1) == i) {
                [self.keys addObject:key];
            }
            else {
                [self.keys insertObject:key atIndex:i + 1];
            }
            break;
        }
    }
    [self.lock unlockWithCondition:DATA_FREE];
    if (! [self.keys containsObject:key]) {
        [self.keys insertObject:key atIndex:0];
    }

    // 超过阈值,归档
    if ((! self.archiving)
        && 0 < ARCHIVING_THRESHOLD
        && ARCHIVING_THRESHOLD < self.size) {
        [self archiveData];
    }
}

- (id)valueForKey:(NSString *)key
{
    KObject *object = [self objectForKey:key];
    if (object && ! [object expired]) {
        return [object value];
    }
    // No such object.
    return nil;
}

- (KObject *)objectForKey:(NSString *)key
{
    if (! [[self.objects allKeys] containsObject:key]) {
        NSString *filePath = [self.path stringByAppendingPathComponent:key];
        if ([self.fileManager fileExistsAtPath:filePath isDirectory:NO]) {
            // 超过阈值直接返回,不装入内存
            if ((! self.archiving) && 0 < ARCHIVING_THRESHOLD && ARCHIVING_THRESHOLD < self.size) {
                return [[KObject alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];
            }
            else {
                NSData *data = [NSData dataWithContentsOfFile:filePath];
                [self.objects setValue:data forKey:key];
                self.size += data.length;
                data = nil;
                [self.fileManager removeItemAtPath:filePath error:nil];
            }
        }
        else {
            return nil;
        }
    }
    return [[KObject alloc] initWithData:[self.objects objectForKey:key]];
}

// Convert object to NSDictionary.
- (NSDictionary *)serialize
{
    [self archiveAllData];
    return [NSDictionary dictionaryWithObjectsAndKeys:
            self.keys, @"keys",
            [NSString stringWithFormat:@"%d", self.size], @"size",
            nil];
}

// Convert NSDictionary to object.
- (void)unserializeFrom:(NSDictionary *)dict
{
    if ([[dict allKeys] containsObject:@"keys"]
        && [[dict allKeys] containsObject:@"meta"]) {
        self.keys = [dict objectForKey:@"keys"];
        self.size = [[dict objectForKey:@"size"] intValue];
    }
}

@end


text:
package ddl_test

import (
	"fmt"

	gofail "github.com/etcd-io/gofail/runtime"
	. "github.com/pingcap/check"
	"github.com/pingcap/tidb/domain"
	"github.com/pingcap/tidb/model"
	"github.com/pingcap/tidb/util/testkit"
	"golang.org/x/net/context"
)

// TestInitializeOffsetAndState tests the case that the column's offset and state don't be initialized in the file of ddl_api.go when
// doing the operation of 'modify column'.
func (s *testStateChangeSuite) TestInitializeOffsetAndState(c *C) {
	_, err := s.se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	_, err = s.se.Execute(context.Background(), "create table t(a int, b int, c int)")
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table t")

	gofail.Enable("github.com/pingcap/tidb/ddl/uninitializedOffsetAndState", `return(true)`)
	_, err = s.se.Execute(context.Background(), "ALTER TABLE t MODIFY COLUMN b int FIRST;")
	c.Assert(err, IsNil)
	gofail.Disable("github.com/pingcap/tidb/ddl/uninitializedOffsetAndState")
}

func (s *testDBSuite) TestUpdateHandleFailed(c *C) {
	gofail.Enable("github.com/pingcap/tidb/ddl/errorUpdateReorgHandle", `return(true)`)
	defer gofail.Disable("github.com/pingcap/tidb/ddl/errorUpdateReorgHandle")
	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("create database if not exists test_handle_failed")
	defer tk.MustExec("drop database test_handle_failed")
	tk.MustExec("use test_handle_failed")
	tk.MustExec("create table t(a int primary key, b int)")
	tk.MustExec("insert into t values(-1, 1)")
	tk.MustExec("alter table t add index idx_b(b)")
	result := tk.MustQuery("select count(*) from t use index(idx_b)")
	result.Check(testkit.Rows("1"))
	tk.MustExec("admin check index t idx_b")
}

func (s *testDBSuite) TestAddIndexFailed(c *C) {
	gofail.Enable("github.com/pingcap/tidb/ddl/mockAddIndexErr", `return(true)`)
	defer gofail.Disable("github.com/pingcap/tidb/ddl/mockAddIndexErr")
	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("create database if not exists test_add_index_failed")
	defer tk.MustExec("drop database test_add_index_failed")
	tk.MustExec("use test_add_index_failed")

	tk.MustExec("create table t(a bigint PRIMARY KEY, b int)")
	for i := 0; i < 1000; i++ {
		tk.MustExec(fmt.Sprintf("insert into t values(%v, %v)", i, i))
	}

	// Get table ID for split.
	dom := domain.GetDomain(tk.Se)
	is := dom.InfoSchema()
	tbl, err := is.TableByName(model.NewCIStr("test_add_index_failed"), model.NewCIStr("t"))
	c.Assert(err, IsNil)
	tblID := tbl.Meta().ID

	// Split the table.
	s.cluster.SplitTable(s.mvccStore, tblID, 100)

	tk.MustExec("alter table t add index idx_b(b)")
	tk.MustExec("admin check index t idx_b")
	tk.MustExec("admin check table t")
}


text:
using System.Globalization;
using AutoMapper;

namespace Subtle.Model.Mapping
{
    public class DecimalTypeConverter : TypeConverter<string, decimal?>
    {
        protected override decimal? ConvertCore(string source)
        {
            decimal result;
            decimal.TryParse(source, NumberStyles.Any, CultureInfo.InvariantCulture, out result);

            // Discard zero values
            if (result == 0)
            {
                return null;
            }

            return result;
        }
    }
}


text:
package com.blazebit.persistence.view.processor;

import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import java.util.Map;

/**
 * @author Christian Beikov
 * @since 1.5.0
 */
public final class OptionalParameterUtils {

    private OptionalParameterUtils() {
    }

    public static void addOptionalParameters(Map<String, String> optionalParameters, String mapping, Context context) {
        addOptionalParameters(
            new OptionalParameterConsumer() {
                @Override
                public void addOptionalParameter(String name, TypeMirror typeMirror) {
                    if (!optionalParameters.containsKey(name)) {
                        if (typeMirror == null) {
                            typeMirror = context.getTypeElement("java.lang.Object").asType();
                        }
                        optionalParameters.put(name, typeMirror.toString());
                    }
                }
            },
            mapping,
            context
        );
    }

    public static void addOptionalParametersTypeElement(Map<String, TypeMirror> optionalParameters, String mapping, Context context) {
        addOptionalParameters(
            new OptionalParameterConsumer() {
                @Override
                public void addOptionalParameter(String name, TypeMirror typeMirror) {
                    if (!optionalParameters.containsKey(name)) {
                        if (typeMirror == null) {
                            typeMirror = context.getTypeElement("java.lang.Object").asType();
                        }
                        optionalParameters.put(name, typeMirror);
                    }
                }
            },
            mapping,
            context
        );
    }

    private static void addOptionalParameters(OptionalParameterConsumer optionalParameters, String mapping, Context context) {
        if (mapping == null || mapping.isEmpty()) {
            return;
        }
        int idx = -1;
        StringBuilder sb = null;
        TypeElement objectTypeElement = null;
        while ((idx = mapping.indexOf(':', idx + 1)) != -1) {
            if (sb == null) {
                sb = new StringBuilder();
            } else {
                sb.setLength(0);
            }
            for (int i = idx + 1; i < mapping.length(); i++) {
                final char c = mapping.charAt(i);
                if (Character.isJavaIdentifierPart(c)) {
                    sb.append(c);
                } else {
                    break;
                }
            }
            if (sb.length() != 0) {
                String name = sb.toString();
                TypeMirror existingTypeElement = context.getOptionalParameters().get(name);
                optionalParameters.addOptionalParameter(name, existingTypeElement);
            }
        }
    }

    /**
     * @author Christian Beikov
     * @since 1.6.8
     */
    private static interface OptionalParameterConsumer {
        void addOptionalParameter(String name, TypeMirror typeMirror);
    }
}


text:
<?php

use ZfrTradeGecko\Container\TradeGeckoClientFactory;
use ZfrTradeGecko\TradeGeckoClient;

return [
    'dependencies' => [
        'factories' => [
            TradeGeckoClient::class => TradeGeckoClientFactory::class,
        ],
    ],
];


text:
package com.opnitech.rules.core.test.engine.test_validators.group;

import com.opnitech.rules.core.annotations.group.GroupDefinition;
import com.opnitech.rules.core.annotations.group.GroupKey;

/**
 * @author Rigre Gregorio Garciandia Sonora
 */
@GroupDefinition
public class InvalidGroupKeyDuplicateGroupDefinition {

    @GroupKey
    public String groupKey() {

        return "TEST";
    }

    @GroupKey
    public String groupKey1() {

        return "TEST";
    }
}


text:
  <form novalidate [formGroup]="heroForm" (ngSubmit)="onSubmit()">

Create new Hero

Edit Hero

{{hero.id || '#' }}

            <input type="text" class="form-control " placeholder="Name" id="name"
                   formControlName="name" required
                   [ngClass]="{'form-control-danger': !heroForm.valid, 'form-control-success': heroForm.valid}"/>

{{ message }}

        <button type="submit" class="btn btn-primary" [disabled]="!heroForm.valid">

        </button>
        <button type="button" class="btn btn-default pull-right" (click)="close()">

        </button>

  </form>


text:
describe('TODO <Sticky />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(true)
  })
})


text:
namespace Telerik.UI.Xaml.Controls.Chart
{
    /// <summary>
    /// Represents the AverageTrueRange financial indicator.
    /// </summary>
    public class AverageTrueRangeIndicator : HighLowClosePeriodIndicatorBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AverageTrueRangeIndicator" /> class.
        /// </summary>
        public AverageTrueRangeIndicator()
        {
            this.DefaultStyleKey = typeof(AverageTrueRangeIndicator);
        }

        /// <summary>
        /// Returns a <see cref="T:System.String" /> that represents the current <see cref="T:System.Object" />.
        /// </summary>
        public override string ToString()
        {
            return "Average True Range (" + this.Period + ")";
        }

        internal override ChartSeriesDataSource CreateDataSourceInstance()
        {
            return new AverageTrueRangeIndicatorDataSource();
        }
    }
}


text:
package org.renjin.primitives.match;

import java.util.Iterator;

import org.renjin.sexp.Vector;

class IndexSequence implements Iterable<Integer> {

  private Vector vector;
  private boolean fromLast;

  public IndexSequence(Vector vector, boolean fromLast) {
    super();
    this.vector = vector;
    this.fromLast = fromLast;
  }

  @Override
  public Iterator<Integer> iterator() {
    if(fromLast) {
      return new ReverseIndexIterator(vector);
    } else {
      return new ForwardIndexIterator(vector);
    }
  }
}


text:
package com.planet_ink.coffee_mud.Items.Armor;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

public class GenPants extends GenArmor
{
	@Override public String ID(){	return "GenPants";}
	public GenPants()
	{
		super();

		setName("a pair of pants");
		setDisplayText("a pair of pants lies here");
		setDescription("a well tailored pair of travelers pants.");
		properWornBitmap=Wearable.WORN_LEGS;
		wornLogicalAnd=false;
		basePhyStats().setArmor(1);
		basePhyStats().setWeight(1);
		basePhyStats().setAbility(0);
		baseGoldValue=1;
		recoverPhyStats();
		material=RawMaterial.RESOURCE_COTTON;
	}

}