text:
@implementation cdaXSellMyUITableViewCell

@synthesize headerLabel, descriptionLabel, downloadHereLabel, iconImageView, appURL, parentTable;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // set style and create labels
        self.headerLabel = [[[UILabel alloc]init] autorelease];
        self.headerLabel.textAlignment = UITextAlignmentLeft;
        self.headerLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 16 : 19)];
        self.headerLabel.textColor = [UIColor colorWithRed:89.0f/255.0f green:59.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        self.headerLabel.lineBreakMode = UILineBreakModeWordWrap;
        self.headerLabel.numberOfLines = 0;

        self.descriptionLabel = [[[UILabel alloc]init] autorelease];
        self.descriptionLabel.textAlignment = UITextAlignmentLeft;
        self.descriptionLabel.font =[UIFont fontWithName:@"Arial" size:((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 14 : 16)];
        self.descriptionLabel.textColor = [UIColor colorWithRed:89.0f/255.0f green:59.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        self.descriptionLabel.lineBreakMode = UILineBreakModeWordWrap;
        self.descriptionLabel.numberOfLines = 0;

        self.downloadHereLabel = [[[UILabel alloc]init] autorelease];
        self.downloadHereLabel.textAlignment = UITextAlignmentLeft;
        self.downloadHereLabel.font =[UIFont fontWithName:@"Arial-BoldMT" size:((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 14 : 16)];
        self.downloadHereLabel.textColor = [UIColor colorWithRed:89.0f/255.0f green:59.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        self.downloadHereLabel.lineBreakMode = UILineBreakModeWordWrap;
        self.downloadHereLabel.numberOfLines = 0;
        self.downloadHereLabel.text = @"Download here.";

        self.iconImageView = [[[UIImageView alloc]init] autorelease];
        [self.contentView addSubview:self.headerLabel];
        [self.contentView addSubview:self.descriptionLabel];
        [self.contentView addSubview:self.downloadHereLabel];
        [self.contentView addSubview:self.iconImageView];

        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

-(void) debugFrame:(CGRect) frame {
    NSLog(@"%fx%f width:%f height:%f",frame.origin.x,frame.origin.y,frame.size.width,frame.size.height);

}

-(id) setAppValues:(cdaXSellApp *) app forTable:(UITableView *) table {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    self.parentTable = table;

    // Register for icon downloaded notification to reload the cell's image
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadImage:)
                                                 name:cdaXSellIconDownloadedNotification
                                               object:app];

    //get image depending on device
    NSString const *iconSize;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {

        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] >= 2) {
            iconSize = IPHONE_RETINA_ICON_SIZE;
        }
        else {
            iconSize = IPHONE_ICON_SIZE;

        }
    }
    else {
        iconSize = IPAD_ICON_SIZE;
    }
    [self setImageViewFromApp:app forSize:iconSize];

    //labels
    self.headerLabel.text=app.name;
    //keep the text as one line
    self.headerLabel.text = [self.headerLabel.text stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    self.descriptionLabel.text=app.shortDescription;

    //not sure how this should work but at the moment pick first link
    NSArray *links = app.appLinks;
    cdaXSellAppLink *link = [links objectAtIndex:0];
    NSString *urlString = link.URL;
    self.appURL = [NSURL URLWithString:urlString];

    return self;
}

-(CGFloat) textXOffset {
    return self.iconImageView.frame.size.width+((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? IMAGE_PADDING_RIGHT_IPHONE :IMAGE_PADDING_RIGHT_IPAD);
}

-(CGFloat) sizeContentToFit {
    CGFloat totalSize = 0.0;

    totalSize += [self sizeLabelToFit:self.headerLabel];
    totalSize += ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? HEADER_PADDING_BOTTOM_IPHONE : HEADER_PADDING_BOTTOM_IPAD);
    totalSize += [self sizeLabelToFit:self.descriptionLabel];
    totalSize += ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? DESCRIPTION_PADDING_BOTTOM_IPHONE : DESCRIPTION_PADDING_BOTTOM_IPAD);
    totalSize += [self sizeLabelToFit:self.downloadHereLabel];

    //check maximum size f
    if (self.iconImageView.frame.size.height > totalSize) {
        totalSize = self.iconImageView.frame.size.height + ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 2 : 13); //hack to layout when using images
    }

    totalSize += ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? CELL_PADDING_BOTTOM_IPHONE : CELL_PADDING_BOTTOM_IPAD);

    return totalSize;
}

//resize the labels to fit the text
-(CGFloat) sizeLabelToFit:(UILabel *) sizeLabel  {
    //Calculate the expected size based on the font and linebreak mode of your label
    CGFloat maxWidth = self.parentTable.frame.size.width-[self textXOffset];
    CGSize maximumLabelSize = CGSizeMake(maxWidth,9999);

    CGSize expectedLabelSize = [sizeLabel.text sizeWithFont:sizeLabel.font
                                      constrainedToSize:maximumLabelSize
                                          lineBreakMode:sizeLabel.lineBreakMode];

    //adjust the label the the new height.
    sizeLabel.frame = CGRectMake(sizeLabel.frame.origin.x, sizeLabel.frame.origin.y, expectedLabelSize.width, expectedLabelSize.height);

    return sizeLabel.frame.size.height;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect contentRect = self.contentView.bounds;
    CGFloat boundsX = contentRect.origin.x;

    //calculate the widths of the labels
    [self sizeContentToFit];

    //layout the labels
    self.iconImageView.frame = CGRectMake(boundsX+0, 0, self.iconImageView.frame.size.width, self.iconImageView.frame.size.height);
    self.headerLabel.frame = CGRectMake(boundsX+[self textXOffset], 0-((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 1 : 4), headerLabel.frame.size.width, headerLabel.frame.size.height); //-4 to compensate uilabel padding
    self.descriptionLabel.frame = CGRectMake(boundsX+headerLabel.frame.origin.x, (headerLabel.frame.origin.y+headerLabel.frame.size.height+((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? HEADER_PADDING_BOTTOM_IPHONE - 1 : HEADER_PADDING_BOTTOM_IPAD -4)), descriptionLabel.frame.size.width, descriptionLabel.frame.size.height); //-4 to compensate uilabel padding
    self.downloadHereLabel.frame =CGRectMake(boundsX+descriptionLabel.frame.origin.x, (descriptionLabel.frame.origin.y + descriptionLabel.frame.size.height+((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? DESCRIPTION_PADDING_BOTTOM_IPHONE : DESCRIPTION_PADDING_BOTTOM_IPAD)), downloadHereLabel.frame.size.width, downloadHereLabel.frame.size.height);
}

-(void)reloadImage:(NSNotification*)notification {
    cdaXSellApp* app = [notification object];

    [self setImageViewFromApp:app forSize:[[notification userInfo] objectForKey:@"size"]];
    [self setNeedsLayout];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) setImageViewFromApp:(cdaXSellApp *) app forSize:(NSString const*) size {

    NSString* path = [app iconImageFileNameForSize:size];
    UIImage* image = [UIImage imageWithContentsOfFile: path];
    [self.iconImageView setImage:image];

    //set the size
    CGRect imageFrame = self.iconImageView.frame;
    imageFrame.size = [app iconDimensions:size];
    self.iconImageView.frame = imageFrame;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.headerLabel removeFromSuperview];
    self.headerLabel = nil;

    [self.descriptionLabel removeFromSuperview];
    self.descriptionLabel = nil;

    [self.downloadHereLabel removeFromSuperview];
    self.downloadHereLabel = nil;

    [self.iconImageView removeFromSuperview];
    self.iconImageView = nil;

    self.appURL = nil;

    self.parentTable = nil;

    [super dealloc];
}

@end


text:
package reveal

import (
	"fmt"

	"github.com/ncw/rclone/cmd"
	"github.com/ncw/rclone/fs/config/obscure"
	"github.com/spf13/cobra"
)

func init() {
	cmd.Root.AddCommand(commandDefintion)
}

var commandDefintion = &cobra.Command{
	Use:   "reveal password",
	Short: `Reveal obscured password from rclone.conf`,
	Run: func(command *cobra.Command, args []string) {
		cmd.CheckArgs(1, 1, command, args)
		cmd.Run(false, false, command, func() error {
			revealed, err := obscure.Reveal(args[0])
			if err != nil {
				return err
			}
			fmt.Println(revealed)
			return nil
		})
	},
	Hidden: true,
}

redpajama_set_name: RedPajamaGithub


text:
package cn.ycoder.android.library.tool;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.drawable.Drawable;
import android.view.View;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 *

 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2016/8/2
 *     desc  : App相关工具类
 *

 */
public final class AppUtils {

    private AppUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 判断App是否安装
     *
     * @param packageName 包名
     * @return {@code true}: 已安装
{@code false}: 未安装
     */
    public static boolean isInstallApp(String packageName) {
        return !isSpace(packageName) && IntentUtils.getLaunchAppIntent(packageName) != null;
    }

    /**
     * 安装App(支持6.0)
     *
     * @param filePath 文件路径
     */
    public static void installApp(String filePath) {
        installApp(FileUtils.getFileByPath(filePath));
    }

    /**
     * 安装App(支持6.0)
     *
     * @param file    文件
     */
    public static void installApp(File file) {
        if (!FileUtils.isFileExists(file)) return;
        Utils.getContext().startActivity(IntentUtils.getInstallAppIntent(file));
    }

    /**
     * 安装App(支持6.0)
     *
     * @param activity    activity
     * @param filePath    文件路径
     * @param requestCode 请求值
     */
    public static void installApp(Activity activity, String filePath, int requestCode) {
        installApp(activity, FileUtils.getFileByPath(filePath), requestCode);
    }

    /**
     * 安装App(支持6.0)
     *
     * @param activity    activity
     * @param file        文件
     * @param requestCode 请求值
     */
    public static void installApp(Activity activity, File file, int requestCode) {
        if (!FileUtils.isFileExists(file)) return;
        activity.startActivityForResult(IntentUtils.getInstallAppIntent(file), requestCode);
    }

    /**
     * 静默安装App
     *
非root需添加权限 {@code <uses-permission android:name="android.permission.INSTALL_PACKAGES" />}

     *
     * @param filePath 文件路径
     * @return {@code true}: 安装成功
{@code false}: 安装失败
     */
    public static boolean installAppSilent(String filePath) {
        File file = FileUtils.getFileByPath(filePath);
        if (!FileUtils.isFileExists(file)) return false;
        String command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install " + filePath;
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(command, !isSystemApp(), true);
        return commandResult.successMsg != null && commandResult.successMsg.toLowerCase().contains("success");
    }

    /**
     * 卸载App
     *
     * @param packageName 包名
     */
    public static void uninstallApp(String packageName) {
        if (isSpace(packageName)) return;
        Utils.getContext().startActivity(IntentUtils.getUninstallAppIntent(packageName));
    }

    /**
     * 卸载App
     *
     * @param activity    activity
     * @param packageName 包名
     * @param requestCode 请求值
     */
    public static void uninstallApp(Activity activity, String packageName, int requestCode) {
        if (isSpace(packageName)) return;
        activity.startActivityForResult(IntentUtils.getUninstallAppIntent(packageName), requestCode);
    }

    /**
     * 静默卸载App
     *
非root需添加权限 {@code <uses-permission android:name="android.permission.DELETE_PACKAGES" />}

     *
     * @param packageName 包名
     * @param isKeepData  是否保留数据
     * @return {@code true}: 卸载成功
{@code false}: 卸载成功
     */
    public static boolean uninstallAppSilent(String packageName, boolean isKeepData) {
        if (isSpace(packageName)) return false;
        String command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall " + (isKeepData ? "-k " : "") + packageName;
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(command, !isSystemApp(), true);
        return commandResult.successMsg != null && commandResult.successMsg.toLowerCase().contains("success");
    }

    /**
     * 判断App是否有root权限
     *
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isAppRoot() {
        ShellUtils.CommandResult result = ShellUtils.execCmd("echo root", true);
        if (result.result == 0) {
            return true;
        }
        if (result.errorMsg != null) {
            LogUtils.d(result.errorMsg);
        }
        return false;
    }

    /**
     * 打开App
     *
     * @param packageName 包名
     */
    public static void launchApp(String packageName) {
        if (isSpace(packageName)) return;
        Utils.getContext().startActivity(IntentUtils.getLaunchAppIntent(packageName));
    }

    /**
     * 打开App
     *
     * @param activity    activity
     * @param packageName 包名
     * @param requestCode 请求值
     */
    public static void launchApp(Activity activity, String packageName, int requestCode) {
        if (isSpace(packageName)) return;
        activity.startActivityForResult(IntentUtils.getLaunchAppIntent(packageName), requestCode);
    }

    /**
     * 获取App包名
     *
     * @return App包名
     */
    public static String getAppPackageName() {
        return Utils.getPackageName();
    }

    /**
     * 获取App具体设置
     *
     */
    public static void getAppDetailsSettings() {
        getAppDetailsSettings(Utils.getPackageName());
    }

    /**
     * 获取App具体设置
     *
     * @param packageName 包名
     */
    public static void getAppDetailsSettings(String packageName) {
        if (isSpace(packageName)) return;
        Utils.getContext().startActivity(IntentUtils.getAppDetailsSettingsIntent(packageName));
    }

    /**
     * 获取App名称
     *
     * @return App名称
     */
    public static String getAppName() {
        return getAppName(Utils.getPackageName());
    }

    /**
     * 获取App名称
     *
     * @param packageName 包名
     * @return App名称
     */
    public static String getAppName(String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.applicationInfo.loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取App图标
     *
     * @return App图标
     */
    public static Drawable getAppIcon() {
        return getAppIcon(Utils.getPackageName());
    }

    /**
     * 获取App图标
     *
     * @param packageName 包名
     * @return App图标
     */
    public static Drawable getAppIcon(String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.applicationInfo.loadIcon(pm);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取App路径
     *
     * @return App路径
     */
    public static String getAppPath() {
        return getAppPath(Utils.getPackageName());
    }

    /**
     * 获取App路径
     *
     * @param packageName 包名
     * @return App路径
     */
    public static String getAppPath(String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.applicationInfo.sourceDir;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取App版本号
     *
     * @return App版本号
     */
    public static String getAppVersionName() {
        return getAppVersionName(Utils.getPackageName());
    }

    /**
     * 获取App版本号
     *
     * @param packageName 包名
     * @return App版本号
     */
    public static String getAppVersionName(String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取App版本码
     *
     * @return App版本码
     */
    public static int getAppVersionCode() {
        return getAppVersionCode(Utils.getPackageName());
    }

    /**
     * 获取App版本码
     *
     * @param packageName 包名
     * @return App版本码
     */
    public static int getAppVersionCode(String packageName) {
        if (isSpace(packageName)) return -1;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? -1 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 判断App是否是系统应用
     *
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isSystemApp() {
        return isSystemApp(Utils.getPackageName());
    }

    /**
     * 判断App是否是系统应用
     *
     * @param packageName 包名
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isSystemApp(String packageName) {
        if (isSpace(packageName)) return false;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
            return ai != null && (ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断App是否是Debug版本
     *
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isAppDebug() {
        return isAppDebug(Utils.getPackageName());
    }

    /**
     * 判断App是否是Debug版本
     *
     * @param packageName 包名
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isAppDebug(String packageName) {
        if (isSpace(packageName)) return false;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
            return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取App签名
     *
     * @return App签名
     */
    public static Signature[] getAppSignature() {
        return getAppSignature(Utils.getPackageName());
    }

    /**
     * 获取App签名
     *
     * @param packageName 包名
     * @return App签名
     */
    @SuppressLint("PackageManagerGetSignatures")
    public static Signature[] getAppSignature(String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            return pi == null ? null : pi.signatures;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取应用签名的的SHA1值
     *
可据此判断高德,百度地图key是否正确

     *
     * @return 应用签名的SHA1字符串, 比如:53:FD:54:DC:19:0F:11:AC:B5:22:9E:F1:1A:68:88:1B:8B:E8:54:42
     */
    public static String getAppSignatureSHA1() {
        return getAppSignatureSHA1(Utils.getPackageName());
    }

    /**
     * 获取应用签名的的SHA1值
     *
可据此判断高德,百度地图key是否正确

     *
     * @param packageName 包名
     * @return 应用签名的SHA1字符串, 比如:53:FD:54:DC:19:0F:11:AC:B5:22:9E:F1:1A:68:88:1B:8B:E8:54:42
     */
    public static String getAppSignatureSHA1(String packageName) {
        Signature[] signature = getAppSignature(packageName);
        if (signature == null) return null;
        return EncryptUtils.encryptSHA1ToString(signature[0].toByteArray()).
                replaceAll("(?<=[0-9A-F]{2})[0-9A-F]{2}", ":$0");
    }

    /**
     * 判断App是否处于前台
     *
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isAppForeground() {
        ActivityManager manager = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        if (infos == null || infos.size() == 0) return false;
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return info.processName.equals(Utils.getPackageName());
            }
        }
        return false;
    }

    /**
     * 判断App是否处于前台
     *
当不是查看当前App,且SDK大于21时,
     * 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}

     *
     * @param packageName 包名
     * @return {@code true}: 是
{@code false}: 否
     */
    public static boolean isAppForeground(String packageName) {
        return !isSpace(packageName) && packageName.equals(ProcessUtils.getForegroundProcessName());
    }

    /**
     * 封装App信息的Bean类
     */
    public static class AppInfo {

        private String name;
        private Drawable icon;
        private String packageName;
        private String packagePath;
        private String versionName;
        private int versionCode;
        private boolean isSystem;

        public Drawable getIcon() {
            return icon;
        }

        public void setIcon(Drawable icon) {
            this.icon = icon;
        }

        public boolean isSystem() {
            return isSystem;
        }

        public void setSystem(boolean isSystem) {
            this.isSystem = isSystem;
        }

        public String getName() {
            return name;
        }

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

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packagName) {
            this.packageName = packagName;
        }

        public String getPackagePath() {
            return packagePath;
        }

        public void setPackagePath(String packagePath) {
            this.packagePath = packagePath;
        }

        public int getVersionCode() {
            return versionCode;
        }

        public void setVersionCode(int versionCode) {
            this.versionCode = versionCode;
        }

        public String getVersionName() {
            return versionName;
        }

        public void setVersionName(String versionName) {
            this.versionName = versionName;
        }

        /**
         * @param name        名称
         * @param icon        图标
         * @param packageName 包名
         * @param packagePath 包路径
         * @param versionName 版本号
         * @param versionCode 版本码
         * @param isSystem    是否系统应用
         */
        public AppInfo(String packageName, String name, Drawable icon, String packagePath,
                       String versionName, int versionCode, boolean isSystem) {
            this.setName(name);
            this.setIcon(icon);
            this.setPackageName(packageName);
            this.setPackagePath(packagePath);
            this.setVersionName(versionName);
            this.setVersionCode(versionCode);
            this.setSystem(isSystem);
        }

        @Override
        public String toString() {
            return "App包名:" + getPackageName() +
                    "\nApp名称:" + getName() +
                    "\nApp图标:" + getIcon() +
                    "\nApp路径:" + getPackagePath() +
                    "\nApp版本号:" + getVersionName() +
                    "\nApp版本码:" + getVersionCode() +
                    "\n是否系统App:" + isSystem();
        }
    }

    /**
     * 获取App信息
     *
AppInfo(名称,图标,包名,版本号,版本Code,是否系统应用)

     *
     * @return 当前应用的AppInfo
     */
    public static AppInfo getAppInfo() {
        return getAppInfo(Utils.getPackageName());
    }

    /**
     * 获取App信息
     *
AppInfo(名称,图标,包名,版本号,版本Code,是否系统应用)

     *
     * @param packageName 包名
     * @return 当前应用的AppInfo
     */
    public static AppInfo getAppInfo(String packageName) {
        try {
            PackageManager pm = Utils.getContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return getBean(pm, pi);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 得到AppInfo的Bean
     *
     * @param pm 包的管理
     * @param pi 包的信息
     * @return AppInfo类
     */
    private static AppInfo getBean(PackageManager pm, PackageInfo pi) {
        if (pm == null || pi == null) return null;
        ApplicationInfo ai = pi.applicationInfo;
        String packageName = pi.packageName;
        String name = ai.loadLabel(pm).toString();
        Drawable icon = ai.loadIcon(pm);
        String packagePath = ai.sourceDir;
        String versionName = pi.versionName;
        int versionCode = pi.versionCode;
        boolean isSystem = (ApplicationInfo.FLAG_SYSTEM & ai.flags) != 0;
        return new AppInfo(packageName, name, icon, packagePath, versionName, versionCode, isSystem);
    }

    /**
     * 获取所有已安装App信息
     *
{@link #getBean(PackageManager, PackageInfo)}(名称,图标,包名,包路径,版本号,版本Code,是否系统应用)

     *
依赖上面的getBean方法

     *
     * @return 所有已安装的AppInfo列表
     */
    public static List<AppInfo> getAppsInfo() {
        List<AppInfo> list = new ArrayList<>();
        PackageManager pm = Utils.getContext().getPackageManager();
        // 获取系统中安装的所有软件信息
        List<PackageInfo> installedPackages = pm.getInstalledPackages(0);
        for (PackageInfo pi : installedPackages) {
            AppInfo ai = getBean(pm, pi);
            if (ai == null) continue;
            list.add(ai);
        }
        return list;
    }

    /**
     * 清除App所有数据
     *
     * @param dirPaths 目录路径
     * @return {@code true}: 成功
{@code false}: 失败
     */
    public static boolean cleanAppData(String... dirPaths) {
        File[] dirs = new File[dirPaths.length];
        int i = 0;
        for (String dirPath : dirPaths) {
            dirs[i++] = new File(dirPath);
        }
        return cleanAppData(dirs);
    }

    /**
     * 清除App所有数据
     *
     * @param dirs 目录
     * @return {@code true}: 成功
{@code false}: 失败
     */
    public static boolean cleanAppData(File... dirs) {
        boolean isSuccess = CleanUtils.cleanInternalCache();
        isSuccess &= CleanUtils.cleanInternalDbs();
        isSuccess &= CleanUtils.cleanInternalSP();
        isSuccess &= CleanUtils.cleanInternalFiles();
        isSuccess &= CleanUtils.cleanExternalCache();
        for (File dir : dirs) {
            isSuccess &= CleanUtils.cleanCustomCache(dir);
        }
        return isSuccess;
    }

    private static boolean isSpace(String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 得到计算不显示的控件高度
     * @param view
     * @return
     */
    public static int[] getMeasureViewSize(View view) {
        int size[] = new int[2];
        int width = View.MeasureSpec.makeMeasureSpec(0,
            View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0,
            View.MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        size[0] = view.getMeasuredWidth();
        size[1] = view.getMeasuredHeight();
        return size;
    }
}


text:
<?xml version="1.0"?>
<!--
  ~ Copyright 2015 JBoss, by Red Hat, Inc
  ~
  ~ 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.
  -->

<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.uberfire</groupId>
    <artifactId>uberfire-simple-docks</artifactId>
    <version>2.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>uberfire-simple-docks-client</artifactId>

  <name>Uberfire Simple Docks Client</name>
  <description>Uberfire Simple Docks Client</description>

  <dependencies>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.gwt.gwtmockito</groupId>
      <artifactId>gwtmockito</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-workbench-client-views-patternfly</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-common</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-ioc</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-user</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-javax-enterprise</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-client-all</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-workbench-client</artifactId>
    </dependency>
    <dependency>
      <groupId>org.gwtbootstrap3</groupId>
      <artifactId>gwtbootstrap3</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-testing-utils</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
.. _setup_development_environment:

=============================
Setup Development Environment
=============================

  .. attention:: If you would like any help setting up these environments, why not join our discord - https://discord.gg/64uhRztS6n

  .. attention:: This environment setup is designed for UAT/DEV environments on server environments. The settings.py file will have a unique secret_key, and the settings.py file can be customized without any chance of an accidently upload into source.

These instructions will help you install a development environment. Setup is
slightly different to a production environment.

It is recommended to install NearBeach on a Long Term Support (LTS) version of Django.
Security fixes/patches are applied for a longer period of time, helping keep your server secure.

NearBeach currently supports the following Django versions;

- Django Version 3.2+

More information about upgrading Django can be found `found in the Django Documentation <https://docs.djangoproject.com/en/3.0/howto/upgrade-version/>`_

.. note::
  The following instructions are for Ubuntu 18.04. If you are using a different operating system, modify the instructions to suit that operating system.

-----------------------
Download Git Repository
-----------------------

#. In a terminal, navigate to your project development folder

  .. code-block:: bash

    cd /<<project-dev-folder>>

#. Use Git to download NearBeach source code

  .. code-block:: bash

    git clone https://github.com/robotichead/NearBeach

#. First update and upgrade the system so you are working with the latest packages;

  .. code-block:: bash

    sudo apt-get update && sudo apt-get upgrade -y

#. Install the required system libraries for Django and NearBeach to working

  .. code-block:: bash

    sudo apt install python3-dev curl build-essential python3-setuptools shared-mime-info libjpeg-dev zlib1g-dev

#. Install pip

  .. code-block:: bash

    curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
    sudo python3 get-pip.py

#. After installing the required packages, you will need to update pip

  .. code-block:: bash

    sudo pip3 install --upgrade pip

#. Once pip is upgraded, you will need to create a virtual environment

  .. code-block:: bash

    sudo pip3 install virtualenv

#. Create your own virtual environment for python

  .. code-block:: bash

    virtualenv <<project_environment>>

  This will create a directory called "<<project_environment>>", this will store NearBeach's libraries for python

#. Activate the virtual environment using the following command

  .. code-block:: bash

    source ./<<project_environment>>/bin/activate

  You terminal prompt will change to indicate that it is working in the virtual environment now. It should look like the following

  .. code-block:: bash

    (<<project_environment>>)user@computer:

#. Install Django

  .. code-block:: bash

    pip install django

#. Create your project

  .. code-block:: bash

  djangoadmin startproject <<django_project>>

  .. note:: Please do NOT call the <<django_project>> NearBeach, or any variation of it.

#. Adjust the project's settings to allow debugging and accept ALL allowed hosts

  .. code-block:: bash

    nano ./<<django_project>>/<<django_project>>/settings.py

#. Change the following lines to reflect the following

  ..image:: images/django-installation-001.png

  This will allow us to test the web server.

  Save the settings file and exit

14. Run the following command to see if Django is running

  .. code-block:: bash

    python3 ./manage.py runserver

  If the server runs fine - then we can proceed.

15. Symbolic link in NearBeach's source code

  .. code-block:: bash

    ln -s /<<project-dev-folder>>/NearBeach/NearBeach /<<project-dev-folder>>/<<django_project>>

  This code will place the core NearBeach code into the Django's project directory.

16. Navigate to your project's folder

  .. code-block:: bash

    $ cd <<django_project_location>>

17. Install all required python files using pip

  .. code-block:: bash

    pip3 install -r ./NearBeach/requirements.txt

18. Edit the project's settings.py to include NearBeach

  .. code-block:: bash

    $ nano ./<<django_project>>/<<django_project>/settings.py

19. Add the following line to the top of "INSTALLED_APPS" section

  .. code-block:: bash

    'NearBeach.apps.NearBeachConfig',

  Now save the document

20. Email - optional however required for resetting passwords

  .. code-block:: bash

    $ nano ./<<project name>>/settings.py

  Add the following lines of code into the settings.py

  .. code-block:: bash

    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_USE_TLS = True
    EMAIL_HOST = '<< your email host >>'
    EMAIL_PORT = 25
    EMAIL_HOST_USER = '<< your username >>'
    EMAIL_HOST_PASSWORD = '<< your password >>'
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

21. Private Documents

  .. code-block:: bash

    nano ./<<project name>>/settings.py

  Add the following lines of code into the settings.py

  .. code-block:: bash

    PRIVATE_MEDIA_URL = '/private/' #Can change
    if DEBUG:
        # dev
        import os

        PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
        PRIVATE_MEDIA_ROOT = os.path.join(PROJECT_PATH, 'private')
        PRIVATE_MEDIA_SERVER = 'DefaultServer'
    else:
        # prod
        PRIVATE_MEDIA_ROOT = '<< private documents location >>'
        PRIVATE_MEDIA_SERVER = 'ApacheXSendfileServer'

  The following redundant code will need to be used at the moment.

  .. code-block:: bash

    STATIC_URL = '/static/'
    STATIC_ROOT= os.path.join(BASE_DIR,'static/')
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR,'media/')

22. Edit the project's URL.py to include NearBeach

  .. code-block:: bash

    nano ./<<django_project>>/url.py

  Please make sure that the following import in included at the top of the file

  .. code-block:: bash

    from django.urls import path, include

  Either of the following can be entered into the "urlpatterns" section

  .. code-block:: bash

    path('', include('NearBeach.urls')),
    path('tinymce/', include('tinymce.urls')),
    path('select2/', include('django_select2.urls')),

23. Create Database/Migrations

  The database will need to be setup. Please note by default Django uses sqlite3, however it is possible to setup NearBeach to use a mysql database.

  .. code-block:: bash

    python ./manage.py migrate
    python ./manage.py migrate NearBeach

  If you have setup NearBeach with an SQLite database, you will need to change it's permissions so nginx can access it

  ..  code-block:: bash

    sudo chmod 7777 ./db.sqlite

24. Create superuser
  A superuser will need to be created. This superuser will be able to enter the ADMIN site of Django, which from there will be able to do administration items.

  .. code-block:: bash

    python ./manage.py createsuperuser

  Enter in the correct details for the superuser

25. Collect the static

  The website uses static images, javascript, and CSS. You will need to collect this data to the static folder (set in the settings.py). Please run the following command

  .. code-block:: bash

    python ./manage.py collectstatic

26. Create the private media folder

  .. code-block:: bash

    $ mkdir ./private_media/

The NearBeach development environment should now be setup on your local.

.. note:: The first user to log in will automatically get administration permissions. It is recommended to get the system admin to log in first before importing any user data from other sources. This also allows the admin to setup groups and permissions.


text:
/**
 * Created by Administrator on 9/10/14.
 */

// --NOTES-------------
//
// nodemon -e js,coffee --ignore out/ --ignore src/  server.js
//
// coffee -o _out -c chathub.coffee
//

console.log('+02+++++++++++++++++++++++++++');

var qVERSION=require('./version.js');
console.log(qVERSION);
var zversion=qVERSION.vname+'-q00';

if(!process.env.PORT){
	process.env.LEBANTAX=true;
	//process.env.LEBANTAX=false;
}

var coffee 	=require('coffee-script/register');
var myapp	=require('./main.coffee');

myapp.chathub.qVERSION=qVERSION;
myapp.chathub.hubvn=zversion;

var fs=require('fs');
var http=require('http');
fs.writeFile('_appid.json', JSON.stringify({appid:myapp.appid}), function(err){ if(err)console.log(err); });
console.log('appid='+myapp.appid);

try{ fs.mkdirSync(__dirname+'/__temp__/'); } catch(e){ console.log(e.message); }
try{ fs.mkdirSync(__dirname+'/__save__/'); } catch(e){ console.log(e.message); }
try{ fs.mkdirSync(__dirname+'/__sign__/'); } catch(e){ console.log(e.message); }

if(process.env.PORT){

	function timedHandler(){
		console.log(zversion + ' : '+ (myapp.appid%1000000) + ' - '+ (Date.now()-myapp.appid)/1000);
		//setTimeout(timedHandler, 60000);
	}
	timedHandler();
	setInterval(timedHandler, 60000);

	// setTimeout(function(){
	// 	console.log('['+myapp.appid+']'+' =exit======================================')
	// 	process.exit();
	// 	},50000*1000);

	function checkHub(){

		if(process.env.PORT){
			http.get("http://vatrahoi.azurewebsites.net/appid", function(res) {
				//console.log("Got response: " + res.statusCode);
				res.on('data',function(data){
					//console.log("Got appid: " + data);
				});
			}).on('error', function(e) {
				console.log("Got error: " + e.message);
			});
		}

		fs.readFile('_appid.json', 'utf8', function(err, data){
			//console.log('checkHub:'+data);
			if(err){
				console.log(err);
				return;
			}
			if(JSON.parse(data).appid==myapp.appid){
				setTimeout( checkHub ,  30*1000 );
				return;
			}

			myapp.chathub.cleanup();
		});
	}
	setTimeout( checkHub ,  10*1000 );

	function wakeupBot(){
		http.get("http://quaxbot.azurewebsites.net/appid.json", function(res) {
			//console.log("Got response: " + res.statusCode);
			res.on('data',function(data){
				console.log("Got from Bot: " + (''+data).substring(0,256));
			});
		}).on('error', function(e) {
			console.log("Got Bot error: " + e.message);
		});
		setTimeout( wakeupBot ,  10*60*1000 );
	}
	setTimeout( wakeupBot ,  5*1000 );
}


text:
<?php

namespace Phlexible\Component\MediaCache\Storage;

use Phlexible\Bundle\MediaCacheBundle\Entity\CacheItem;
use Phlexible\Component\MediaManager\Volume\ExtendedFileInterface;

/**
 * Storage interface
 *
 * @author Peter Fahsel <pfahsel@brainbits.net>
 */
interface StorageInterface
{
    /**
     * @param CacheItem $cacheItem
     * @param string    $filename
     */
    public function store(CacheItem $cacheItem, $filename);

    /**
     * @param ExtendedFileInterface $file
     * @param string                $baseUrl
     *
     * @return array
     */
    public function getUrls(ExtendedFileInterface $file, $baseUrl);

    /**
     * @param ExtendedFileInterface $file
     * @param CacheItem             $cacheItem
     * @param string                $baseUrl
     *
     * @return array
     */
    public function getCacheUrls(ExtendedFileInterface $file, CacheItem $cacheItem, $baseUrl);

    /**
     * @param CacheItem $cacheItem
     *
     * @return string
     */
    public function getLocalPath(CacheItem $cacheItem);

    /**
     * @param string $fileId
     * @param string $fileName
     */
    public function deleteByFileId($fileId, $fileName);
}


text:
package com.alibaba.aliper.remote.proxy;

public class ProxyException extends RuntimeException {
	public ProxyException(Exception e) {
		super(e);
	}

	public ProxyException(String message) {
		super(message);
	}
}


text:
package org.fnet.oldschool.entities;

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;

import org.fnet.oldschool.Logics;
import org.fnet.oldschool.Main;
import org.fnet.oldschool.Manager;
import org.fnet.oldschool.PublicVars;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.util.ResourceLoader;

public class Overlay {

	private static boolean soundEnabled = Boolean.parseBoolean(System.getProperty("os.music", String.valueOf(true))),
			mouseClicked = false;
	public static int score = 0, highscore = score, round = 0;
	public static long lasttime = 0, besttime = 0;

	public static void drawDefault() throws IOException {
		font.drawString(10, 10, "SCORE     : " + score);
		font.drawString(10, 40, "HIGHSCORE : " + highscore);
		font.drawString(200, 10, "TIME : " + (Logics.getTime() / 1000 - lasttime) + 's');
		font.drawString(200, 40, "BEST : " + besttime + 's');
		font.drawString(350, 10, "ROUND : " + round);
	}

	private static TrueTypeFont font;

	public static void newRound() {
		final long current = Logics.getTime() / 1000;
		if (round == 1) {
			besttime = current - lasttime;
		} else {
			besttime = Math.min(besttime, current - lasttime);
		}
		lasttime = current;
		round++;
	}

	public static void init() throws FontFormatException, IOException {
		font = new TrueTypeFont(
				Font.createFont(Font.TRUETYPE_FONT, ResourceLoader.getResourceAsStream("res/fonts/data-latin.ttf"))
						.deriveFont(24f),
				false);
	}

	public static void drawPauseMenu() throws IOException {
		Texture overlay = Manager.getPng("overlay");
		Texture close = Manager.getPng("close");
		Texture exit = Manager.getPng("exit");
		Texture sound_mute = Manager.getPng("sound_mute");
		Texture sound_unmute = Manager.getPng("sound_unmute");
		Manager.draw(overlay, 0, 0, PublicVars.DISPLAY_WIDTH, PublicVars.DISPLAY_HEIGHT);
		Manager.draw(close, PublicVars.DISPLAY_WIDTH - 35, 5, 30, 30);
		Manager.draw(exit, PublicVars.DISPLAY_WIDTH - 70, 5, 30, 30);
		if (!soundEnabled) {
			Manager.draw(sound_mute, PublicVars.DISPLAY_WIDTH - 105, 5, 30, 30);
		} else {
			Manager.draw(sound_unmute, PublicVars.DISPLAY_WIDTH - 105, 5, 30, 30);
		}
		if (Mouse.isButtonDown(0)) {
			if (Manager.mouseIsInRangeOf(PublicVars.DISPLAY_WIDTH - 35, 5, 30, 30)) {
				Main.closeOverlay();
			} else if (Manager.mouseIsInRangeOf(PublicVars.DISPLAY_WIDTH - 70, 5, 30, 30)) {
				Main.close();
			} else if (Manager.mouseIsInRangeOf(PublicVars.DISPLAY_WIDTH - 105, 5, 30, 30)) {
				if (!mouseClicked) {
					mouseClicked = true;
					if (soundEnabled) {
						Manager.getOgg("music").stop();
						soundEnabled = false;
					} else {
						Manager.getOgg("music").playAsMusic(1, 1, true);
						soundEnabled = true;
					}
				}
			}
		} else {
			mouseClicked = false;
		}
	}

}


text:
describe Snapshot do
  describe Snapshot::TestCommandGenerator do
    describe "Valid Configuration" do
      before do
        options = { project: "./example/Example.xcodeproj", scheme: "ExampleUITests" }
        Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options)
      end

      it "uses the default parameters" do
        expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
        command = Snapshot::TestCommandGenerator.generate(device_type: "Something")
        ios = command.join('').match(/OS=(\d+.\d+)/)[1]
        expect(command).to eq([
          "set -o pipefail &&",
          "xcodebuild",
          "-scheme 'ExampleUITests'",
          "-project './example/Example.xcodeproj'",
          "-derivedDataPath '/tmp/path/to/snapshot_derived'",
          "-destination 'platform=iOS Simulator,id=,OS=#{ios}'",
          :build,
          :test,
          "| tee '#{File.expand_path('~/Library/Logs/snapshot/Example-ExampleUITests.log')}' | xcpretty "
        ])
      end
    end
  end
end


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

    var module = angular.module('angular-token-auth.auth', [
        'angular-token-auth.auth-storage',
    ]);

    module.factory('authFactory', [
        '$rootScope',
        'authStorageFactory',
        'authModuleSettings',
        function ($rootScope, authStorageFactory, MODULE_SETTINGS) {
            return {
                getAuth: function () {
                    var auth = authStorageFactory.get('auth');
                    if (angular.isObject(auth)) {
                        return auth;
                    }
                    return null;
                },
                getToken: function () {
                    var auth = this.getAuth();
                    if (auth !== null && angular.isDefined(auth.token)) {
                        return auth.token;
                    }
                    return null;
                },
                getHeaderPrefix: function () {
                    var auth = this.getAuth();
                    if (auth !== null && angular.isDefined(auth.prefix)) {
                        return auth.prefix;
                    }
                    return MODULE_SETTINGS.AUTH_HEADER_PREFIX;
                },
                getAuthHeader: function () {
                    var token = this.getToken();
                    if (token) {
                        return this.getHeaderPrefix() + ' ' + token;
                    }
                    return null;
                },
                setAuth: function (data) {
                    authStorageFactory.set('auth', data);
                    $rootScope.$broadcast('tokenAuth:set');
                },
                clearAuth: function () {
                    authStorageFactory.clear('auth');
                    $rootScope.$broadcast('tokenAuth:clear');
                },
            };
        }]);

}(window.angular));


text:
package pro.taskana.monitor.api;

import pro.taskana.task.api.models.Task;

/** This enum contains all timestamps saved in the database table for a {@linkplain Task}. */
public enum TaskTimestamp {
  CREATED,
  CLAIMED,
  COMPLETED,
  MODIFIED,
  PLANNED,
  DUE
}


text:
template <typename T>
int flipToWin(T bits)
{
    static_assert(std::is_unsigned<T>::value, "T must be unsigned integral type");

    int result = 1;
    int lenLeft = 0;
    int lenRight = 0;
    while (bits != 0)
    {
        if (bits & 1)
            ++lenLeft;
        else
        {
            // The current bit is 0 means that we counted right sequence length.
            // If the next bit will be 0, then right sequence length will reset to 0.
            lenRight = lenLeft;
            lenLeft = 0;
        }
        bits >>= 1;
        result = std::max(lenRight + lenLeft + 1, result);
    }
    // We can not flip bit to 1 if there was no bit 0
    return std::min(result, std::numeric_limits<T>::digits);
}

int main()
{
    for (auto testValue : {
                0b11011101111U
            ,  0b110111001111U
            , 0b1100111001111U
            , 0U
            , ~0U
        })
        std::cout << bits(testValue) << ": " << flipToWin(testValue) << std::endl;
}


text:
#ifndef __NSPortMessage_h_GNUSTEP_BASE_INCLUDE
#define __NSPortMessage_h_GNUSTEP_BASE_INCLUDE
#import	<GNUstepBase/GSVersionMacros.h>

#import	<Foundation/NSArray.h>
#import	<Foundation/NSPort.h>

#if	defined(__cplusplus)
extern "C" {
#endif

/**
 *
The data transported for distributed objects communications is sent over
 * the network encapsulated by NSPortMessage objects, which consist of two
 * [NSPort]s (sender and receiver, not sent over the network) and a body
 * consisting of one or more [NSData] or [NSPort] objects. (Data in the
 * [NSData] must be in network byte order.)

 *
 *
See the [NSConnection] and [NSPortCoder] classes.

 */
@interface	NSPortMessage : NSObject
{
#if	GS_EXPOSE(NSPortMessage)
@private
  unsigned		_msgid;
  NSPort		*_recv;
  NSPort		*_send;
  NSMutableArray	*_components;
#endif
#if     GS_NONFRAGILE
#else
  /* Pointer to private additional data used to avoid breaking ABI
   * when we don't have the non-fragile ABI available.
   * Use this mechanism rather than changing the instance variable
   * layout (see Source/GSInternal.h for details).
   */
  @private id _internal GS_UNUSED_IVAR;
#endif
}
/**
 * OpenStep compatibility.
 */
- (id) initWithMachMessage: (void*)buffer;

/** <init/> Initializes to send message described by items (which should
 * contain only [NSPort] and/or [NSData] objects, with contents in network
 * byte order) over aPort.  If/when a reply to the message is sent, it will
 * arrive on anotherPort.
 */
- (id) initWithSendPort: (NSPort*)aPort
	    receivePort: (NSPort*)anotherPort
	     components: (NSArray*)items;

/**
 * Request that the message be sent before when.  Will block until either
 * sends it (returns YES) or when expires (returns NO).  The latter may occur
 * if many messages are queued up (by multiple threads) faster than they can
 * be sent over the network.
 */
- (BOOL) sendBeforeDate: (NSDate*)when;

/**
 * Returns the message components originally used to constitute this message.
 */
- (NSArray*) components;

/**
 * For an outgoing message, returns the port the receiver will send itself
 * through.  For an incoming message, returns the port replies to the receiver
 * should be sent through.
 */
- (NSPort*) sendPort;

/**
 * For an outgoing message, returns the port on which a reply to this message
 * will arrive.  For an incoming message, returns the port this message
 * arrived on.
 */
- (NSPort*) receivePort;

/**
 * Sets ID for message.  This is not used by the distributed objects system,
 * but may be used in custom ways by cooperating applications to sort or
 * otherwise organize messages.
 */
- (void) setMsgid: (unsigned)anId;

/**
 * Returns ID for message.  This is not used by the distributed objects
 * system, but may be used in custom ways by cooperating applications to sort
 * or otherwise organize messages.  Set to 0 initially.
 */
- (unsigned) msgid;
@end

#if	defined(__cplusplus)
}
#endif

#endif


text:
"""Guide: new, non-linear learning experience module."""

__author__ = [
    'davyrisso@google.com (Davy Risso)',
]

from models import custom_modules

from modules.guide import constants
from modules.guide import course_settings
from modules.guide import graphql
from modules.guide import handlers
from modules.guide import messages
from modules.guide import settings

def register_module():
    course_settings.register()
    graphql.register()

    global custom_module  # pylint: disable=global-statement
    custom_module = custom_modules.Module(
        constants.MODULE_TITLE, messages.MODULE_DESCRIPTION,
        handlers.global_routes,
        handlers.namespaced_routes + settings.namespaced_routes)

    return custom_module

custom_module = None


text: export * from './ThriftClientTTwitterFilter'


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Locking;

use Closure;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\DBAL\Logging\EchoSQLLogger;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use GearmanWorker;
use InvalidArgumentException;
use const GEARMAN_SUCCESS;
use function is_array;
use function microtime;
use function sleep;
use function unserialize;

class LockAgentWorker
{
    private $em;

    public static function run()
    {
        $lockAgent = new LockAgentWorker();

        $worker = new GearmanWorker();
        $worker->addServer(
            $_SERVER['GEARMAN_HOST'] ?? null,
            $_SERVER['GEARMAN_PORT'] ?? 4730
        );
        $worker->addFunction('findWithLock', [$lockAgent, 'findWithLock']);
        $worker->addFunction('dqlWithLock', [$lockAgent, 'dqlWithLock']);
        $worker->addFunction('lock', [$lockAgent, 'lock']);

        while ($worker->work()) {
            if ($worker->returnCode() !== GEARMAN_SUCCESS) {
                echo 'return_code: ' . $worker->returnCode() . "\n";
                break;
            }
        }
    }

    protected function process($job, Closure $do)
    {
        $fixture = $this->processWorkload($job);

        $s = microtime(true);
        $this->em->beginTransaction();
        $do($fixture, $this->em);

        sleep(1);
        $this->em->rollback();
        $this->em->clear();
        $this->em->close();
        $this->em->getConnection()->close();

        return microtime(true) - $s;
    }

    public function findWithLock($job)
    {
        return $this->process($job, static function ($fixture, $em) {
            $entity = $em->find($fixture['entityName'], $fixture['entityId'], $fixture['lockMode']);
        });
    }

    public function dqlWithLock($job)
    {
        return $this->process($job, static function ($fixture, $em) {
            /** @var Doctrine\ORM\Query $query */
            $query = $em->createQuery($fixture['dql']);

            $query->setLockMode($fixture['lockMode']);
            $query->setParameters($fixture['dqlParams']);
            $result = $query->getResult();
        });
    }

    public function lock($job)
    {
        return $this->process($job, static function ($fixture, $em) {
            $entity = $em->find($fixture['entityName'], $fixture['entityId']);

            $em->lock($entity, $fixture['lockMode']);
        });
    }

    protected function processWorkload($job)
    {
        echo 'Received job: ' . $job->handle() . ' for function ' . $job->functionName() . "\n";

        $workload = $job->workload();
        $workload = unserialize($workload);

        if (! isset($workload['conn']) || ! is_array($workload['conn'])) {
            throw new InvalidArgumentException('Missing Database parameters');
        }

        $this->em = $this->createEntityManager($workload['conn']);

        if (! isset($workload['fixture'])) {
            throw new InvalidArgumentException('Missing Fixture parameters');
        }

        return $workload['fixture'];
    }

    protected function createEntityManager($conn)
    {
        $config = new Configuration();
        $config->setProxyDir(__DIR__ . '/../../../Proxies');
        $config->setProxyNamespace('MyProject\Proxies');
        $config->setAutoGenerateProxyClasses(true);

        $annotDriver = $config->newDefaultAnnotationDriver([__DIR__ . '/../../../Models/']);
        $config->setMetadataDriverImpl($annotDriver);

        $cache = new ArrayCache();
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
        $config->setSQLLogger(new EchoSQLLogger());

        return EntityManager::create($conn, $config);
    }
}

LockAgentWorker::run();


text:
'use strict';

var pg = require('pg'),
    async = require('async'),
    config = require('./config/config').database;

var conString = 'postgres://' + config.username + ':' + config.password +
    '@' + config.options.host + '/' + config.database;

var queryList = [
    query('SELECT count(*) from threads', 'Thread Count:', 'count'),
    query('SELECT count(*) from thread_rank', 'Thread Rank Count:', 'count'),
    query('SELECT count(*) from threads where "createdAt" = now()::date', 'Today thread count:', 'count'),
    query('SELECT count(*) from thread_rank where "createdAt" = now()::date', 'Today rank count:', 'count')
];

var client = new pg.Client(conString);
    client.connect(function(err) {
        if(err) {
            return console.error('could not connect to postgres', err);
        }
        async.parallel(queryList, function () {
                client.end();
            });
});

function query(queryString, title, key) {
    return function query(callback) {
        client.query(queryString, function(err, result) {
            if(err) {
                console.error('error running query', err);
                return callback(err);
            }
            console.log(title, result.rows[0][key]);
            return callback();
        });
    };
}


text:
<?php

namespace DvsaCommon\ApiClient\Person\PerformanceDashboardStats\Dto;

use DvsaCommon\DtoSerialization\ReflectiveDtoInterface;
/**
 * All the tester's stats for the day.
 */
class DayPerformanceDashboardStatsDto implements ReflectiveDtoInterface
{
    private $total;
    private $numberOfPasses;
    private $numberOfFails;

    /**
     * @return int
     */
    public function getTotal()
    {
        return $this->total;
    }

    /**
     * @param int $total
     * @return $this
     */
    public function setTotal($total)
    {
        $this->total = $total;
        return $this;
    }

    /**
     * @return int
     */
    public function getNumberOfPasses()
    {
        return $this->numberOfPasses;
    }

    /**
     * @param int $numberOfPasses
     * @return $this
     */
    public function setNumberOfPasses($numberOfPasses)
    {
        $this->numberOfPasses = $numberOfPasses;
        return $this;
    }

    /**
     * @return int
     */
    public function getNumberOfFails()
    {
        return $this->numberOfFails;
    }

    /**
     * @param int $numberOfFails
     * @return $this
     */
    public function setNumberOfFails($numberOfFails)
    {
        $this->numberOfFails = $numberOfFails;
        return $this;
    }
}


text:
package main

import (
	"bufio"
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path"
	"strings"

	"github.com/codegangsta/cli"
	"github.com/docker-library/go-dockerlibrary/manifest"
)

var dockerFromCache = map[string]string{}

func (r Repo) DockerFrom(entry *manifest.Manifest2822Entry) (string, error) {
	return r.ArchDockerFrom(arch, entry)
}

func (r Repo) ArchDockerFrom(arch string, entry *manifest.Manifest2822Entry) (string, error) {
	commit, err := r.fetchGitRepo(arch, entry)
	if err != nil {
		return "", err
	}

	dockerfileFile := path.Join(entry.ArchDirectory(arch), entry.ArchFile(arch))

	cacheKey := strings.Join([]string{
		commit,
		dockerfileFile,
	}, "\n")
	if from, ok := dockerFromCache[cacheKey]; ok {
		return from, nil
	}

	dockerfile, err := gitShow(commit, dockerfileFile)
	if err != nil {
		return "", err
	}
	defer dockerfile.Close()

	from, err := dockerfileFrom(dockerfile)
	if err != nil {
		return "", err
	}

	if err := dockerfile.Close(); err != nil {
		return "", err
	}

	// make sure to add ":latest" if it's implied
	from = latestizeRepoTag(from)

	dockerFromCache[cacheKey] = from
	return from, nil
}

// TODO determine multi-stage-builds impact here (once official images are willing/able to support them; post-17.06 at the earliest)
func dockerfileFrom(dockerfile io.Reader) (string, error) {
	scanner := bufio.NewScanner(dockerfile)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" {
			// ignore blank lines
			continue
		}
		if line[0] == '#' {
			// ignore comments
			continue
		}
		fields := strings.Fields(line)
		if len(fields) < 1 {
			continue
		}
		if strings.ToUpper(fields[0]) == "FROM" {
			return fields[1], nil
		}
	}
	if err := scanner.Err(); err != nil {
		return "", err
	}
	return "", nil
}

func (r Repo) DockerCacheName(entry *manifest.Manifest2822Entry) (string, error) {
	cacheHash, err := r.dockerCacheHash(entry)
	if err != nil {
		return "", err
	}
	return "bashbrew/cache:" + cacheHash, err
}

func (r Repo) dockerCacheHash(entry *manifest.Manifest2822Entry) (string, error) {
	uniqueBits, err := r.dockerBuildUniqueBits(entry)
	if err != nil {
		return "", err
	}
	uniqueString := strings.Join(uniqueBits, "\n")
	b := sha256.Sum256([]byte(uniqueString))
	return hex.EncodeToString(b[:]), nil
}

func dockerInspect(format string, args ...string) (string, error) {
	args = append([]string{"inspect", "-f", format}, args...)
	out, err := exec.Command("docker", args...).Output()
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return "", fmt.Errorf("%v\ncommand: docker inspect -f %q %q\n%s", ee, format, args, string(ee.Stderr))
		}
	}
	return strings.TrimSpace(string(out)), nil
}

var dockerFromIdCache = map[string]string{
	"scratch": "scratch",
}

func (r Repo) dockerBuildUniqueBits(entry *manifest.Manifest2822Entry) ([]string, error) {
	from, err := r.DockerFrom(entry)
	if err != nil {
		return nil, err
	}
	fromId, ok := dockerFromIdCache[from]
	if !ok {
		var err error
		fromId, err = dockerInspect("{{.Id}}", from)
		if err != nil {
			return nil, err
		}
		dockerFromIdCache[from] = fromId
	}
	return []string{
		entry.ArchGitRepo(arch),
		entry.ArchGitCommit(arch),
		entry.ArchDirectory(arch),
		entry.ArchFile(arch),
		fromId,
	}, nil
}

func dockerBuild(tag string, file string, context io.Reader) error {
	args := []string{"build", "-t", tag, "-f", file, "--rm", "--force-rm"}
	args = append(args, "-")
	cmd := exec.Command("docker", args...)
	cmd.Stdin = context
	if debugFlag {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		fmt.Printf("$ docker %q\n", args)
		return cmd.Run()
	} else {
		buf := &bytes.Buffer{}
		cmd.Stdout = buf
		cmd.Stderr = buf
		err := cmd.Run()
		if err != nil {
			err = cli.NewMultiError(err, fmt.Errorf(`docker %q output:%s`, args, "\n"+buf.String()))
		}
		return err
	}
}

func dockerTag(tag1 string, tag2 string) error {
	if debugFlag {
		fmt.Printf("$ docker tag %q %q\n", tag1, tag2)
	}
	_, err := exec.Command("docker", "tag", tag1, tag2).Output()
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return fmt.Errorf("%v\ncommand: docker tag %q %q\n%s", ee, tag1, tag2, string(ee.Stderr))
		}
	}
	return err
}

func dockerPush(tag string) error {
	if debugFlag {
		fmt.Printf("$ docker push %q\n", tag)
	}
	_, err := exec.Command("docker", "push", tag).Output()
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return fmt.Errorf("%v\ncommand: docker push %q\n%s", ee, tag, string(ee.Stderr))
		}
	}
	return err
}

func dockerPull(tag string) error {
	if debugFlag {
		fmt.Printf("$ docker pull %q\n", tag)
	}
	_, err := exec.Command("docker", "pull", tag).Output()
	if err != nil {
		if ee, ok := err.(*exec.ExitError); ok {
			return fmt.Errorf("%v\ncommand: docker pull %q\n%s", ee, tag, string(ee.Stderr))
		}
	}
	return err
}


text:
package engine.game.gameloop;

import engine.Entity;
import engine.Event;
import engine.entities.CharacterEntity;
import engine.events.CollisionEvent;
import engine.events.KeyPressEvent;
import engine.events.TimerEvent;
import engine.game.LevelManager;
import engine.game.eventobserver.CollisionObservable;
import engine.game.eventobserver.InputObservable;
import engine.game.eventobserver.TimerObservable;
import engine.graphics.GraphicsEngine;
import engine.graphics.cameras.ScrollingCamera;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.util.Duration;

/**
 * Manages the highest level of time flow in the game.
 *
 * @author Matthew Barbano
 * @author Jay Doherty
 *
 */
public class OldGameLoopBackup {
	private static final int FRAME_TIME_MILLISECONDS = 20;
	private GraphicsEngine graphicsEngine;
	private LevelManager levelManager;
	private Timeline timeline;
	private InputObservable inputObservable;
	private CollisionObservable collisionObservable;
	private TimerObservable timerObservable;

	/**
	 * currentLevelManager is instantiated in the Game Authoring Environment
	 * (probably somewhere in the authoring.settings package)
	 *
	 * @param currentLevelManager
	 */
	public OldGameLoopBackup(Scene gameScene, String gameFilename) {
		// Setup Observables - at beginning of entire game only
		inputObservable = new InputObservable();
		collisionObservable = new CollisionObservable();
		timerObservable = new TimerObservable();

		// Setup levelManager
		levelManager = new LevelManager(gameFilename);
		//levelManager.loadAllSavedLevels(gameFilename);

		//More Observables - at beginning of each level only
		inputObservable.setupInputListeners(gameScene);
		timerObservable.attachCurrentLevelTimerManager(levelManager.getCurrentLevel().getTimerManager());

		// Give all Events belonging to Entities in the current Level their
		// corresponding Observables
		for (Entity entity : levelManager.getCurrentLevel().getEntities()) {
			for (Event event : entity.getEvents()) {
				if (event instanceof KeyPressEvent) {
					event.setEventObservable(inputObservable);
				}
				else if (event instanceof CollisionEvent){
					event.setEventObservable(collisionObservable);
				}
				else if (event instanceof TimerEvent){
					event.setEventObservable(timerObservable);
				}
			}
		}

		// Attach entities in current level to observables
		for (Entity entity : levelManager.getCurrentLevel().getEntities()) {
			inputObservable.attach(entity);
			collisionObservable.attach(entity);
			timerObservable.attach(entity);
		}

		// Start the GAE's current level in Level Manager
		//levelManager.startCurrentLevel();

		//Set up graphical view
		setupGameView();

		//Start timeline
		setupTimeline();
	}

	private void setupTimeline() {
		// From ExampleBounce.java (will likely upgrade)
		KeyFrame frame = new KeyFrame(Duration.millis(FRAME_TIME_MILLISECONDS), e -> step());
		timeline = new Timeline();
		timeline.setCycleCount(Timeline.INDEFINITE);
		timeline.getKeyFrames().add(frame);
	}

	/**
	 * External Engine API. Proceeds to the next frame of the animation while
	 * the game is playing. Responsibilities include: - loop through all
	 * Entities and call AlwaysEvent's act() (for Actions that occur on every
	 * frame, such as an enemy moving) - for all three types of Observer Events,
	 * call updateObservables() - and more
	 */
	public void startTimeline() {
		timeline.play();
	}

	public Pane getGameView() {
		return graphicsEngine.getView();
	}

	private void setupGameView() {
		graphicsEngine = new GraphicsEngine();
		graphicsEngine.setEntitiesCollection(levelManager.getCurrentLevel().getEntities());
		//TODO: Remove the following (just for tests)
		//Entity mario = new CharacterEntity("Mario", "file:" + System.getProperty("user.dir") + "/src/resources/images/mario.png");
		//mario.setX(200);
		//mario.setY(200);
		//mario.setWidth(100);
		//mario.setHeight(100);
		//levelManager.getCurrentLevel().getEntities().add(mario);
	}

	private void step() {
		inputObservable.updateObservers();
		collisionObservable.updateObservers();
		timerObservable.updateObservers();   //ticks the clock (need to at beginning of step(), not end, because onFinished of Timeline called at END of time elapsed

		for (Entity entity : levelManager.getCurrentLevel().getEntities()) {
			entity.update();
		}

		inputObservable.setInputToProcess(false);

		printStepData();

		//OK to do for BOTH TickUp and TickDown timers!
		//This is NOT repeating the TimerObservable DP's job - this changes the game loop's flow, that calls Actions on Entities
		if(levelManager.getCurrentLevel().getTimerManager().timeIsUp()){
			 System.out.println("Game over - you ran out of time!");
			 timeline.stop();
		}

		graphicsEngine.updateFrame();
	}

	/**
	 * Temporary, for testing. Will be removed later.
	 */
	private void printStepData(){
		System.out.println(levelManager.getCurrentLevel().getTimerManager());
	}
}


text:
module Fog
  module Compute
    class Glesys
      class Real
        def template_list
          request("/server/templates")
        end
      end
    end
  end
end


text:
define("dijit/form/RangeBoundTextBox", [
	"dojo/_base/declare", // declare
	"dojo/i18n", // i18n.getLocalization
	"./MappedTextBox"
], function(declare, i18n, MappedTextBox){

	// module:
	//		dijit/form/RangeBoundTextBox

	var RangeBoundTextBox = declare("dijit.form.RangeBoundTextBox", MappedTextBox, {
		// summary:
		//		Base class for textbox form widgets which defines a range of valid values.

		// rangeMessage: String
		//		The message to display if value is out-of-range
		rangeMessage: "",

		/*=====
		// constraints: RangeBoundTextBox.__Constraints
		constraints: {},
		======*/

		rangeCheck: function(/*Number*/ primitive, /*dijit/form/RangeBoundTextBox.__Constraints*/ constraints){
			// summary:
			//		Overridable function used to validate the range of the numeric input value.
			// tags:
			//		protected
			return	("min" in constraints? (this.compare(primitive,constraints.min) >= 0) : true) &&
				("max" in constraints? (this.compare(primitive,constraints.max) <= 0) : true); // Boolean
		},

		isInRange: function(/*Boolean*/ /*===== isFocused =====*/){
			// summary:
			//		Tests if the value is in the min/max range specified in constraints
			// tags:
			//		protected
			return this.rangeCheck(this.get('value'), this.constraints);
		},

		_isDefinitelyOutOfRange: function(){
			// summary:
			//		Returns true if the value is out of range and will remain
			//		out of range even if the user types more characters
			var val = this.get('value');
			if(val == null){ return false; } // not yet valid enough to compare to
			var outOfRange = false;
			if("min" in this.constraints){
				var min = this.constraints.min;
				outOfRange = this.compare(val, ((typeof min == "number") && min >= 0 && val != 0) ? 0 : min) < 0;
			}
			if(!outOfRange && ("max" in this.constraints)){
				var max = this.constraints.max;
				outOfRange = this.compare(val, ((typeof max != "number") || max > 0) ? max : 0) > 0;
			}
			return outOfRange;
		},

		_isValidSubset: function(){
			// summary:
			//		Overrides `dijit/form/ValidationTextBox._isValidSubset()`.
			//		Returns true if the input is syntactically valid, and either within
			//		range or could be made in range by more typing.
			return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
		},

		isValid: function(/*Boolean*/ isFocused){
			// Overrides dijit/form/ValidationTextBox.isValid() to check that the value is also in range.
			return this.inherited(arguments) &&
				((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			// Overrides dijit/form/ValidationTextBox.getErrorMessage() to print "out of range" message if appropriate
			var v = this.get('value');
			if(v != null /* and !undefined */ && v !== '' && (typeof v != "number" || !isNaN(v)) && !this.isInRange(isFocused)){ // don't check isInRange w/o a real value
				return this.rangeMessage; // String
			}
			return this.inherited(arguments);
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			if(!this.rangeMessage){
				this.messages = i18n.getLocalization("dijit.form", "validate", this.lang);
				this.rangeMessage = this.messages.rangeMessage;
			}
		},

		_setConstraintsAttr: function(/*Object*/ constraints){
			this.inherited(arguments);
			if(this.focusNode){ // not set when called from postMixInProperties
				if(this.constraints.min !== undefined){
					this.focusNode.setAttribute("aria-valuemin", this.constraints.min);
				}else{
					this.focusNode.removeAttribute("aria-valuemin");
				}
				if(this.constraints.max !== undefined){
					this.focusNode.setAttribute("aria-valuemax", this.constraints.max);
				}else{
					this.focusNode.removeAttribute("aria-valuemax");
				}
			}
		},

		_setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){
			// summary:
			//		Hook so set('value', ...) works.

			this.focusNode.setAttribute("aria-valuenow", value);
			this.inherited(arguments);
		},

		applyTextDir: function(/*===== element, text =====*/){
			// summary:
			//		The function overridden in the _BidiSupport module,
			//		originally used for setting element.dir according to this.textDir.
			//		In this case does nothing.
			// element: Object
			// text: String
			// tags:
			//		protected.
		}
	});
	/*=====
	RangeBoundTextBox.__Constraints = declare(null, {
		// min: Number
		//		Minimum signed value.  Default is -Infinity
		// max: Number
		//		Maximum signed value.  Default is +Infinity
	});
	=====*/
	return RangeBoundTextBox;
});


text:
<?php
// Vérifiez que les champs soient remplis
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Crée l'e-mail et envoie le message
$to = 'christophe@mydatalabs.com'; // Ajoutez votre adresse email entre les '' remplacez yourname@yourdomain.com - C'est l'endroit où le formulaire enverra un message.
$email_subject = "Formulaire de Contact Web :  $name";
$email_body = "Vous avez reçu un nouveau message de votre formulaire de contact web.\n\n"."Voici les détails:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@christopheducamp.com\n"; // Ceci est l'adresse email à laquelle le message sera genere. Nous recommandons d'utiliser quelque chose comme noreply@votredomaine.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>


text:
import Ember from 'ember';

const { Component } = Ember;

export default Component.extend({
  tagName: 'span',
  classNames: ['md-title']
});


text:
'use strict';

angular.module('lscsClientApp')
  .controller('ManagerCtrl', function ($scope, appAuthorize, $location, setting, $http, $modal, $log) {
  	var url = setting.apiurl + "/authorize_token/";
  	var url_checklist = setting.apiurl + "/checklist/";
  	var url_employee = setting.apiurl + "/employees/";
  	$scope.CompletedList = [];
	$scope.OngoingList = [];
  	if(appAuthorize.isLoggedIn() == true){
  		$http.get(url)
  		.success(function(data){
  			if(data.role == 2){
  				$location.path("/surveyor");
  			} else if(data.role == 0){
  				$location.path("/admin");
  			}

  		})
  		.error(function(data){
  			console.log('Error' + data);
  		});
  	}

    $scope.openNewChecklist = function() {
        $location.path("/checklistCreation");
    };

  	$http.get(url_employee)
  	.success(function(empdata){
  		var employeeCount = 0;
  		$scope.EmployeeList = [];
  		angular.forEach(empdata, function(item){
  			if(item.role == 2){
  				$scope.EmployeeList.push(item);
  				employeeCount++;
  			}
  		});
  		$http.get(url_checklist)
	  	.success(function(data){
	  		var completedCount = 0,
	  		ongoingCount = 0;
	  		angular.forEach(data, function(item){
	  			if(item.status == 'C') {
	  				$scope.CompletedList.push(item);
	  				completedCount++;
	  			} else {
	  				$scope.OngoingList.push(item);
	  				ongoingCount++;
	  			}
	  		});
	  		$scope.headerTabs = [
            {
                'headerTabId': 1,
                'header': 'Ongoing Surveys',
                'icon': 'glyphicon-time',
                'count': ongoingCount,
            },
            {
                'headerTabId': 2,
                'header': 'Completed Surveys',
                'icon': 'glyphicon-ok',
                'count': completedCount,
            },
            {
                'headerTabId': 3,
                'header': 'Surveyors',
                'icon': 'glyphicon-user',
                'count': employeeCount,
            }
        ];
	    $scope.selected = 0;
	    $scope.template = 'page' + 0;

	    $scope.select= function(index) {
	       $scope.selected = index;
	       $scope.template = 'page' + index;
	    };
	  	})
	  	.error(function(data){
	  		console.log('Error ' + data);
	  	});
  	})
  	.error(function(empdata){
  		console.log('Error ' + empdata);
  	});

	$scope.items = ['item1', 'item2', 'item3'];

	$scope.delete_survey = function (id) {
		var url_survey_delete = setting.apiurl + '/checklist/' + id +'/delete';
		$http.delete(url_survey_delete)
		.success(function(data){
			angular.forEach($scope.CompletedList, function(item, index){
	  			if(item.id == id){
	  				$scope.CompletedList.splice(index, 1);
	  			}
	  		});

			console.log(id + ' has been deleted.');
		})
		.error(function(data){
			console.log('Error: ' + data);
		});
	}

	$scope.open_survey = function (checklist) {
		var modalInstance = $modal.open({
		  	templateUrl: 'views/manager-survey-view.html',
        controller: ['$scope', '$modalInstance', 'checklist',
            function($scope, $modalInstance, checklist) {

          $scope.checklist = checklist;
          $scope.json_contents = JSON.parse($scope.checklist['json_contents']);

          $scope.close = function () {
            $modalInstance.dismiss('close');
          };
        }],

		  	size: 'lg',
		  	resolve: {
  		    checklist: function () {
  		      return checklist;
  		    }
		    }
		});

		modalInstance.result.then(function (selectedItem) {
		  $scope.selected = selectedItem;
		}, function () {
		  $log.info('Modal dismissed at: ' + new Date());
		});
	};

	$scope.open_location = function (checklist) {
		var modalInstance = $modal.open({
		  	templateUrl: 'views/manager-location-modal.html',
		  	controller: ManagerLocationModalInstanceCtrl,
		  	size: 'lg',
		  	resolve: {
		    items: function () {
		      return checklist;
		    }
		  }
		});

		modalInstance.result.then(function (selectedItem) {
		  $scope.selected = selectedItem;
		}, function () {
		  $log.info('Modal dismissed at: ' + new Date());
		});
	}

	$scope.open = function () {

	var modalInstance = $modal.open({
	  templateUrl: 'views/manager-modal.html',
	  controller: ManagerModalInstanceCtrl,
	  resolve: {
	    items: function () {
	      return $scope.items;
	    }
	  }
	});

	modalInstance.result.then(function (selectedItem) {
	  $scope.selected = selectedItem;
	}, function () {
	  $log.info('Modal dismissed at: ' + new Date());
	});
	};
  })
  .directive("ngWeather", function(){
	return {
		scope: {
			locationMap: '='
		},
		link: function(scope, element, attributes, $http){
		$.simpleWeather({
	    location: scope.locationMap,
	    woeid: '',
	    unit: 'f',
	    success: function(weather) {
	      var html = '
 '+weather.temp+'°'+weather.units.temp+'
';
	      html += '

'+weather.city+', '+weather.region+'
';
	      html += '
'+weather.currently+'
';
	      html += '
'+weather.wind.direction+' '+weather.wind.speed+' '+weather.units.speed+'

';

	      angular.element("#weather").html(html);
	      console.log(weather);
	    },
	    error: function(error) {
	      console.log(error);
	    }
	  });
	},
	template: "

"
	}
});


text:
var fs = require('fs');
var _ = require('lodash');
var yaml = require('js-yaml');
var gitLoader = require('./block-loader/nodegit');

exports.loadLocal = function() {
  var ret = {};
  Array.prototype.slice.call(arguments).forEach(function (path) {
    if (fs.existsSync(path) && fs.statSync(path).isDirectory()) {
      ret = _.extend(ret, readBlockDir(path));
    }
  });
  return ret;
};

exports.loadRemote = function(root,blockDefs) {
  var ret = {};
  if (blockDefs) {
    console.log("* " + "Loading external blocks".cyan);
    blockDefs.forEach(function (def) {
      // plain URL is also ok
      def = typeof def === "object" ? def : { url : def };
      if (def.type == "git" || (def.url && def.url.match(/.*\.git$/))) {
        _.extend(ret, gitLoader.load(root, def, readBlockDir));
      }
    });
  }
  return ret;
};

// =========================================================================================

function readBlockDir(path) {
  var blocks = {};

  var files = fs.readdirSync(path);
  files.forEach(function (entry) {
    var stat = fs.statSync(path + "/" + entry);
    var name = extractBasename(entry);
    if (stat.isFile()) {
      // "Simple Blocks"
      // * Plain template fragment
      // * No sub-snippet
      // * No files
      blocks[name] = {
        text: {
          default: fs.readFileSync(path + "/" + entry, "utf8")
        }
      };
    } else if (stat.isDirectory()) {
      // "Extended Blocks":
      // * A "block.<ext>" which is the default textual block used as fragment if no subtype is given.
      //   There can be only one.
      // * Any other files are sub snippets which can be referenced by their basename (ext doesn't matter)
      // * A directory "files/" hold all files which should copied over into the build directory
      //   (with template substitution)
      // * Any other directory is ignored
      var subEntries = fs.readdirSync(path + "/" + entry);
      var block = {
        text:  {},
        files: []
      };
      subEntries.forEach(function (subEntry) {
        var subPath = path + "/" + entry + "/" + subEntry;
        var subStat = fs.statSync(subPath);
        if (subStat.isFile()) {
          var text = fs.readFileSync(subPath, "utf8");
          if (subEntry.match(/^block\./)) {
            if (block.text.default) {
              throw Error("Only one default block entry starting with 'block.' is allowed in " + path + "/" + entry);
            }
            block.text.default = text
          } else {
            block.text[extractBasename(subEntry)] = text;
          }
        } else if (subStat.isDirectory() && subEntry == "fp-files") {
          fs.readdirSync(subPath).forEach(function (f) {
            block.files.push(subPath + "/" + f);
          });
        }
      });
      blocks[name] = block;
    }
  });
  return blocks;
}

// Check files
function extractBasename(file) {
  return file.replace(/\..*?$/, "");
}


text:
package com.tyrfing.games.tyrlib3.pc.model.config;

import com.tyrfing.games.tyrlib3.model.math.Vector2F;

public class Config {

	public enum ScreenState {
		FULLSCREEN,
		WINDOWED
	}

	public ScreenState screenState;
	public Vector2F screenSize;
}


text:
// +groupName=experimental.cert-manager.io
// +groupGoName=Experimental

// Package experimental contains the group containing experimental APIs.
package experimental

const GroupName = "experimental.cert-manager.io"


text:
const _ = require('underscore');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

let CompPostModel = {};

const convertId = mongoose.Types.ObjectId;
const setName = (name) => _.escape(name).trim();
const setDescription = (descrip) => _.escape(descrip).trim();
const setLocation = (loc) => _.escape(loc).trim();
const setEmail = (email) => _.escape(email).trim();
const setPhoneNumber = (phone) => _.escape(phone).trim();

const CompPostSchema = new mongoose.Schema({

	// Title/info about the event
  title: {
    type: String,
    required: true,
    trim: true,
    set: setName,
  },
	// Info about the event
  description: {
    type: String,
    required: true,
    trim: true,
    set: setDescription,
  },
	// Timestamp - when the event starts
  eventStart: {
    type: Date,
    required: true,
    default: Date.now,
  },
	// Timestamp - when the event ends
  eventEnd: {
    type: Date,
    required: true,
    default: Date.now,
  },
	// Event location
  location: {
    type: String,
    required: true,
    trim: true,
    set: setLocation,
  },
	// Contact email
  contactEmail: {
    type: String,
    required: true,
    default: undefined,
    set: setEmail,
  },
	// Contact phone number
  contactPhone: {
    type: String,
    required: true,
    default: undefined,
    set: setPhoneNumber,
  },
	// Tags for the event
  tags: {
    type: Array,
    required: false,
  },
	// Assoc. user account
  owner: {
    type: mongoose.Schema.ObjectId,
    required: true,
    ref: 'Account',
  },
	// Metadata
  createdData: {
    type: Date,
    default: Date.now,
  },
});

CompPostSchema.statics.ToAPI = (doc) => ({
  name: doc.name,
  age: doc.age,
});

CompPostSchema.statics.findByOwner = (ownerId, callback) => {
  const search = {
    owner: convertId(ownerId),
  };

  return CompPostModel.find(search).exec(callback);
};

// NOT FULLY IMPLEMENTED
CompPostSchema.statics.findByTag = (tag, callback) => {
  const search = {
    tag: [], //TODO: make this actually find the right tag
  };

  return CompPostModel.find(search).exec(callback);
};

CompPostModel = mongoose.model('CompPost', CompPostSchema);

module.exports.CompPostModel = CompPostModel;
module.exports.CompPostSchema = CompPostSchema;


text:
Sublime_DuplicateLineExtend
===========================


text:
* Create a new separate repository which will be used to version control database changes.
* Initialize empty sqitch project in that repository by using following command
```bash
# here we have assumed the db to be used is postgres. Please change engine parameter according to your requirement
# change project name to your required string
sqitch init PROJECTNAME --uri https://github.com/team-avesta/sqitch-startup/ --engine pg**
```
* What above commands does is that it clones a existing git repo created by us which contains basic folder structure that is required for sqitch projects and creates a `sqitch.plan` & `sqitch.conf` file which are required.
* After init sqitch project set username and email which will be used by sqitch to show who changed what in database
```bash
sqitch config --user user.name 'Marge N. O'Vera'
sqitch config --user user.email 'marge@example.com'
```

## Example use (Create new table)

* create users table query through pgadmin.
* After created table, run below command
```bash
sqitch add users -n 'Creates table to track our users'
```
* Execution of above command will create three files in deploy, revert and verify folder with users.sql name
* Copy create table query copy from pgadmin and paste into deploy/users.sql file.
* Copy drop table query and paste into revert/user.sql file. This file is used by sqitch when you perform rollbacks
* This query is for confirming if the required change was executed or not hence query in this file should be such that if it executes successfully then you can be sure that your change has been persisted to db. In this case we use a select query to check if users table is created. Put this query in verify/users.sql file.
* To run verify query, run below command
```bash
sqitch verify
```
* Once changes are verified we need to commit the changes in our repo using below commands
```bash
git add .
git commit -am 'Add users table.'
```

## Updating production database
---

* When Database changes are to upload into production database, add tag into sqitch and git. For this use following command:
```bash
#add new sqitch tag
sqitch tag v1.0.0-dev1 -n 'Tag v1.0.0-dev1.'**
#commit changes made by sqitch tag
git commit -am 'Tag the database with v1.0.0-dev1'
#add git tag (must when releasing )
git tag v1.0.0-dev1 -am 'Tag v1.0.0-dev1
```
* Before release changes into production, tag is required. Otherwise we can not modify files.

## Changing existing function (which is already in production)
---

* After upload changes into production database, if change is required in any table/function then we need to run below command :
```bash
sqitch rework insert_user -n 'Change insert_user function'
```
* Now make the required changes in deploy/insert_user.sql, revert/insert_user.sql and verify/insert_user.sql

## How to download/use sqitch
- Sqitch is a command line utility which needs to be be present in your system's `PATH` to be used directly from command line.
- Instead of downloading the binary we will be using a docker container which provides us with sqitch binary. Run the command below to download the relevant docker image
```bash
docker run -it --network="host"  -v PATH_TO_YOUR_PROJECT_DATABASE_REPO  docteurklein/sqitch:pgsql
```
- In above command it is important to pass in the correct `volume (-v)` flag to docker run command as that is where all the sqitch actions will be executed.
- We can alias the above command as shown below so that it is easy to use during development
```bash
alias sqitchRnd='sudo docker run -it --network="host"  -v /home/upc1/MyProj/RND/sqitchRnd:/src  docteurklein/sqitch:pgsql'
# Now you can simply type sqitchRnd to access sqitch from terminal !
```
---

## Important
* **NEVER** run `sqitch deploy` locally. It is meant to be used only when deploying production database
* You should not use **sqitch rework** for making changes to existing tables in postgres. It should be used only for altering functions


text:
using System;
using BluffinMuffin.HandEvaluator.Enums;
using BluffinMuffin.HandEvaluator.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using static System.String;

namespace BluffinMuffin.HandEvaluator.Test
{
    [TestClass]
    public class PlayingCardTest
    {
        private void ValidateGoodValue(NominalValueEnum value, SuitEnum suit)
        {
            string card = PlayingCard.VALUES[(int) value] + PlayingCard.SUITS[(int) suit];

            var playingCard1 = new PlayingCard(card);
            Assert.AreEqual(card, playingCard1.ToString());
            Assert.AreEqual(value, playingCard1.Value);
            Assert.AreEqual(suit, playingCard1.Suit);

            var playingCard2 = new PlayingCard(value, suit);
            Assert.AreEqual(card, playingCard2.ToString());
            Assert.AreEqual(value, playingCard2.Value);
            Assert.AreEqual(suit, playingCard2.Suit);
        }

        [TestMethod]
        public void ValidateAllGoodValues()
        {
            foreach (NominalValueEnum v in Enum.GetValues(typeof (NominalValueEnum)))
                foreach (SuitEnum s in Enum.GetValues(typeof (SuitEnum)))
                    ValidateGoodValue(v, s);
        }

        [TestMethod]
        public void ValidateBadLengthOf0()
        {
            try
            {
                var c = new PlayingCard(Empty);
                Assert.Fail(c.ToString()); // If it gets to this line, no exception was thrown
            }
            catch (InvalidStringRepresentationException)
            {
            }
        }

        [TestMethod]
        public void ValidateBadLengthOf1()
        {
            try
            {
                var c = new PlayingCard("X");
                Assert.Fail(c.ToString()); // If it gets to this line, no exception was thrown
            }
            catch (InvalidStringRepresentationException)
            {
            }
        }

        [TestMethod]
        public void ValidateBadLengthOf4()
        {
            try
            {
                var c = new PlayingCard("XXXX");
                Assert.Fail(c.ToString()); // If it gets to this line, no exception was thrown
            }
            catch (InvalidStringRepresentationException)
            {
            }
        }

        [TestMethod]
        public void ValidateBadValueInString()
        {
            try
            {
                var c = new PlayingCard("3X");
                Assert.Fail(c.ToString()); // If it gets to this line, no exception was thrown
            }
            catch (InvalidStringRepresentationException)
            {
            }
        }
    }
}


text:
function[out] = interior_wrap(self,inp)
% interior_wrap -- Wraps real-valued angles to 2*pi-length interval for weld
%
% out = interior_wrap(self, inp)
%
%     Expresses inp as the values in the interval self.interior_interval by
%     adding an appropriate multiple of 2*pi.

out = self.interior_interval(1) + mod(inp - self.interior_interval(1), 2*pi);


text:
cd $LV2_SRC_DIR
for i in gettext intltool gettext-devel libglib2.0-dev libsndfile1-dev libglibmm-2.4-dev libfftw3-dev libeigen3-dev; do
  sudo apt-get install -y $i
done
git clone http://git.code.sf.net/p/guitarix/git guitarix-git
cd guitarix-git/trunk
./waf configure --no-lv2-gui --lv2-only --disable-sse --lv2dir=$LV2_DIR --no-avahi --no-bluez --no-ladspa --no-faust
./waf build
sudo ./waf install
./waf clean
cd ../..