text:
package com.ckkloverdos.props

import com.ckkloverdos.convert.Converters
import com.ckkloverdos.maybe.{NoVal, Maybe}
import com.ckkloverdos.resource.{StreamResourceContext, StreamResource, ThreadResourceContext}
import java.io.InputStream
import java.util.Properties

/**
 * Properties with conversion methods.
 *
 * @author Christos KK Loverdos <loverdos@gmail.com>.
 */
class AnyProps(val map: Map[String, Any])(implicit conv: Converters = Converters.DefaultConverters) extends PropsBase[String, Any, AnyProps]{
  def newProps(map: AnyProps#MapType) = new AnyProps(map)

  val converters = conv

  def getBoolean(key: String, falseStrings: Set[String] = AnyProps.DefaultFalseStrings): Maybe[Boolean] = map.get(key) match {
    case Some(value) ⇒ conv.convertToBoolean(value)
    case None ⇒ NoVal
  }

  def getByte(key: String): Maybe[Byte] = map.get(key) match {
    case Some(value) ⇒ conv.convertToByte(value)
    case None ⇒ NoVal
  }

  def getShort(key: String): Maybe[Short] = map.get(key) match {
    case Some(value) ⇒ conv.convertToShort(value)
    case None ⇒ NoVal
  }

  def getInt(key: String): Maybe[Int] = map.get(key) match {
    case Some(value) ⇒ conv.convertToInt(value)
    case None ⇒ NoVal
  }

  def getLong(key: String): Maybe[Long] = map.get(key) match {
    case Some(value) ⇒ conv.convertToLong(value)
    case None ⇒ NoVal
  }

  def getDouble(key: String): Maybe[Double] = map.get(key) match {
    case Some(value) ⇒ conv.convertToDouble(value)
    case None ⇒ NoVal
  }

  def getFloat(key: String): Maybe[Float] = map.get(key) match {
    case Some(value) ⇒ conv.convertToFloat(value)
    case None ⇒ NoVal
  }

  def getProps(key: String): Maybe[AnyProps] = map.get(key) match {
    case Some(value) ⇒ conv.convert[AnyProps](value)
    case None ⇒ NoVal
  }

  def getList(key: String, separatorRegex: String = "\\s*,\\s*") = map.get(key) match {
    case Some(value) ⇒ value match {
      case value: String ⇒
        value.split(separatorRegex).toList
      case _ ⇒
        Nil
    }
    case None ⇒ Nil
  }

  def getTrimmedList(key: String, separatorRegex: String = "\\s*,\\s*"): List[String] =
    getList(key, separatorRegex).map(_.trim).filter(_.length > 0)

  override def equals(any: Any) = any match {
    case props: AnyProps ⇒ props.getClass == this.getClass && props.map == this.map
    case _ ⇒ false
  }

  def equalsAnyProps(other: AnyProps): Boolean = other match {
    case null ⇒ false
    case _    ⇒ equalsMap(other.map)
  }

  def equalsMap(other: Map[String, Any]): Boolean = other match {
    case null ⇒ false
    case _ ⇒ other == this.map
  }

  override def hashCode() = map.##

  override def toString = "AnyProps(%s)".format(map.mkString(", "))
}

object AnyProps {
  lazy val DefaultFalseStrings = Set("false", "off", "0")

  lazy val empty = new Props(Map())

  def apply(rc: StreamResource)(implicit conv: Converters): Maybe[AnyProps] = {
    rc.mapStream { in ⇒
      val props = new java.util.Properties
      props.load(in)
      import collection.JavaConversions._
      props.toMap
    } map (new AnyProps(_))
  }

  def apply(in: InputStream)(implicit conv: Converters): Maybe[AnyProps] = {
    Maybe {
      val props = new java.util.Properties
      props.load(in)
      import collection.JavaConversions._
      new AnyProps(props.toMap)
    }
  }

  def apply(props: Properties)(implicit conv: Converters): Maybe[AnyProps] = {
    import collection.JavaConversions._
    Maybe(new AnyProps(props.toMap))
  }

  def apply(path: String, rc: StreamResourceContext = ThreadResourceContext)(implicit conv: Converters): Maybe[AnyProps] = {
    rc.getResource(path).flatMap(this(_))
  }

  def apply(keyvals: (String, Any)*)(implicit conv: Converters): AnyProps = new AnyProps(Map(keyvals: _*))
}


text:
    <button type="button" class="close" data-dismiss="modal">×Fechar
    </button>

Adicionar grupo de produtos

    <form class="form-horizontal" role="form" method="post" action="<?php echo $action;?>">

            Produto

                <input name="idgroup" type="text" class="form-control" id="inputNomeProduto" placeholder="Código" <?php insert_input_value($this,"id");?>>

                <input name="name" type="text" class="form-control" id="inputNomeProduto" placeholder="Nome do grupo" <?php insert_input_value($this,"name");?>>

            Descrição

                <textarea class="form-control" rows="3"></textarea>

    </form>

    <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
    <button type="button" class="btn btn-primary btn-send-form">Salvar</button>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace Microsoft.LiveMeeting.RecordingExporter
{
    public partial class SettingsForm : Form
    {
        public SettingsForm()
        {
            InitializeComponent();

            textBoxConfCenter.Text = Config.ConfCenterName;
            textBoxUsername.Text = Config.Username;
            textBoxPassword.Text = Config.Password;

            textRecViewerName.Text = Config.RecViewerName;
            textRecViewerCompany.Text = Config.RecViewerCompany;
            textRecViewerEmail.Text = Config.RecViewerEmail;

            if (!string.IsNullOrWhiteSpace(Config.PostingURL))
            {
                valueURL.Text = Config.PostingURL;
            }
            else
            {
                valueURL.Text = "Enter a conference center name, and check that it is valid to continue";
            }
            ValidateInput();
        }

        public string Username { get { return textBoxUsername.Text; } }

        public string ConfCenter { get { return textBoxConfCenter.Text; } }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            Config.Username = textBoxUsername.Text;
            Config.Password = textBoxPassword.Text;
            Config.RecViewerName = textRecViewerName.Text;
            Config.RecViewerCompany = textRecViewerCompany.Text;
            Config.RecViewerEmail = textRecViewerEmail.Text;

            Properties.Settings.Default.Username = Config.Username;
            Properties.Settings.Default.ConfCenter = Config.ConfCenterName;
            Properties.Settings.Default.PostingURL = Config.PostingURL;
            Properties.Settings.Default.RecViewerName = Config.RecViewerName;
            Properties.Settings.Default.RecViewerCompany = Config.RecViewerCompany;
            Properties.Settings.Default.RecViewerEmail = Config.RecViewerEmail;
            Properties.Settings.Default.Save();
            DialogResult = DialogResult.OK;
        }

        private void buttonCheckURL_Click(object sender, EventArgs e)
        {
            Config.ConfCenterName = textBoxConfCenter.Text;
            Config.UpdatePostingURL();
            if (Config.IsValidPostingUrl)
            {
                valueURL.Text = Config.PostingURL;
                buttonCheckURL.Enabled = false;
            }
            else
            {
                valueURL.Text = "Not a valid conference center name";
                buttonSave.Enabled = false;
            }
            ValidateInput();
        }

        private void textBoxConfCenter_TextChanged(object sender, EventArgs e)
        {
            buttonSave.Enabled = false;
            buttonCheckURL.Enabled = true;
        }

        private void textBoxUsername_TextChanged(object sender, EventArgs e)
        {
            ValidateInput();
        }

        private void textBoxPassword_TextChanged(object sender, EventArgs e)
        {
            ValidateInput();
        }

        private void ValidateInput()
        {
            bool isValid =
                Config.IsValidPostingUrl &&
                !string.IsNullOrWhiteSpace(textBoxUsername.Text) &&
                !string.IsNullOrWhiteSpace(textBoxPassword.Text);

            buttonSave.Enabled = isValid;
        }

        private void linkPrivacy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo("https://go.microsoft.com/fwlink/?LinkId=521839");
            Process.Start(sInfo);
        }
    }
}


text:
<?php

final class PhabricatorEditEngineSubtypeMap
  extends Phobject {

  private $subtypes;

  public function __construct(array $subtypes) {
    assert_instances_of($subtypes, 'PhabricatorEditEngineSubtype');

    $this->subtypes = $subtypes;
  }

  public function getDisplayMap() {
    return mpull($this->subtypes, 'getName');
  }

  public function getCount() {
    return count($this->subtypes);
  }

  public function isValidSubtype($subtype_key) {
    return isset($this->subtypes[$subtype_key]);
  }

  public function getSubtypes() {
    return $this->subtypes;
  }

  public function getSubtype($subtype_key) {
    if (!$this->isValidSubtype($subtype_key)) {
      throw new Exception(
        pht(
          'Subtype key "%s" does not identify a valid subtype.',
          $subtype_key));
    }

    return $this->subtypes[$subtype_key];
  }

  public function getCreateFormsForSubtype(
    PhabricatorEditEngine $edit_engine,
    PhabricatorEditEngineSubtypeInterface $object) {

    $subtype_key = $object->getEditEngineSubtype();
    $subtype = $this->getSubtype($subtype_key);

    $select_identifiers = $subtype->getChildFormIdentifiers();
    $select_subtypes = $subtype->getChildSubtypes();

    $query = $edit_engine->newConfigurationQuery()
      ->withIsDisabled(false);

    if ($select_identifiers) {
      $query->withIdentifiers($select_identifiers);
    } else {
      // If we're selecting by subtype rather than selecting specific forms,
      // only select create forms.
      $query->withIsDefault(true);

      if ($select_subtypes) {
        $query->withSubtypes($select_subtypes);
      } else {
        $query->withSubtypes(array($subtype_key));
      }
    }

    $forms = $query->execute();
    $forms = mpull($forms, null, 'getIdentifier');

    // If we're selecting by ID, respect the order specified in the
    // constraint. Otherwise, use the create form sort order.
    if ($select_identifiers) {
      $forms = array_select_keys($forms, $select_identifiers) + $forms;
    } else {
      $forms = msort($forms, 'getCreateSortKey');
    }

    return $forms;
  }

}


text:
class AddDefaultLockedToForumsTopic < ActiveRecord::Migration[5.0]
  def change
    add_column :forums_topics, :default_locked, :boolean, default: false
  end
end


text:
//
//  GJGCChatFriendImageMessageCell.m
//  ZYChat
//
//  Created by KivenLin on 14-11-5.
//  Copyright (c) 2014年 ConnectSoft. All rights reserved.
//

#import "GJGCChatFriendImageMessageCell.h"
#import "UIImage+Color.h"
#import "UIImage+YYAdd.h"

@interface GJGCChatFriendImageMessageCell ()

@property(nonatomic, strong) CALayer *contentLayer;
@property(nonatomic, strong) CAShapeLayer *maskLayer;
@property(nonatomic, strong) UIImageView *imageDefaultView;
@property(nonatomic, strong) UIImage *saveImage;
@property(nonatomic, strong) UIImageView *uploadImageView;

@end

@implementation GJGCChatFriendImageMessageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.contentImageView = [[UIImageView alloc] init];
        self.contentImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.contentImageView.gjcf_size = (CGSize) {160, 160};
        self.contentImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnContentImageView)];
        tapR.numberOfTapsRequired = 1;
        [self.bubbleBackImageView addGestureRecognizer:tapR];
        [self.bubbleBackImageView addSubview:self.contentImageView];

        self.blankImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"IM聊天页-占位图"]];
        [self.contentImageView addSubview:self.blankImageView];
        self.blankImageView.gjcf_centerX = self.contentImageView.gjcf_width / 2;
        self.blankImageView.gjcf_centerY = self.contentImageView.gjcf_height / 2;

        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        self.maskLayer = maskLayer;
        maskLayer.fillColor = [UIColor clearColor].CGColor;
        maskLayer.strokeColor = [UIColor clearColor].CGColor;
        maskLayer.contentsCenter = CGRectMake(0.5, 0.8, 0.1, 0.1);
        maskLayer.contentsScale = [UIScreen mainScreen].scale;

        CALayer *contentLayer = [CALayer layer];
        self.contentLayer = contentLayer;
        contentLayer.mask = maskLayer;
        [self.contentImageView.layer addSublayer:contentLayer];

        self.cirProgressView = [[UAProgressView alloc] initWithFrame:CGRectMake(0, 0, 40.0f, 40.0f)];
        self.cirProgressView.tintColor = [UIColor whiteColor];
        [self.contentImageView addSubview:self.cirProgressView];
        self.cirProgressView.hidden = YES;

        self.imageDefaultView = [[UIImageView alloc] init];
        [self.contentImageView addSubview:self.imageDefaultView];
        self.imageDefaultView.image = [UIImage imageNamed:@"message_picture_default"];
        self.imageDefaultView.size = AUTO_SIZE(63, 51);
        self.uploadImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"upload_icon"]];
        [self.contentImageView addSubview:self.uploadImageView];

        self.uploadImageView.size = self.cirProgressView.size;
        self.cirProgressView.centralView = self.uploadImageView;

    }
    return self;
}

- (void)tapOnContentImageView {
    if (self.delegate && [self.delegate respondsToSelector:@selector(imageMessageCellDidTap:)]) {
        [self.delegate imageMessageCellDidTap:self];
    }
}

- (void)resetState {

}

- (void)resetStateWithPrepareSize:(CGSize)pSize {
    self.contentImageView.gjcf_size = pSize;

    UIImage *buImage = nil;
    if (self.isFromSelf) {
        buImage = [UIImage imageNamed:@"sender_message_blue"];
    } else {
        buImage = [UIImage imageNamed:@"reciver_message_white"];
    }
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.maskLayer.contents = (id) buImage.CGImage;
    self.contentImageView.gjcf_size = pSize;
    self.maskLayer.frame = self.contentImageView.bounds;
    self.contentLayer.frame = self.contentImageView.bounds;
    self.contentLayer.contents = (id) [UIImage imageWithColor:[UIColor clearColor] withSize:self.contentSize].CGImage;
    [CATransaction commit];

    [self resetMaxBlankImageViewSize];
    self.blankImageView.gjcf_centerX = self.contentImageView.gjcf_width / 2;
    self.blankImageView.gjcf_centerY = self.contentImageView.gjcf_height / 2;
    self.blankImageView.hidden = NO;
    self.cirProgressView.progress = 0.2f;
    self.cirProgressView.hidden = YES;
}

- (void)resetMaxBlankImageViewSize {
    CGFloat blankToBord = 8.f;

    CGFloat minSide = MIN(self.contentImageView.gjcf_width, self.contentImageView.gjcf_height);

    CGFloat blankWidth = minSide - 2 * blankToBord;

    self.blankImageView.gjcf_size = CGSizeMake(blankWidth, blankWidth);
}

- (void)removePrepareState {
    self.blankImageView.hidden = YES;
    self.cirProgressView.hidden = YES;
}

- (void)setContentModel:(GJGCChatContentBaseModel *)contentModel {
    if (!contentModel) {
        return;
    }

    [super setContentModel:contentModel];

    GJGCChatFriendContentModel *chatContentModel = (GJGCChatFriendContentModel *) contentModel;

    self.isFromSelf = chatContentModel.isFromSelf;

    UIImage *buImage = nil;
    if (self.isFromSelf) {
        buImage = [UIImage imageNamed:@"sender_message_blue"];
    } else {
        buImage = [UIImage imageNamed:@"reciver_message_white"];
    }

    CGSize imageSize = CGSizeMake(chatContentModel.originImageWidth, chatContentModel.originImageHeight);
    UIImage *cacheImage = chatContentModel.messageContentImage;

    if (CGSizeEqualToSize(imageSize, CGSizeZero)) {
        imageSize = cacheImage.size;
        chatContentModel.originImageWidth = imageSize.width;
        chatContentModel.originImageHeight = imageSize.height;
    }
    CGFloat maxWidth = AUTO_WIDTH(340);
    CGFloat maxHeight = AUTO_WIDTH(340);
    self.contentSize = CGSizeMake(maxWidth, maxHeight);

    if (!CGSizeEqualToSize(imageSize, CGSizeZero)) {
        CGSize thumbSize = [GJGCImageResizeHelper getCutImageSize:imageSize maxSize:CGSizeMake(imageSize.width * 0.2, imageSize.height * 0.2)];
        if (thumbSize.width > thumbSize.height) {
            thumbSize.width = maxWidth;
            thumbSize.height = (thumbSize.width / chatContentModel.originImageWidth) * chatContentModel.originImageHeight;
        } else {
            thumbSize.height = maxHeight;
            thumbSize.width = (thumbSize.height / chatContentModel.originImageHeight) * chatContentModel.originImageWidth;
        }
        if (thumbSize.height < buImage.size.height) {
            thumbSize.height = buImage.size.height + 2;
        }
        if (thumbSize.width < buImage.size.width) {
            thumbSize.width = buImage.size.width + 2;
        }
        self.contentSize = thumbSize;
    }
    if (!cacheImage) {
        [self resetStateWithPrepareSize:self.contentSize];
        cacheImage = [UIImage imageWithColor:GJCFQuickHexColor(@"EAEBEE") withSize:self.contentSize];
        self.imageDefaultView.hidden = NO;
    } else {
        self.imageDefaultView.hidden = YES;
    }

    if (chatContentModel.isSnapChatMode) {
        cacheImage = [cacheImage imageByBlurRadius:30 tintColor:nil tintMode:0 saturation:1 maskImage:nil];
    } else {
        if (GJCFFileIsExist(chatContentModel.imageOriginDataCachePath)) {
            cacheImage = GJCFQuickImageByFilePath(chatContentModel.imageOriginDataCachePath);
            self.imageDefaultView.hidden = YES;
            self.cirProgressView.hidden = YES;
        } else {
            if (!cacheImage) {
                cacheImage = GJCFQuickImageByFilePath(chatContentModel.thumbImageCachePath);
            }
            if (!cacheImage) {
                cacheImage = [UIImage imageWithColor:GJCFQuickHexColor(@"EAEBEE") withSize:self.contentSize];
                self.imageDefaultView.hidden = NO;
                self.cirProgressView.hidden = NO;
            }
        }
    }

    self.bubbleBackImageView.gjcf_size = self.contentSize;
    [self adjustContent];

    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.maskLayer.contents = (id) self.bubbleBackImageView.image.CGImage;
    self.contentImageView.gjcf_size = self.contentSize;
    self.maskLayer.frame = self.contentImageView.bounds;
    self.contentLayer.frame = self.contentImageView.bounds;
    self.saveImage = cacheImage;
    self.contentLayer.contents = (id) cacheImage.CGImage;
    [CATransaction commit];

    if (GJCFSystemiPhone6Plus) {
        UIImage *image = self.bubbleBackImageView.image;
        self.bubbleBackImageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [self.bubbleBackImageView setTintColor:[UIColor clearColor]];
    }

    self.contentImageView.gjcf_top = 0;
    if (self.isFromSelf) {
        self.contentImageView.gjcf_left = 0;
    } else {
        self.contentImageView.gjcf_right = self.bubbleBackImageView.gjcf_width;
    }
    self.cirProgressView.center = self.contentImageView.center;
    self.imageDefaultView.center = self.contentImageView.center;

    if (self.isFromSelf) {
        if (chatContentModel.messageContentImage) {
            if (chatContentModel.uploadSuccess) {
                self.cirProgressView.hidden = YES;
                self.uploadImageView.hidden = YES;
            } else {
                //upload progress
                self.cirProgressView.hidden = chatContentModel.uploadProgress >= 1.f;
                self.uploadImageView.hidden = chatContentModel.uploadProgress >= 1.f;
                [self.cirProgressView setProgress:chatContentModel.uploadProgress animated:NO];
            }
        } else {
            //download progress
            [self downloadProgress:chatContentModel.downloadProgress];
        }
    } else {
        if (chatContentModel.messageContentImage) {
            self.cirProgressView.hidden = YES;
        } else {
            //download progress
            [self downloadProgress:chatContentModel.downloadProgress];
        }
    }
}

- (void)downloadProgress:(float)downloadProgress {
    GJGCChatFriendContentModel *chatContentModel = (GJGCChatFriendContentModel *) self.contentModel;
    if (chatContentModel.downloadProgress == downloadProgress) {
        return;
    }
    self.cirProgressView.hidden = downloadProgress >= 1.f;
    chatContentModel.downloadProgress = downloadProgress;
    [GCDQueue executeInMainQueue:^{
        [self.cirProgressView setProgress:downloadProgress animated:YES];
    }];
}

- (void)setUploadProgress:(float)progress {
    if (progress >= 1.f) {
        self.cirProgressView.hidden = YES;
        self.uploadImageView.hidden = YES;
    }
    [GCDQueue executeInMainQueue:^{
        [self.cirProgressView setProgress:progress animated:YES];
    }];
}

- (void)goToShowLongPressMenu:(UILongPressGestureRecognizer *)sender {
    [super goToShowLongPressMenu:sender];

    if (sender.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        UIMenuController *popMenu = [UIMenuController sharedMenuController];
        UIMenuItem *item3 = [[UIMenuItem alloc] initWithTitle:LMLocalizedString(@"Chat Retweet", nil) action:@selector(retweetMessage:)];
        UIMenuItem *item1 = [[UIMenuItem alloc] initWithTitle:LMLocalizedString(@"Set Save Photo", nil) action:@selector(saveImage:)];
        UIMenuItem *item2 = [[UIMenuItem alloc] initWithTitle:LMLocalizedString(@"Link Delete", nil) action:@selector(deleteMessage:)];
        NSArray *menuItems = @[item3, item1, item2];
        [popMenu setMenuItems:menuItems];
        [popMenu setArrowDirection:UIMenuControllerArrowDown];

        [popMenu setTargetRect:self.bubbleBackImageView.frame inView:self];
        [popMenu setMenuVisible:YES animated:YES];

    }

}

- (void)faildState {
    CGSize thumbNoScaleSize = self.contentSize;
    self.contentImageView.gjcf_size = thumbNoScaleSize;
    self.contentImageView.image = [UIImage imageWithColor:[UIColor clearColor] withSize:thumbNoScaleSize];
    self.blankImageView.gjcf_centerX = self.contentImageView.gjcf_width / 2;
    self.blankImageView.gjcf_centerY = self.contentImageView.gjcf_height / 2;
    self.blankImageView.hidden = NO;
    self.cirProgressView.progress = 0.f;
    self.cirProgressView.hidden = YES;
}

- (void)successDownloadWithImageData:(NSData *)imageData {
    if (imageData) {
        self.cirProgressView.hidden = YES;
        self.imageDefaultView.hidden = YES;
        [self removePrepareState];
        UIImage *cacheImage = [UIImage imageWithData:imageData];
        if (self.contentModel.isSnapChatMode) {
            cacheImage = [cacheImage imageByBlurRadius:30 tintColor:nil tintMode:0 saturation:1 maskImage:nil];
        }

        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        self.maskLayer.contents = (id) self.bubbleBackImageView.image.CGImage;
        self.contentImageView.gjcf_size = self.contentSize;
        self.maskLayer.frame = self.contentImageView.bounds;
        self.contentLayer.frame = self.contentImageView.bounds;
        self.saveImage = cacheImage;
        self.contentLayer.contents = (id) cacheImage.CGImage;
        [CATransaction commit];

        self.bubbleBackImageView.gjcf_size = self.contentImageView.gjcf_size;

        [self adjustContent];

        if (GJCFSystemiPhone6Plus) {
            UIImage *image = self.bubbleBackImageView.image;
            self.bubbleBackImageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            [self.bubbleBackImageView setTintColor:[UIColor clearColor]];
        }

        self.contentImageView.gjcf_top = 0;
        if (self.isFromSelf) {
            self.contentImageView.gjcf_left = 0;
        } else {
            self.contentImageView.gjcf_right = self.bubbleBackImageView.gjcf_width;
        }
        self.saveImage = cacheImage;
        self.contentLayer.contents = (id) cacheImage.CGImage;
    }
}

/**
 *  save image
 *
 *  @param sender
 */
- (void)saveImage:(UIMenuItem *)sender {
    UIImageWriteToSavedPhotosAlbum(self.saveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {

}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(saveImage:) ||
            action == @selector(deleteMessage:) ||
            action == @selector(reSendMessage) ||
            action == @selector(retweetMessage:)) {
        return YES;
    }
    return NO;
}

+ (CGFloat)cellHeightForContentModel:(GJGCChatContentBaseModel *)contentModel {

    GJGCChatFriendContentModel *chatContentModel = (GJGCChatFriendContentModel *) contentModel;

    UIImage *buImage = nil;
    if (chatContentModel.isFromSelf) {
        buImage = [UIImage imageNamed:@"sender_message_blue"];
    } else {
        buImage = [UIImage imageNamed:@"reciver_message_white"];
    }

    CGSize imageSize = CGSizeMake(chatContentModel.originImageWidth, chatContentModel.originImageHeight);
    UIImage *cacheImage = chatContentModel.messageContentImage;
    if (!cacheImage) {
        cacheImage = GJCFQuickImageByFilePath(chatContentModel.imageOriginDataCachePath);
        if (!cacheImage) {
            cacheImage = GJCFQuickImageByFilePath(chatContentModel.thumbImageCachePath);
        }
        chatContentModel.messageContentImage = cacheImage;
    }
    if (CGSizeEqualToSize(imageSize, CGSizeZero)) {
        imageSize = cacheImage.size;
        chatContentModel.originImageWidth = imageSize.width;
        chatContentModel.originImageHeight = imageSize.height;
    }
    CGFloat maxWidth = AUTO_WIDTH(340);
    CGFloat maxHeight = AUTO_WIDTH(340);

    CGSize contentSize = CGSizeZero;

    if (!CGSizeEqualToSize(imageSize, CGSizeZero)) {
        CGSize thumbSize = [GJGCImageResizeHelper getCutImageSize:imageSize maxSize:CGSizeMake(imageSize.width * 0.2, imageSize.height * 0.2)];
        if (thumbSize.width > thumbSize.height) {
            thumbSize.width = maxWidth;
            thumbSize.height = (thumbSize.width / chatContentModel.originImageWidth) * chatContentModel.originImageHeight;
        } else {
            thumbSize.height = maxHeight;
            thumbSize.width = (thumbSize.height / chatContentModel.originImageHeight) * chatContentModel.originImageWidth;
        }
        if (thumbSize.height < buImage.size.height) {
            thumbSize.height = buImage.size.height + 2;
        }
        if (thumbSize.width < buImage.size.width) {
            thumbSize.width = buImage.size.width + 2;
        }
        contentSize = thumbSize;
    }

    CGSize nameSize = CGSizeZero;
    if (chatContentModel.isGroupChat && !chatContentModel.isFromSelf) {
        NSAttributedString *name = [[NSAttributedString alloc] initWithString:chatContentModel.senderName];
        nameSize = [GJCFCoreTextContentView contentSuggestSizeWithAttributedString:name forBaseContentSize:CGSizeMake(DEVICE_SIZE.width - AUTO_WIDTH(150), 25)];
        nameSize.height += 3;
    }

    return contentSize.height + BOTTOM_CELL_MARGIN + nameSize.height;
}

#pragma mark -

- (void)willDisplayCell {

}

- (void)didEndDisplayingCell {

}

@end


text:
.clearfix { *zoom: 1; }
.clearfix:before, .clearfix:after { content: " "; display: table; }
.clearfix:after { clear: both; }
h4 { margin: 0; }
.form-table th, .form-wrap label { vertical-align: middle; }
table.rtnginx-table { border-bottom: 1px solid #EEE; }
table.rtnginx-table:last-child { border-bottom: 0; }
.rtnginx-table p.error { color: red; }
pre#map { background: #e5e5e5 none; border-radius: 10px; padding: 10px; }
.wrap h2.rt_option_title { background: url(nginx-icon-32x32.png) 0 6px no-repeat rgba(0, 0, 0, 0); padding-left: 40px; }
#poststuff h2 { padding: 0 0 0 10px; margin-top: 0; }
form#purgeall .button-primary { margin-bottom: 20px; box-shadow: inset 0 -2px rgba(0, 0, 0, 0.14);padding: 15px 30px;font-size: 1rem;border: 0;border-radius: 5px;color: #FFF;background: #DD3D36; height: auto; }
form#purgeall .button-primary:hover, form#purgeall .button-primary:focus { background: #d52c24; }
.nh-aligncenter { display: block; text-align: center; line-height: 2; }
#latest_news .inside ul, #useful-links .inside ul { margin: 0 0 0 12px }
    #latest_news .inside ul li, #useful-links .inside ul li { list-style: square; padding: 0 0 7px; }
#social .inside a { background-color: #666;color: #FFF;display: inline-block;height: 30px;font-size: 1.25rem;line-height: 30px;margin: 10px 20px 0 0;overflow: hidden;padding: 0;text-align: center;text-decoration: none;width: 30px;-webkit-border-radius: 1000px;-moz-border-radius: 1000px;border-radius: 1000px; }
    #social .inside .nginx-helper-rss:hover { background-color: #FAA33D; }
    #social .inside .nginx-helper-facebook:hover { background-color: #537BBD; }
    #social .inside .nginx-helper-twitter:hover { background-color: #40BFF5; }
    #social .inside .nginx-helper-gplus:hover { background-color: #DD4B39; }
.rt-purge_url { width: 100%; }


text:
layout: base
title:  'Dependencies'
generated: 'true'
permalink: pcm/dep/index.html
udver: '2'
---

# Dependencies

The following table lists the syntactic relations used in UD v2 for Naija.

{% include pcm-dep-table.html %}


text:
<?php

// Inclus les dépendances
require_once 'include'.DIRECTORY_SEPARATOR.'head.php';

// §§§ EN AVANT §§§ EDITER LES LIGNES SUIVANTES

define('GROUPE', 'Tour 2 - Poule 5');

	// Versions en lice
	$calculator->addCandidate('A1');
	$calculator->addCandidate('B3');
	$calculator->addCandidate('C1');
	$calculator->addCandidate('F2');
	$calculator->addCandidate('H4');

	// Votants
	$calculator->addVote('C1=F2>H4>B3>A1', 'Draffin');
	$calculator->addVote('H4>F2>C1>A1>B3', 'Warren 60');
	$calculator->addVote('H4>F2>A1>C1>B3', 'Resigned');
	$calculator->addVote('C1>A1>H4>B3>F2', 'Asinius Pollion');
	$calculator->addVote('A1>F2>C1>B3>H4', 'Siegmund');

		// Note, le renseignement du dernier rang de chaque vote est optionnel. Il sera automatiquement déduit si absent, j'ai d'ailleur procédé ainsi ci-dessus.

// Lance l'affichage §§§ On ne touche plus aux suivantes
require_once 'include'.DIRECTORY_SEPARATOR.'affichage.php';

?>


text:
var app = angular.module('cah', [
    'ngRoute',
    'LocalStorageModule'
])

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
}])

.run(['authService', function(authService) {
    authService.fillAuthData();
}]);
;app.controller('homeCtrl', ['$scope', 'test', function($scope, test) {
    console.log('home');

    test.needAuth().then(function(data) {
        console.log(data);
    });

}]);
;app.controller('loginCtrl', ['$scope', '$location', 'authService', function($scope, $location, authService) {

    $scope.user = {
        username: 'jason@walterbrimleykitty.com',
        password: 'Celie123'
    }

    authService.logOut()

    $scope.login = function() {
        authService.login($scope.user).then(function(data) {
            if (data && data.success) {
                $location.path('/');
            }
        });
    };
}]);
;app.config(['$routeProvider', function($routeProvider) {
    var cacheBustPrefix = Date.now();
    $routeProvider
        .when('/', {
            templateUrl: '/scripts/app/home/index.html?cache-bust=' + cacheBustPrefix,
            controller: 'homeCtrl',
            caseInsensitiveMatch: true
        })
        .when('/login', {
            templateUrl: '/scripts/app/login/index.html?cache-bust=' + cacheBustPrefix,
            controller: 'loginCtrl',
            caseInsensitiveMatch: true
        });
}]);
;app.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', function($q, $injector, $location, localStorageService) {

    var authInterceptorServiceFactory = {};

    var _request = function(config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            //config.headers.Authorization = 'Bearer ' + authData.token;
            config.headers["x-access-token"] = authData.token;
        }

        return config;
    };

    var _responseError = function(rejection) {
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            var authData = localStorageService.get('authorizationData');

            if (authData) {
                if (authData.useRefreshTokens) {
                    $location.path('/refresh');
                    return $q.reject(rejection);
                }
            }
            authService.logOut();
            if ($location.path() != '/login') {
                localStorageService.set('referrer', $location.path());
            }
            $location.path('/login');
        }
        return $q.reject(rejection);
    };

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);
;app.factory('authService', ['$rootScope', '$http', '$q', 'localStorageService', function($rootScope, $http, $q, localStorageService) {

    var authServiceFactory = {};

    var _authentication = {
        isAuth: false,
        userName: "",
        useRefreshTokens: false,
        userRoles: []
    };

    var _externalAuthData = {
        provider: "",
        userName: "",
        externalAccessToken: ""
    };

    var _login = function(loginData) {

        var data = "grant_type=password&username=" + loginData.username + "&password=" + loginData.password;

        var deferred = $q.defer();

        $http.post("/api/login", data, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(response) {

            localStorageService.set('authorizationData', {
                token: response.token
            });

            _authentication.isAuth = true;
            _authentication.userName = loginData.userName;
            _authentication.useRefreshTokens = loginData.useRefreshTokens;

            $rootScope.user = response;

            deferred.resolve(response);

        }).error(function(err, status) {
            _logOut();
            deferred.reject(err);
        });

        return deferred.promise;

    };

    var _logOut = function() {

        localStorageService.remove('authorizationData');

        _authentication.isAuth = false;
        _authentication.userName = "";
        _authentication.useRefreshTokens = false;

    };

    var _fillAuthData = function() {

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            _authentication.isAuth = true;
            _authentication.userName = authData.userName;
            _authentication.useRefreshTokens = authData.useRefreshTokens;
            _authentication.userRoles = authData.userRoles;
        }

    };

    var _refreshToken = function() {
        var deferred = $q.defer();

        //     var authData = localStorageService.get('authorizationData');
        //
        //     if (authData) {
        //
        //       if (authData.useRefreshTokens) {
        //
        //         var data = "grant_type=refresh_token&refresh_token=" + authData.refreshToken + "&client_id=" + ngAuthSettings.clientId;
        //
        //         localStorageService.remove('authorizationData');
        //
        //         $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
        //
        //           localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName, refreshToken: response.refresh_token, useRefreshTokens: true });
        //
        //           deferred.resolve(response);
        //
        //         }).error(function (err, status) {
        //           _logOut();
        //           deferred.reject(err);
        //         });
        //       }
        //     }

        return deferred.promise;
    };

    var _obtainAccessToken = function(externalData) {

        var deferred = $q.defer();

        //     $http.get(serviceBase + 'api/account/ObtainLocalAccessToken', { params: { provider: externalData.provider, externalAccessToken: externalData.externalAccessToken } }).success(function (response) {
        //
        //       localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName, refreshToken: "", useRefreshTokens: false });
        //
        //       _authentication.isAuth = true;
        //       _authentication.userName = response.userName;
        //       _authentication.useRefreshTokens = false;
        //
        //       deferred.resolve(response);
        //
        //     }).error(function (err, status) {
        //       _logOut();
        //       deferred.reject(err);
        //     });

        return deferred.promise;

    };

    var _registerExternal = function(registerExternalData) {

        var deferred = $q.defer();

        //     $http.post(serviceBase + 'api/account/registerexternal', registerExternalData).success(function (response) {
        //
        //       localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName, refreshToken: "", useRefreshTokens: false });
        //
        //       _authentication.isAuth = true;
        //       _authentication.userName = response.userName;
        //       _authentication.useRefreshTokens = false;
        //
        //       $rootScope.userRoles = response.userRoles;
        //
        //       deferred.resolve(response);
        //
        //     }).error(function (err, status) {
        //       _logOut();
        //       deferred.reject(err);
        //     });

        return deferred.promise;

    };

    //authServiceFactory.saveRegistration = _saveRegistration;
    authServiceFactory.login = _login;
    authServiceFactory.logOut = _logOut;
    authServiceFactory.fillAuthData = _fillAuthData;
    authServiceFactory.authentication = _authentication;
    authServiceFactory.refreshToken = _refreshToken;

    authServiceFactory.obtainAccessToken = _obtainAccessToken;
    authServiceFactory.externalAuthData = _externalAuthData;
    authServiceFactory.registerExternal = _registerExternal;

    return authServiceFactory;
}]);
;/**
 * An Angular module that gives you access to the browsers local storage
 * @version v0.2.1 - 2015-05-18
 * @link https://github.com/grevory/angular-local-storage
 * @author grevory <greg@gregpike.ca>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
(function(window, angular, undefined) {
    /*jshint globalstrict:true*/
    //'use strict';

    var isDefined = angular.isDefined,
        isUndefined = angular.isUndefined,
        isNumber = angular.isNumber,
        isObject = angular.isObject,
        isArray = angular.isArray,
        extend = angular.extend,
        toJson = angular.toJson;
    var angularLocalStorage = angular.module('LocalStorageModule', []);

    angularLocalStorage.provider('localStorageService', function() {

        // You should set a prefix to avoid overwriting any local storage variables from the rest of your app
        // e.g. localStorageServiceProvider.setPrefix('yourAppName');
        // With provider you can use config as this:
        // myApp.config(function (localStorageServiceProvider) {
        //    localStorageServiceProvider.prefix = 'yourAppName';
        // });
        this.prefix = 'ls';

        // You could change web storage type localstorage or sessionStorage
        this.storageType = 'localStorage';

        // Cookie options (usually in case of fallback)
        // expiry = Number of days before cookies expire // 0 = Does not expire
        // path = The web path the cookie represents
        this.cookie = {
            expiry: 30,
            path: '/'
        };

        // Send signals for each of the following actions?
        this.notify = {
            setItem: true,
            removeItem: false
        };

        // Setter for the prefix
        this.setPrefix = function(prefix) {
            this.prefix = prefix;
            return this;
        };

        // Setter for the storageType
        this.setStorageType = function(storageType) {
            this.storageType = storageType;
            return this;
        };

        // Setter for cookie config
        this.setStorageCookie = function(exp, path) {
            this.cookie.expiry = exp;
            this.cookie.path = path;
            return this;
        };

        // Setter for cookie domain
        this.setStorageCookieDomain = function(domain) {
            this.cookie.domain = domain;
            return this;
        };

        // Setter for notification config
        // itemSet & itemRemove should be booleans
        this.setNotify = function(itemSet, itemRemove) {
            this.notify = {
                setItem: itemSet,
                removeItem: itemRemove
            };
            return this;
        };

        this.$get = ['$rootScope', '$window', '$document', '$parse', function($rootScope, $window, $document, $parse) {
            var self = this;
            var prefix = self.prefix;
            var cookie = self.cookie;
            var notify = self.notify;
            var storageType = self.storageType;
            var webStorage;

            // When Angular's $document is not available
            if (!$document) {
                $document = document;
            } else if ($document[0]) {
                $document = $document[0];
            }

            // If there is a prefix set in the config lets use that with an appended period for readability
            if (prefix.substr(-1) !== '.') {
                prefix = !!prefix ? prefix + '.' : '';
            }
            var deriveQualifiedKey = function(key) {
                return prefix + key;
            };
            // Checks the browser to see if local storage is supported
            var browserSupportsLocalStorage = (function() {
                try {
                    var supported = (storageType in $window && $window[storageType] !== null);

                    // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
                    // is available, but trying to call .setItem throws an exception.
                    //
                    // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
                    // that exceeded the quota."
                    var key = deriveQualifiedKey('__' + Math.round(Math.random() * 1e7));
                    if (supported) {
                        webStorage = $window[storageType];
                        webStorage.setItem(key, '');
                        webStorage.removeItem(key);
                    }

                    return supported;
                } catch (e) {
                    storageType = 'cookie';
                    $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
                    return false;
                }
            }());

            // Directly adds a value to local storage
            // If local storage is not available in the browser use cookies
            // Example use: localStorageService.add('library','angular');
            var addToLocalStorage = function(key, value) {
                // Let's convert undefined values to null to get the value consistent
                if (isUndefined(value)) {
                    value = null;
                } else {
                    value = toJson(value);
                }

                // If this browser does not support local storage use cookies
                if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
                    if (!browserSupportsLocalStorage) {
                        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
                    }

                    if (notify.setItem) {
                        $rootScope.$broadcast('LocalStorageModule.notification.setitem', {
                            key: key,
                            newvalue: value,
                            storageType: 'cookie'
                        });
                    }
                    return addToCookies(key, value);
                }

                try {
                    if (webStorage) {
                        webStorage.setItem(deriveQualifiedKey(key), value)
                    };
                    if (notify.setItem) {
                        $rootScope.$broadcast('LocalStorageModule.notification.setitem', {
                            key: key,
                            newvalue: value,
                            storageType: self.storageType
                        });
                    }
                } catch (e) {
                    $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
                    return addToCookies(key, value);
                }
                return true;
            };

            // Directly get a value from local storage
            // Example use: localStorageService.get('library'); // returns 'angular'
            var getFromLocalStorage = function(key) {

                if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
                    if (!browserSupportsLocalStorage) {
                        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
                    }

                    return getFromCookies(key);
                }

                var item = webStorage ? webStorage.getItem(deriveQualifiedKey(key)) : null;
                // angular.toJson will convert null to 'null', so a proper conversion is needed
                // FIXME not a perfect solution, since a valid 'null' string can't be stored
                if (!item || item === 'null') {
                    return null;
                }

                return JSON.parse(item);
            };

            // Remove an item from local storage
            // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
            var removeFromLocalStorage = function() {
                var i, key;
                for (i = 0; i < arguments.length; i++) {
                    key = arguments[i];
                    if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
                        if (!browserSupportsLocalStorage) {
                            $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
                        }

                        if (notify.removeItem) {
                            $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {
                                key: key,
                                storageType: 'cookie'
                            });
                        }
                        removeFromCookies(key);
                    } else {
                        try {
                            webStorage.removeItem(deriveQualifiedKey(key));
                            if (notify.removeItem) {
                                $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {
                                    key: key,
                                    storageType: self.storageType
                                });
                            }
                        } catch (e) {
                            $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
                            removeFromCookies(key);
                        }
                    }
                }
            };

            // Return array of keys for local storage
            // Example use: var keys = localStorageService.keys()
            var getKeysForLocalStorage = function() {

                if (!browserSupportsLocalStorage) {
                    $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
                    return false;
                }

                var prefixLength = prefix.length;
                var keys = [];
                for (var key in webStorage) {
                    // Only return keys that are for this app
                    if (key.substr(0, prefixLength) === prefix) {
                        try {
                            keys.push(key.substr(prefixLength));
                        } catch (e) {
                            $rootScope.$broadcast('LocalStorageModule.notification.error', e.Description);
                            return [];
                        }
                    }
                }
                return keys;
            };

            // Remove all data for this app from local storage
            // Also optionally takes a regular expression string and removes the matching key-value pairs
            // Example use: localStorageService.clearAll();
            // Should be used mostly for development purposes
            var clearAllFromLocalStorage = function(regularExpression) {

                // Setting both regular expressions independently
                // Empty strings result in catchall RegExp
                var prefixRegex = !!prefix ? new RegExp('^' + prefix) : new RegExp();
                var testRegex = !!regularExpression ? new RegExp(regularExpression) : new RegExp();

                if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
                    if (!browserSupportsLocalStorage) {
                        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
                    }
                    return clearAllFromCookies();
                }

                var prefixLength = prefix.length;

                for (var key in webStorage) {
                    // Only remove items that are for this app and match the regular expression
                    if (prefixRegex.test(key) && testRegex.test(key.substr(prefixLength))) {
                        try {
                            removeFromLocalStorage(key.substr(prefixLength));
                        } catch (e) {
                            $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
                            return clearAllFromCookies();
                        }
                    }
                }
                return true;
            };

            // Checks the browser to see if cookies are supported
            var browserSupportsCookies = (function() {
                try {
                    return $window.navigator.cookieEnabled ||
                        ("cookie" in $document && ($document.cookie.length > 0 ||
                            ($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
                } catch (e) {
                    $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
                    return false;
                }
            }());

            // Directly adds a value to cookies
            // Typically used as a fallback is local storage is not available in the browser
            // Example use: localStorageService.cookie.add('library','angular');
            var addToCookies = function(key, value, daysToExpiry) {

                if (isUndefined(value)) {
                    return false;
                } else if (isArray(value) || isObject(value)) {
                    value = toJson(value);
                }

                if (!browserSupportsCookies) {
                    $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
                    return false;
                }

                try {
                    var expiry = '',
                        expiryDate = new Date(),
                        cookieDomain = '';

                    if (value === null) {
                        // Mark that the cookie has expired one day ago
                        expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
                        expiry = "; expires=" + expiryDate.toGMTString();
                        value = '';
                    } else if (isNumber(daysToExpiry) && daysToExpiry !== 0) {
                        expiryDate.setTime(expiryDate.getTime() + (daysToExpiry * 24 * 60 * 60 * 1000));
                        expiry = "; expires=" + expiryDate.toGMTString();
                    } else if (cookie.expiry !== 0) {
                        expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000));
                        expiry = "; expires=" + expiryDate.toGMTString();
                    }
                    if (!!key) {
                        var cookiePath = "; path=" + cookie.path;
                        if (cookie.domain) {
                            cookieDomain = "; domain=" + cookie.domain;
                        }
                        $document.cookie = deriveQualifiedKey(key) + "=" + encodeURIComponent(value) + expiry + cookiePath + cookieDomain;
                    }
                } catch (e) {
                    $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
                    return false;
                }
                return true;
            };

            // Directly get a value from a cookie
            // Example use: localStorageService.cookie.get('library'); // returns 'angular'
            var getFromCookies = function(key) {
                if (!browserSupportsCookies) {
                    $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
                    return false;
                }

                var cookies = $document.cookie && $document.cookie.split(';') || [];
                for (var i = 0; i < cookies.length; i++) {
                    var thisCookie = cookies[i];
                    while (thisCookie.charAt(0) === ' ') {
                        thisCookie = thisCookie.substring(1, thisCookie.length);
                    }
                    if (thisCookie.indexOf(deriveQualifiedKey(key) + '=') === 0) {
                        var storedValues = decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length))
                        try {
                            return JSON.parse(storedValues);
                        } catch (e) {
                            return storedValues
                        }
                    }
                }
                return null;
            };

            var removeFromCookies = function(key) {
                addToCookies(key, null);
            };

            var clearAllFromCookies = function() {
                var thisCookie = null,
                    thisKey = null;
                var prefixLength = prefix.length;
                var cookies = $document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    thisCookie = cookies[i];

                    while (thisCookie.charAt(0) === ' ') {
                        thisCookie = thisCookie.substring(1, thisCookie.length);
                    }

                    var key = thisCookie.substring(prefixLength, thisCookie.indexOf('='));
                    removeFromCookies(key);
                }
            };

            var getStorageType = function() {
                return storageType;
            };

            // Add a listener on scope variable to save its changes to local storage
            // Return a function which when called cancels binding
            var bindToScope = function(scope, key, def, lsKey) {
                lsKey = lsKey || key;
                var value = getFromLocalStorage(lsKey);

                if (value === null && isDefined(def)) {
                    value = def;
                } else if (isObject(value) && isObject(def)) {
                    value = extend(def, value);
                }

                $parse(key).assign(scope, value);

                return scope.$watch(key, function(newVal) {
                    addToLocalStorage(lsKey, newVal);
                }, isObject(scope[key]));
            };

            // Return localStorageService.length
            // ignore keys that not owned
            var lengthOfLocalStorage = function() {
                var count = 0;
                var storage = $window[storageType];
                for (var i = 0; i < storage.length; i++) {
                    if (storage.key(i).indexOf(prefix) === 0) {
                        count++;
                    }
                }
                return count;
            };

            return {
                isSupported: browserSupportsLocalStorage,
                getStorageType: getStorageType,
                set: addToLocalStorage,
                add: addToLocalStorage, //DEPRECATED
                get: getFromLocalStorage,
                keys: getKeysForLocalStorage,
                remove: removeFromLocalStorage,
                clearAll: clearAllFromLocalStorage,
                bind: bindToScope,
                deriveKey: deriveQualifiedKey,
                length: lengthOfLocalStorage,
                cookie: {
                    isSupported: browserSupportsCookies,
                    set: addToCookies,
                    add: addToCookies, //DEPRECATED
                    get: getFromCookies,
                    remove: removeFromCookies,
                    clearAll: clearAllFromCookies
                }
            };
        }];
    });
})(window, window.angular);
;app.factory('test', ['$http', '$q', function($http, $q) {
    return {
        needAuth: function() {
            var defer = $q.defer();

            $http({
                    method: 'GET',
                    url: 'api/test'
                })
                .success(function(data, status, headers, config) {
                    defer.resolve(data);
                })
                .error(function(data, status, headers, config) {
                    defer.reject(data);
                });

            return defer.promise;
        }
    };
}]);


text:
<?php

namespace App\Http\Controllers\Email;

use App\Http\Controllers\MainController;
use App\Mail\GenericEmail;
use App\Models\Email;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class EmailSendController extends MainController
{
    /**
     * Save email in queue
     * Change email status to QUEUE (Pending)
     */
    public function send(Request $request, int $id)
    {
        $email = Email::find($id);
        $email->status = Email::QUEUE;
        $email->save();
        $emailTemplate = new GenericEmail(Auth::user()->company, $email->subject, ['body' => $email->body]);
        try {
            Mail::to($email->to)->send($emailTemplate);
            $email->status = Email::SENT;
        } catch (\Throwable $t) {
            Log::error($t->getMessage());
            $email->status = Email::ERROR;
        }
        $email->save();

        return redirect('/email');
    }
}


text:
import sys
import os
import glob
from helpers import download_file

supported_engines = dict()

engines = glob.glob(os.path.join(os.path.dirname(__file__), 'engines','*.py'))
for engine in engines:
    e = engine.split(os.sep)[-1][:-3]
    if len(e.strip()) == 0: continue
    if e.startswith('_'): continue
    try:
        exec("from engines.%s import %s"%(e,e))
        exec("engine_url = %s.url"%e)
        supported_engines[engine_url] = e
    except:
        pass

if __name__ == '__main__':
    if len(sys.argv) < 3:
        raise SystemExit('./nova2dl.py engine_url download_parameter')
    engine_url = sys.argv[1].strip()
    download_param = sys.argv[2].strip()
    if engine_url not in list(supported_engines.keys()):
        raise SystemExit('./nova2dl.py: this engine_url was not recognized')
    exec("engine = %s()"%supported_engines[engine_url])
    if hasattr(engine, 'download_torrent'):
        engine.download_torrent(download_param)
    else:
        print(download_file(download_param))
    sys.exit(0)


text:
#include <device.h>
#include <i2c.h>
#include <misc/util.h>
#include <kernel.h>
#include <sensor.h>

#include "lis3dh.h"

int lis3dh_trigger_set(struct device *dev,
		       const struct sensor_trigger *trig,
		       sensor_trigger_handler_t handler)
{
	struct lis3dh_data *drv_data = dev->driver_data;

	if (trig->type != SENSOR_TRIG_DATA_READY) {
		return -ENOTSUP;
	}

	gpio_pin_disable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);

	drv_data->data_ready_handler = handler;
	if (handler == NULL) {
		return 0;
	}
	drv_data->data_ready_trigger = *trig;

	gpio_pin_enable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);

	return 0;
}

static void lis3dh_gpio_callback(struct device *dev,
				 struct gpio_callback *cb, u32_t pins)
{
	struct lis3dh_data *drv_data =
		CONTAINER_OF(cb, struct lis3dh_data, gpio_cb);

	ARG_UNUSED(pins);

	gpio_pin_disable_callback(dev, CONFIG_LIS3DH_GPIO_PIN_NUM);

#if defined(CONFIG_LIS3DH_TRIGGER_OWN_THREAD)
	k_sem_give(&drv_data->gpio_sem);
#elif defined(CONFIG_LIS3DH_TRIGGER_GLOBAL_THREAD)
	k_work_submit(&drv_data->work);
#endif
}

static void lis3dh_thread_cb(void *arg)
{
	struct device *dev = arg;
	struct lis3dh_data *drv_data = dev->driver_data;

	if (drv_data->data_ready_handler != NULL) {
		drv_data->data_ready_handler(dev,
					     &drv_data->data_ready_trigger);
	}

	gpio_pin_enable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);
}

#ifdef CONFIG_LIS3DH_TRIGGER_OWN_THREAD
static void lis3dh_thread(int dev_ptr, int unused)
{
	struct device *dev = INT_TO_POINTER(dev_ptr);
	struct lis3dh_data *drv_data = dev->driver_data;

	ARG_UNUSED(unused);

	while (1) {
		k_sem_take(&drv_data->gpio_sem, K_FOREVER);
		lis3dh_thread_cb(dev);
	}
}
#endif

#ifdef CONFIG_LIS3DH_TRIGGER_GLOBAL_THREAD
static void lis3dh_work_cb(struct k_work *work)
{
	struct lis3dh_data *drv_data =
		CONTAINER_OF(work, struct lis3dh_data, work);

	lis3dh_thread_cb(drv_data->dev);
}
#endif

int lis3dh_init_interrupt(struct device *dev)
{
	struct lis3dh_data *drv_data = dev->driver_data;

	/* setup data ready gpio interrupt */
	drv_data->gpio = device_get_binding(CONFIG_LIS3DH_GPIO_DEV_NAME);
	if (drv_data->gpio == NULL) {
		SYS_LOG_DBG("Cannot get pointer to %s device",
			    CONFIG_LIS3DH_GPIO_DEV_NAME);
		return -EINVAL;
	}

	gpio_pin_configure(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM,
			   GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE |
			   GPIO_INT_ACTIVE_HIGH | GPIO_INT_DEBOUNCE);

	gpio_init_callback(&drv_data->gpio_cb,
			   lis3dh_gpio_callback,
			   BIT(CONFIG_LIS3DH_GPIO_PIN_NUM));

	if (gpio_add_callback(drv_data->gpio, &drv_data->gpio_cb) < 0) {
		SYS_LOG_DBG("Could not set gpio callback");
		return -EIO;
	}

	/* clear data ready interrupt line by reading sample data */
	if (lis3dh_sample_fetch(dev, SENSOR_CHAN_ALL) < 0) {
		SYS_LOG_DBG("Could not clear data ready interrupt line.");
		return -EIO;
	}

	/* enable data ready interrupt on INT1 line */
	if (i2c_reg_write_byte(drv_data->i2c, LIS3DH_I2C_ADDRESS,
			       LIS3DH_REG_CTRL3, LIS3DH_EN_DRDY1_INT1) < 0) {
		SYS_LOG_DBG("Failed to enable data ready interrupt.");
		return -EIO;
	}

#if defined(CONFIG_LIS3DH_TRIGGER_OWN_THREAD)
	k_sem_init(&drv_data->gpio_sem, 0, UINT_MAX);

	k_thread_create(&drv_data->thread, drv_data->thread_stack,
			CONFIG_LIS3DH_THREAD_STACK_SIZE,
			(k_thread_entry_t)lis3dh_thread, POINTER_TO_INT(dev),
			0, NULL, K_PRIO_COOP(CONFIG_LIS3DH_THREAD_PRIORITY),
			0, 0);
#elif defined(CONFIG_LIS3DH_TRIGGER_GLOBAL_THREAD)
	drv_data->work.handler = lis3dh_work_cb;
	drv_data->dev = dev;
#endif

	gpio_pin_enable_callback(drv_data->gpio, CONFIG_LIS3DH_GPIO_PIN_NUM);

	return 0;
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//
/**
 * ringo core codeigniter class
 *
 * @package  CodeIgniter
 * @subpackage Libraries
 * @category hktp
 * @author Ringo Lau
 * @link
 * @date 2017-07-21
 */

class Upgrades_model extends CI_Model {

 	public function __construct() {
	  $this->load->helper('url');
	  $this->load->database();
	  $this->hktp_db=$this->load->database('HKTP', TRUE);
	  $this->maildb=$this->load->database('maildb', TRUE);
	}

        public function getUpgradeHistory($oid = 'H201702000000') {
	  //return data array
	  $orderid = substr($oid, -6);
	  //$sql="select su.id, su.orders_id, su.fullorder_id, su.staff_id, s.name, su.tc_staff_id, tc.name tcname, su.com_staff_id, com.name comname, su.createddate from square_upgrade su join ".HKTP.".staff s on su.staff_id = s.staffid join ".HKTP.".staff tc on su.tc_staff_id = tc.staffid join ".HKTP.".staff com on su.com_staff_id = com.staffid where su.orders_id=right(?,6) order by su.createddate desc";
	$sql="select su.id, su.orders_id, su.fullorder_id, su.staff_id, su.staff_name, su.tc_staff_id, su.tc_staff_name, su.com_staff_id, com_staff_name, su.createddate from square_upgrade su where su.orders_id=right(?,6) order by su.updatetime desc";
	  $results = $this->db->query($sql, array($orderid));
	  //return an array of result
	  return $results->result_array();
        }

        public function getUpgradeInfo($oid, $upgradeid = '0') {
	  $fullorder_id = $oid;
	  //$orderid = substr($oid, -6);
	  $orders_id = substr($oid, -6);
	  $id = $upgradeid;
	  log_message('debug', 'zzz[Upgrades_model]34:orderid-upgradeid='.$fullorder_id.'-'.$id);
  	  log_message('debug', 'zzz[Upgrades_model]41:id='.$id);
          if ($id > 0) { //upgradeid
	    $sql="SELECT `su`.`id`, `su`.`staff_id`, `su`.staff_name, `su`.staff_teamcode, `su`.staff_channel, `su`.`orders_id`, `su`.`fullorder_id`, `su`.`u_model`, sum.model modelname, `su`.`u_quantity`, `su`.`u_appointmentdate`, `su`.`u_appointmenttime`, `su`.`u_appointmentdatetime`, `su`.`u_smno`, `su`.`u_remark`, `su`.`tc_staff_id`, `su`.`tc_staff_name`, `su`.`tc_staff_teamcode`, `su`.`tc_staff_channel`, `su`.`tc_staff_telno`, `su`.`tc_appointmentdate`, `su`.`tc_appointmenttime`, `su`.`tc_appointmentdatetime`, `su`.`com_staff_id`, `su`.`com_staff_name`, `su`.`com_staff_teamcode`,`su`.`com_staff_channel`,`su`.`com_staff_telno`, `su`.`com_remark`, `su`.`updatetime`, `su`.`createdby`, `su`.`modifiedby`, `su`.`createddate`, `su`.`com_date`
		FROM `square_upgrade` su
		left join `square_upgrade_model` sum on su.u_model = sum.id
		where su.id=?";
	    log_message('debug', 'zzz[Upgrades_model]43:'.$sql);
	    $result = $this->db->query($sql, array($id));
	    $data = $result->row_array();
          } else {
	    $sql="SELECT 0 id, 0 staff_id, '' staff_name, '' staff_teamcode, '' staff_channel, id `orders_id`, serial fullorder_id , 0 `u_model`, '' modelname, 0 `u_quantity`, '' `u_appointmentdate`, '' `u_appointmenttime`, '' `u_appointmentdatetime`, '' `u_smno`, '' `u_remark`, 0 `tc_staff_id`, '' `tc_staff_name`, '' `tc_staff_teamcode`, '' `tc_staff_channel`, '' `tc_staff_telno`, '' `tc_appointmentdate`, '' `tc_appointmenttime`, '' `tc_appointmentdatetime`, 0 `com_staff_id`, '' `com_staff_name`, '' `com_staff_teamcode`,'' `com_staff_channel`,'' `com_staff_telno`, '' `com_remark`, '' `updatetime`, '' `createdby`, '' `modifiedby`, '' `createddate`, '' `com_date` FROM orders o where id=?";

	    log_message('debug', 'zzz[Upgrades_model]53:'.$sql);
	    $result = $this->db->query($sql, array($orders_id));
	    $data = $result->row_array();
          }
	  log_message('debug','zzz[Upgrades_model]56:'. json_encode(array($orders_id)));
	  log_message('debug', 'zzz[Upgrades_model]57:'.json_encode($data));

	  $sql = "select `id`,`model` from square_upgrade_model";
	  $result = $this->db->query($sql);
	  $data['tab_model'] = $result->result_array();

	  return $data;
        }

        public function set_upgrades() {
	  //log action
	  //update/insert table
	  //$customername = url_title($this->input->post('customername'), 'underscore' ,TRUE);

          $id = $this->input->post('id'); //upgrade id
          $staff_id = $this->input->post('staff_id');
          $staff_name = $this->input->post('staff_name');
          $staff_teamcode = $this->input->post('staff_teamcode');
          $staff_channel = $this->input->post('staff_channel');
          $fullorder_id = $this->input->post('fullorder_id');
          $orders_id = substr($this->input->post('fullorder_id'),-6);
	  $u_model = $this->input->post('u_model');
	  $u_quantity = $this->input->post('u_quantity');
	  $u_appointmentdate = $this->input->post('u_appointmentdate');
	  $u_appointmenttime = $this->input->post('u_appointmenttime');
	  $u_appointmentdatetime = $this->input->post('u_appointmentdatetime');
	  if (strlen($u_appointmentdatetime)<3)
	    $u_appointmentdatetime = null;
	  $u_smno = $this->input->post('u_smno');
	  $u_remark = $this->input->post('u_remark');
	  $tc_staff_id = $this->input->post('tc_staff_id');
	  $tc_staff_name = $this->input->post('tc_staff_name');
	  $tc_staff_teamcode = $this->input->post('tc_staff_teamcode');
	  $tc_staff_channel = $this->input->post('tc_staff_channel');
	  $tc_staff_telno = $this->input->post('tc_staff_telno');
	  $tc_appointmentdate = $this->input->post('tc_appointmentdate');
	  $tc_appointmenttime= $this->input->post('tc_appointmenttime');
	  $tc_appointmentdatetime= $this->input->post('tc_appointmentdatetime');
	  if (strlen($tc_appointmentdatetime)<3)
	    $tc_appointmentdatetime = null;
	  $com_staff_id = $this->input->post('com_staff_id');
	  $com_staff_name = $this->input->post('com_staff_name');
	  $com_staff_teamcode = $this->input->post('com_staff_teamcode');
	  $com_staff_telno = $this->input->post('com_staff_telno');
	  $com_staff_channel = $this->input->post('com_staff_channel');
	  $com_remark = $this->input->post('com_remark');
	  //$createdby = $this->input->post('createdby');
	  //$modifiedby = $this->input->post('modifiedby');
	  $com_date = $this->input->post('com_date');
	  if (strlen($com_date)<3)
	    $com_date = null;
	  $com_staff_id = $this->input->post('com_staff_id');
          $action = $this->input->post('action');

	  $ret['fullorder_id']=$fullorder_id;
	  $ret['id']=$id; //upgrade id
	  $ret['msg']='DONE';

	  log_message('debug', 'zzz[Upgrades_model]215(orderid-upgradeid):'.$fullorder_id.'-'.$id);

	  //check appointment quota
	/*
	  $appointmentquota = 0;
	  $sql = "select quotaused+1<=quota c from square_fault_appointment where id=?";
	  log_message('debug', 'zzz[Faults_model]220:check quota'.$sql);
	  $results = $this->db->query($sql, array($f_appointmentid));
	  if ($results->num_rows() > 0) {
	    $row = $results->row_array();
	    $appointmentquota = $row['c'];
	  }

	  if ($appointmentquota>0) {
	    if ($f_appointmentid-$f_o_appointmentid!=0) {
	      //quotaused ++
	      log_message('debug', 'zzz[Faults_model]218:quotaused++'.$orderid.'-'.$faultid.'-'.$f_appointmentid);
	      $sql = "update square_fault_appointment set quotaused=quotaused+1 where id=".$f_appointmentid;
	      $presult = $this->db->query($sql);
	      //$this->db->set('quotaused', 'quotaused+1');
	      //$this->db->where('id', $f_appointmentid);
	      //$presult = $this->db->update('square_fault_appointment');
	      if (!$presult) {
	        $ret['msg']="ERR236: database error, Failed to modify quota table, please contact system administrator";
	        return $ret;
	      }

	      if ($presult) {
	        if ($f_o_appointmentid>0) {
	          // quotaused -- for old quota
	          log_message('debug', 'zzz[Faults_model]216:quotaused--'.$orderid.'-'.$faultid.'-'.$f_o_appointmentid);
	          $this->db->set('quotaused', 'quotaused-1');
	          $this->db->where('id', $f_o_appointmentid);
	          $presult = $this->db->update('square_fault_appointment');
	          if (!$presult) {
	            $ret['msg']="ERR248: database error, Failed to modify quota table, please contact system administrator";
	            return $ret;
	          }
	        }
	      }
	    } else {
	      $presult = true;
	    }
	  } else {
	    $ret['msg']="ERR257: Quota Full";
	    return $ret;
	  }
	*/
	//bypass quota checking, no need to check
	$presult = true;

	  if ($presult) {
 	    if ($id == 0) { //upgradeid (insert)
	      $data = array (
		'staff_id' => $staff_id,
		'staff_name' => $staff_name,
		'staff_teamcode' => $staff_teamcode,
                'staff_channel' => $staff_channel,
		'orders_id' => $orders_id,
		'fullorder_id' => $fullorder_id,
		'u_model' => $u_model,
		'u_quantity' => $u_quantity,
	        'u_appointmentdate' => $u_appointmentdate,
		'u_appointmenttime' => $u_appointmenttime,
		'u_appointmentdatetime' => $u_appointmentdatetime,
		'u_smno' => $u_smno,
		'u_remark' => $u_remark,
		'tc_staff_id' => $tc_staff_id,
		'tc_staff_name' => $tc_staff_name,
		'tc_staff_teamcode' => $tc_staff_teamcode,
		'tc_staff_channel' => $tc_staff_channel,
		'tc_staff_telno' => $tc_staff_telno,
		'tc_appointmentdate' => $tc_appointmentdate,
		'tc_appointmenttime' => $tc_appointmenttime,
		'tc_appointmentdatetime' => $tc_appointmentdatetime,
		'com_staff_id' => $com_staff_id,
		'com_staff_name' => $com_staff_name,
		'com_staff_teamcode' => $com_staff_teamcode,
		'com_staff_channel' => $com_staff_channel,
		'com_staff_telno' => $com_staff_telno,
		'com_remark' => $com_remark,
		'com_date' => $com_date,
		'createdby' => $this->session->userdata('s_staffid'),
		'modifiedby' => $this->session->userdata('s_staffid'),
		'createddate' => date("Y-m-d H:i:s")
	      );
	      if ($data['staff_id'] != null)  {
	        log_message('debug', 'zzz[Upgrades_model]261/insert:'.json_encode($data));
	        $row = $this->insert_log('upgrade','insert',$data,'');
	        if ($row == 1) {
		  //$row = $this->email('HS - upgrade','ringo.wc.lau@pccw.com','HS - Upgrade', json_encode($data));
                  $row = $this->db->insert('square_upgrade', $data);
	          if ($row==0) {
	            $ret['msg']="ERR232: database error, Failed to insert upgrade, please contact system administrator";
	            return $ret;
	          }
		  $ret['upgradeid'] = $this->db->insert_id();
	          log_message('debug', 'zzz[Upgrades_model]290:row='.$row);
	          log_message('debug', 'zzz[Upgrades_model]291:actionupgradeid='.$ret['upgradeid']);
                  $row = $this->email('HS - Upgrade','',$this->emailSubject($data,$ret['upgradeid']), $this->emailContent($data,$ret['upgradeid']));
		  $ret['msg']='New Record Added Successfully.';
	        }
  	      }
	    } else { //update
	      $data = array (
		'staff_id' => $staff_id,
		'staff_name' => $staff_name,
		'staff_teamcode' => $staff_teamcode,
                'staff_channel' => $staff_channel,
		'orders_id' => $orders_id,
		'fullorder_id' => $fullorder_id,
		'u_model' => $u_model,
		'u_quantity' => $u_quantity,
	        'u_appointmentdate' => $u_appointmentdate,
		'u_appointmenttime' => $u_appointmenttime,
		'u_appointmentdatetime' => $u_appointmentdatetime,
		'u_smno' => $u_smno,
		'u_remark' => $u_remark,
		'tc_staff_id' => $tc_staff_id,
		'tc_staff_name' => $tc_staff_name,
		'tc_staff_teamcode' => $tc_staff_teamcode,
		'tc_staff_channel' => $tc_staff_channel,
		'tc_staff_telno' => $tc_staff_telno,
		'tc_appointmentdate' => $tc_appointmentdate,
		'tc_appointmenttime' => $tc_appointmenttime,
		'tc_appointmentdatetime' => $tc_appointmentdatetime,
		'com_staff_id' => $com_staff_id,
		'com_staff_name' => $com_staff_name,
		'com_staff_teamcode' => $com_staff_teamcode,
		'com_staff_channel' => $com_staff_channel,
		'com_staff_telno' => $com_staff_telno,
		'com_remark' => $com_remark,
		'com_date' => $com_date,
		'modifiedby' => $this->session->userdata('s_staffid')
		//'createdby' => $this->session->userdata('s_staffid'),
		//'createddate' => date("Y-m-d H:i:s")
	      );
	      log_message('debug', 'zzz[Upgrades_model]248/update:'.json_encode($data));
	      $row = $this->insert_log('upgrade','update',$data,$id);
	      if ($row == 1) {
	        //$row = $this->email('HS - fault','ringo.wc.lau@pccw.com','HS - Fault', json_encode($data));
	        $this->db->where('id', $id);
	        $row = $this->db->update('square_upgrade', $data);
	        log_message('debug', 'zzz[Upgrades_model]286:row='.$row);
	        if ($row==0) {
	          $ret['msg']="ERR232: database error, Failed to update upgrade, please contact system administrator";
	          return $ret;
	        }
	        log_message('debug', 'zzz[Upgrades]287:actionupgradeid='.$ret['id']);
		$ret['msg']='Record Updated Successfully.';
	      }
	    }
	    $ret['line']='309';
	    return $ret;
          } else {
	    $ret['line']='312';
	    return $ret;
	  }
	}

        public function insert_log($section, $action, $raw, $other) {
	  $staffid = $raw['staff_id'];
	  $modifiedby = $raw['modifiedby'];
	  //$raw['c_uid'] = 'XXXXXX';
	  //$raw['c_contact'] = 'XXXXXXXX';
	  if (strlen($other)>0)
	    $d = '{upgradeid:'.$other.'},'.json_encode($raw);
  	  else
	    $d = json_encode($raw);
	  $data = array (
		'section' => $section,
		'action' => $action,
		'user' => $staffid,
		'modifiedby' => $modifiedby,
		'data' => $d
	  );
          $row = $this->db->insert('square_log', $data);
	  return $row;
	}

        public function emailSubject($data, $id) {
          $upgradeid = $data['fullorder_id']."-".$id;
          $subject = 'New order created (HS-Upgrade ';
          $subject = $subject.$upgradeid.')';
          return $subject;
        }

        public function emailContent($data, $id) {
          $upgradeid = $data['fullorder_id']."-".$id;
          $ordertype = "HS-Upgrade";
          $content='New order created
Order type: '.$ordertype.'
Order ID: '.$upgradeid.'
Created by: '.$data['createdby'].'
Created Date: '.$data['createddate'].'
Please visit Home Solution to review the order.
This is an automatically generated email.  Please do not reply.';
          return $content;
        }

 	public function email($section, $mailto, $mailsubject, $mailcontent) {
	  $data = array (
		'mail_system' => $section,
		'mail_to' => TCADMINEMAIL,
		'mail_subject' => $mailsubject,
		'mail_content' => $mailcontent,
		'mail_inserttime' => date("Y-m-d H:i:s")
	  );
	  $row = $this->maildb->insert('mailsend', $data);
	  log_message('debug', 'zzz[Upgrades_model]291/insert maildb:'.json_encode($data));
	  return $row;
  	}

}


text:
package com.dongdongxia.my.jdk8.lambda;
/**
 *
 *
Description: demo

 * @ClassName: InstanceMethWithObjectRefDemo
 * @author java_liudong@163.com  2017年12月5日 下午2:29:28
 */
public class InstanceMethWithObjectRefDemo {

    static <T> int counter(T[] vals, MyFunc<T> f, T v) {
        int count = 0;
        for (int i = 0; i < vals.length; i++) {
            if (f.func(vals[i], v)) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int count;

        HighTemp[] weekDayHighs = {new HighTemp(89), new HighTemp(82), new HighTemp(90), new HighTemp(89), new HighTemp(89),
                new HighTemp(91), new HighTemp(84), new HighTemp(83)};

        count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(12));
        System.out.println(count + " days had a high of 12");
        count = counter(weekDayHighs, HighTemp::lessThanTemp, new HighTemp(89));
        System.out.println(count + " days had a high less than 89");
    }
}

interface MyFunc<T> {

    boolean func(T v1, T v2);
}

class HighTemp {

    private int hTemp;

    HighTemp(int hTemp) {
        this.hTemp = hTemp;
    }

    boolean sameTemp(HighTemp ht2) {
        return hTemp == ht2.hTemp;
    }

    boolean lessThanTemp(HighTemp ht2) {
        return hTemp < ht2.hTemp;
    }
}


text:
<?php

abstract class DrydockController extends PhabricatorController {

  abstract public function buildSideNavView();

  public function buildApplicationMenu() {
    return $this->buildSideNavView()->getMenu();
  }

}


text:
package arg

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type NameDotName struct {
	Head, Tail string
}

func (n *NameDotName) UnmarshalText(b []byte) error {
	s := string(b)
	pos := strings.Index(s, ".")
	if pos == -1 {
		return fmt.Errorf("missing period in %s", s)
	}
	n.Head = s[:pos]
	n.Tail = s[pos+1:]
	return nil
}

func (n *NameDotName) MarshalText() (text []byte, err error) {
	text = []byte(fmt.Sprintf("%s.%s", n.Head, n.Tail))
	return
}

func TestWriteUsage(t *testing.T) {
	expectedUsage := "Usage: example [--name NAME] [--value VALUE] [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] [--ids IDS] [--values VALUES] [--workers WORKERS] [--testenv TESTENV] [--file FILE] INPUT [OUTPUT [OUTPUT ...]]"

	expectedHelp := `
Usage: example [--name NAME] [--value VALUE] [--verbose] [--dataset DATASET] [--optimize OPTIMIZE] [--ids IDS] [--values VALUES] [--workers WORKERS] [--testenv TESTENV] [--file FILE] INPUT [OUTPUT [OUTPUT ...]]

Positional arguments:
  INPUT
  OUTPUT                 list of outputs

Options:
  --name NAME            name to use [default: Foo Bar]
  --value VALUE          secret value [default: 42]
  --verbose, -v          verbosity level
  --dataset DATASET      dataset to use
  --optimize OPTIMIZE, -O OPTIMIZE
                         optimization level
  --ids IDS              Ids
  --values VALUES        Values
  --workers WORKERS, -w WORKERS
                         number of workers to start [default: 10, env: WORKERS]
  --testenv TESTENV, -a TESTENV [env: TEST_ENV]
  --file FILE, -f FILE   File with mandatory extension [default: scratch.txt]
  --help, -h             display this help and exit
`

	var args struct {
		Input    string       `arg:"positional,required"`
		Output   []string     `arg:"positional" help:"list of outputs"`
		Name     string       `help:"name to use"`
		Value    int          `help:"secret value"`
		Verbose  bool         `arg:"-v" help:"verbosity level"`
		Dataset  string       `help:"dataset to use"`
		Optimize int          `arg:"-O" help:"optimization level"`
		Ids      []int64      `help:"Ids"`
		Values   []float64    `help:"Values"`
		Workers  int          `arg:"-w,env:WORKERS" help:"number of workers to start" default:"10"`
		TestEnv  string       `arg:"-a,env:TEST_ENV"`
		File     *NameDotName `arg:"-f" help:"File with mandatory extension"`
	}
	args.Name = "Foo Bar"
	args.Value = 42
	args.File = &NameDotName{"scratch", "txt"}
	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	os.Args[0] = "example"

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

type MyEnum int

func (n *MyEnum) UnmarshalText(b []byte) error {
	return nil
}

func (n *MyEnum) MarshalText() ([]byte, error) {
	return nil, errors.New("There was a problem")
}

func TestUsageWithDefaults(t *testing.T) {
	expectedUsage := "Usage: example [--label LABEL] [--content CONTENT]"

	expectedHelp := `
Usage: example [--label LABEL] [--content CONTENT]

Options:
  --label LABEL [default: cat]
  --content CONTENT [default: dog]
  --help, -h             display this help and exit
`
	var args struct {
		Label   string
		Content string `default:"dog"`
	}
	args.Label = "cat"
	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	args.Label = "should_ignore_this"

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestUsageCannotMarshalToString(t *testing.T) {
	var args struct {
		Name *MyEnum
	}
	v := MyEnum(42)
	args.Name = &v
	_, err := NewParser(Config{Program: "example"}, &args)
	assert.EqualError(t, err, `args.Name: error marshaling default value to string: There was a problem`)
}

func TestUsageLongPositionalWithHelp_legacyForm(t *testing.T) {
	expectedUsage := "Usage: example [VERYLONGPOSITIONALWITHHELP]"

	expectedHelp := `
Usage: example [VERYLONGPOSITIONALWITHHELP]

Positional arguments:
  VERYLONGPOSITIONALWITHHELP
                         this positional argument is very long but cannot include commas

Options:
  --help, -h             display this help and exit
`
	var args struct {
		VeryLongPositionalWithHelp string `arg:"positional,help:this positional argument is very long but cannot include commas"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestUsageLongPositionalWithHelp_newForm(t *testing.T) {
	expectedUsage := "Usage: example [VERYLONGPOSITIONALWITHHELP]"

	expectedHelp := `
Usage: example [VERYLONGPOSITIONALWITHHELP]

Positional arguments:
  VERYLONGPOSITIONALWITHHELP
                         this positional argument is very long, and includes: commas, colons etc

Options:
  --help, -h             display this help and exit
`
	var args struct {
		VeryLongPositionalWithHelp string `arg:"positional" help:"this positional argument is very long, and includes: commas, colons etc"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestUsageWithProgramName(t *testing.T) {
	expectedUsage := "Usage: myprogram"

	expectedHelp := `
Usage: myprogram

Options:
  --help, -h             display this help and exit
`
	config := Config{
		Program: "myprogram",
	}
	p, err := NewParser(config, &struct{}{})
	require.NoError(t, err)

	os.Args[0] = "example"

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

type versioned struct{}

// Version returns the version for this program
func (versioned) Version() string {
	return "example 3.2.1"
}

func TestUsageWithVersion(t *testing.T) {
	expectedUsage := "example 3.2.1\nUsage: example"

	expectedHelp := `
example 3.2.1
Usage: example

Options:
  --help, -h             display this help and exit
  --version              display version and exit
`
	os.Args[0] = "example"
	p, err := NewParser(Config{}, &versioned{})
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

type described struct{}

// Described returns the description for this program
func (described) Description() string {
	return "this program does this and that"
}

func TestUsageWithDescription(t *testing.T) {
	expectedUsage := "Usage: example"

	expectedHelp := `
this program does this and that
Usage: example

Options:
  --help, -h             display this help and exit
`
	os.Args[0] = "example"
	p, err := NewParser(Config{}, &described{})
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

type epilogued struct{}

// Epilogued returns the epilogue for this program
func (epilogued) Epilogue() string {
	return "For more information visit github.com/alexflint/go-arg"
}

func TestUsageWithEpilogue(t *testing.T) {
	expectedUsage := "Usage: example"

	expectedHelp := `
Usage: example

Options:
  --help, -h             display this help and exit

For more information visit github.com/alexflint/go-arg
`
	os.Args[0] = "example"
	p, err := NewParser(Config{}, &epilogued{})
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestUsageForRequiredPositionals(t *testing.T) {
	expectedUsage := "Usage: example REQUIRED1 REQUIRED2\n"
	var args struct {
		Required1 string `arg:"positional,required"`
		Required2 string `arg:"positional,required"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, usage.String())
}

func TestUsageForMixedPositionals(t *testing.T) {
	expectedUsage := "Usage: example REQUIRED1 REQUIRED2 [OPTIONAL1 [OPTIONAL2]]\n"
	var args struct {
		Required1 string `arg:"positional,required"`
		Required2 string `arg:"positional,required"`
		Optional1 string `arg:"positional"`
		Optional2 string `arg:"positional"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, usage.String())
}

func TestUsageForRepeatedPositionals(t *testing.T) {
	expectedUsage := "Usage: example REQUIRED1 REQUIRED2 REPEATED [REPEATED ...]\n"
	var args struct {
		Required1 string   `arg:"positional,required"`
		Required2 string   `arg:"positional,required"`
		Repeated  []string `arg:"positional,required"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, usage.String())
}

func TestUsageForMixedAndRepeatedPositionals(t *testing.T) {
	expectedUsage := "Usage: example REQUIRED1 REQUIRED2 [OPTIONAL1 [OPTIONAL2 [REPEATED [REPEATED ...]]]]\n"
	var args struct {
		Required1 string   `arg:"positional,required"`
		Required2 string   `arg:"positional,required"`
		Optional1 string   `arg:"positional"`
		Optional2 string   `arg:"positional"`
		Repeated  []string `arg:"positional"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, usage.String())
}

func TestRequiredMultiplePositionals(t *testing.T) {
	expectedUsage := "Usage: example REQUIREDMULTIPLE [REQUIREDMULTIPLE ...]\n"

	expectedHelp := `
Usage: example REQUIREDMULTIPLE [REQUIREDMULTIPLE ...]

Positional arguments:
  REQUIREDMULTIPLE       required multiple positional

Options:
  --help, -h             display this help and exit
`
	var args struct {
		RequiredMultiple []string `arg:"positional,required" help:"required multiple positional"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, usage.String())
}

func TestUsageWithNestedSubcommands(t *testing.T) {
	expectedUsage := "Usage: example child nested [--enable] OUTPUT"

	expectedHelp := `
Usage: example child nested [--enable] OUTPUT

Positional arguments:
  OUTPUT

Options:
  --enable

Global options:
  --values VALUES        Values
  --verbose, -v          verbosity level
  --help, -h             display this help and exit
`

	var args struct {
		Verbose bool `arg:"-v" help:"verbosity level"`
		Child   *struct {
			Values []float64 `help:"Values"`
			Nested *struct {
				Enable bool
				Output string `arg:"positional,required"`
			} `arg:"subcommand:nested"`
		} `arg:"subcommand:child"`
	}

	os.Args[0] = "example"
	p, err := NewParser(Config{}, &args)
	require.NoError(t, err)

	_ = p.Parse([]string{"child", "nested", "value"})

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var help2 bytes.Buffer
	p.WriteHelpForSubcommand(&help2, "child", "nested")
	assert.Equal(t, expectedHelp[1:], help2.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))

	var usage2 bytes.Buffer
	p.WriteUsageForSubcommand(&usage2, "child", "nested")
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage2.String()))
}

func TestNonexistentSubcommand(t *testing.T) {
	var args struct {
		sub *struct{} `arg:"subcommand"`
	}
	p, err := NewParser(Config{}, &args)
	require.NoError(t, err)

	var b bytes.Buffer

	err = p.WriteUsageForSubcommand(&b, "does_not_exist")
	assert.Error(t, err)

	err = p.WriteHelpForSubcommand(&b, "does_not_exist")
	assert.Error(t, err)

	err = p.FailSubcommand("something went wrong", "does_not_exist")
	assert.Error(t, err)

	err = p.WriteUsageForSubcommand(&b, "sub", "does_not_exist")
	assert.Error(t, err)

	err = p.WriteHelpForSubcommand(&b, "sub", "does_not_exist")
	assert.Error(t, err)

	err = p.FailSubcommand("something went wrong", "sub", "does_not_exist")
	assert.Error(t, err)
}

func TestUsageWithoutLongNames(t *testing.T) {
	expectedUsage := "Usage: example [-a PLACEHOLDER] -b SHORTONLY2"

	expectedHelp := `
Usage: example [-a PLACEHOLDER] -b SHORTONLY2

Options:
  -a PLACEHOLDER         some help [default: some val]
  -b SHORTONLY2          some help2
  --help, -h             display this help and exit
`
	var args struct {
		ShortOnly  string `arg:"-a,--" help:"some help" default:"some val" placeholder:"PLACEHOLDER"`
		ShortOnly2 string `arg:"-b,--,required" help:"some help2"`
	}
	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestUsageWithShortFirst(t *testing.T) {
	expectedUsage := "Usage: example [-c CAT] [--dog DOG]"

	expectedHelp := `
Usage: example [-c CAT] [--dog DOG]

Options:
  -c CAT
  --dog DOG
  --help, -h             display this help and exit
`
	var args struct {
		Dog string
		Cat string `arg:"-c,--"`
	}
	p, err := NewParser(Config{Program: "example"}, &args)
	assert.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestUsageWithEnvOptions(t *testing.T) {
	expectedUsage := "Usage: example [-s SHORT]"

	expectedHelp := `
Usage: example [-s SHORT]

Options:
  -s SHORT [env: SHORT]
  --help, -h             display this help and exit
`
	var args struct {
		Short            string `arg:"--,-s,env"`
		EnvOnly          string `arg:"--,env"`
		EnvOnlyOverriden string `arg:"--,env:CUSTOM"`
	}

	p, err := NewParser(Config{Program: "example"}, &args)
	assert.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())

	var usage bytes.Buffer
	p.WriteUsage(&usage)
	assert.Equal(t, expectedUsage, strings.TrimSpace(usage.String()))
}

func TestFail(t *testing.T) {
	originalStderr := stderr
	originalExit := osExit
	defer func() {
		stderr = originalStderr
		osExit = originalExit
	}()

	var b bytes.Buffer
	stderr = &b

	var exitCode int
	osExit = func(code int) { exitCode = code }

	expectedStdout := `
Usage: example [--foo FOO]
error: something went wrong
`

	var args struct {
		Foo int
	}
	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)
	p.Fail("something went wrong")

	assert.Equal(t, expectedStdout[1:], b.String())
	assert.Equal(t, -1, exitCode)
}

func TestFailSubcommand(t *testing.T) {
	originalStderr := stderr
	originalExit := osExit
	defer func() {
		stderr = originalStderr
		osExit = originalExit
	}()

	var b bytes.Buffer
	stderr = &b

	var exitCode int
	osExit = func(code int) { exitCode = code }

	expectedStdout := `
Usage: example sub
error: something went wrong
`

	var args struct {
		Sub *struct{} `arg:"subcommand"`
	}
	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	err = p.FailSubcommand("something went wrong", "sub")
	require.NoError(t, err)

	assert.Equal(t, expectedStdout[1:], b.String())
	assert.Equal(t, -1, exitCode)
}

type lengthOf struct {
	Length int
}

func (p *lengthOf) UnmarshalText(b []byte) error {
	p.Length = len(b)
	return nil
}

func TestHelpShowsDefaultValueFromOriginalTag(t *testing.T) {
	// check that the usage text prints the original string from the default tag, not
	// the serialization of the parsed value

	expectedHelp := `
Usage: example [--test TEST]

Options:
  --test TEST [default: some_default_value]
  --help, -h             display this help and exit
`

	var args struct {
		Test *lengthOf `default:"some_default_value"`
	}
	p, err := NewParser(Config{Program: "example"}, &args)
	require.NoError(t, err)

	var help bytes.Buffer
	p.WriteHelp(&help)
	assert.Equal(t, expectedHelp[1:], help.String())
}