text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using HZLApp.Entity;
using System.Data;

namespace HZLApp.DAL
{
  public  class DBAccessHelper
    {

      LogHelper log = new LogHelper();
      private static readonly string StrCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + System.Configuration.ConfigurationManager.ConnectionStrings["HZLACCESSDB"].ConnectionString + ";Persist Security Info=True;Jet OLEDB:Database Password=hzl123";

        public  string strCon()
      {
          string strCon = "";
        try
        {
            strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + System.Configuration.ConfigurationManager.ConnectionStrings["HZLACCESSDB"].ConnectionString + ";Persist Security Info=True;Jet OLEDB:Database Password=hzl123";

        }
        catch (Exception ex) { log.wrirteLog("数据库操作","链接是否有效",ex.Message); }
        return strCon;
    }
         // string strCon = StrCon();
      //AccessHelper.conn_str;

      /// <summary>
      /// 登录是否有效
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public bool IsVaileLogin(H_UserEntity ue)
      {
           bool result = true;
           try
           {

               string SqlStr = "SELECT * FROM H_User where UserLoginName=@ul and UserPWD=@pwd";
               OleDbParameter[] prams = {
                                                 new OleDbParameter("@ul", ue.UserLoginName),
                                                 new OleDbParameter("@pwd", ue.UserPWD)
                                             };
               DataSet ds = AccessHelper.ExecuteDataSet(strCon(), SqlStr, prams);
               if (ds == null) result = false;
               else if (ds.Tables[0].Rows.Count == 0) result = false;
               else result = true;
               UserPublicClass.LoginValue = ue.UserLoginName;
               UserPublicClass.NameValue = ds.Tables[0].Rows[0]["UserName"].ToString();
               UserPublicClass.PWDValue = ds.Tables[0].Rows[0]["UserPWD"].ToString();
           }
           catch (Exception ex)
           {
               log.wrirteLog("数据库操作", "登录是否有效", ex.Message);
               result = false;
           }
           return result;

      }

      /// <summary>
      /// 修改密码
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public int UpdatePWD(string userlogin,string newpwd)
      {
          int result = 0;
          try
          {

              string SqlStr = "UPDATE   H_User SET UserPWD='" + newpwd + "',DoTime='" + DateTime.Now.ToString() + "' where UserLoginName='" + userlogin + "' ";
              OleDbParameter[] prams = {
                                                 new OleDbParameter("@ul", userlogin),
                                                 new OleDbParameter("@pwd", newpwd),
                                                     new OleDbParameter("@u3", DateTime.Now.ToString())
                                             };
             result=  AccessHelper.ExecuteNonQuery(strCon(), SqlStr, prams);
               }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "修改密码", ex.Message);
              result = 0;
          }
          return result;

      }

      public DataSet GetDSPara()
      {
          try
          {

              string SqlStr = "SELECT * FROM H_Style ";
              OleDbParameter[] prams = {

                                             };
              DataSet ds = AccessHelper.ExecuteDataSet(strCon(), SqlStr, null);
              if (ds == null) return null;
              else return ds;

              }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "获取类型Style", ex.Message);
              return null;
          }
      }

      public string GetMaxID(string Perstr,string StrTable)
      {
          try
          {

              string SqlStr = "SELECT Max(HID) as HID FROM " + StrTable + " ";
              OleDbParameter[] prams = {

                                             };
              DataSet ds = AccessHelper.ExecuteDataSet(strCon(), SqlStr, null);
              if (ds == null) return Perstr+"001";
              else if (ds.Tables[0].Rows.Count <= 0) return Perstr + "001";
              else
              {
                  string StrMaxID = ds.Tables[0].Rows[0][0].ToString().Replace(Perstr,"");
                  int IntMaxID = int.Parse(StrMaxID)+1;
                  return Perstr + IntMaxID.ToString("000");
              }

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "获取最大编号", ex.Message);
              return Perstr+"001";
          }
      }

      /// <summary>
      /// 参数增加
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public bool InsertH_Para(string StrTable,string filename,string HID)
      {
          bool result = true;
          try
          {

              string SqlStr = "Insert into " + StrTable + " (HID,HName,HAdress,DoTime) " +
                  " values('" + HID + "','" + filename + "','" + filename + "','" + DateTime.Now.ToString() + "') ";

            int  intresult = AccessHelper.ExecuteNonQuery(strCon(),SqlStr,null);
            if (intresult == 0) result = false;
            else result = true;

            }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "增加各类基础参数", ex.Message);
              result = false;
          }
          return result;

      }

      /// <summary>
      /// 参数增加
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public bool DeleteH_Para(string StrTable,   string HID)
      {
          bool result = true;
          try
          {

              string SqlStr = "Delete from " + StrTable + "  where HID='" + HID + "' ";

              int intresult = AccessHelper.ExecuteNonQuery(strCon(), SqlStr, null);
              if (intresult == 0) result = false;
              else result = true;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "删除各类基础参数", ex.Message);
              result = false;
          }
          return result;

      }

      /// <summary>
      /// 公司
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public bool InsertCompany(H_CompanyEntity hce)
      {
          bool result = true;
          try
          {
              string SqlStr = "  " +
                  " Insert into H_Company (CID,CName,CTelphone,CColor,CGlass, CIsGlass, CRemarks,CAdress, DoTime) " +
                  " values(@c1,@c2,@c3,@c4,@c5,@c6,@c7,@c8,@c9) " ;
              OleDbParameter[] prams = {
                                                     new OleDbParameter("@c1", hce.CID),
                                                     new OleDbParameter("@c2", hce.CName),
                                                       new OleDbParameter("@c3", hce.CTelphone),
                                                     new OleDbParameter("@c4", hce.CColor),
                                                       new OleDbParameter("@c5", hce.CGlass),
                                                     new OleDbParameter("@c6", hce.CIsGlass),
                                                       new OleDbParameter("@c7", hce.CRemarks),
                                                     new OleDbParameter("@c8", hce.CAdress),
                                                      new OleDbParameter("@c9", DateTime.Now.ToString())
                                                 };

              int intresult = AccessHelper.ExecuteNonQuery(strCon(), SqlStr, prams);
              if (intresult == 0) result = false;
              else result = true;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "公司资料增加", ex.Message);
              result = false;
          }
          return result;

      }

      public int DeleteCompany(H_CompanyEntity hce)
      {
          int intResult = 0;
          string strSql = "Delete from  H_Company where CID=@c1";
          OleDbParameter[] prams = {
                                             new OleDbParameter("@c1", hce.CID)
                                         };
          intResult = AccessHelper.ExecuteNonQuery(strCon(), strSql, prams);
          return intResult;
      }

      public DataSet GetDSCompany(string CID)
      {
          try
          {
               string SqlStr = "SELECT * FROM H_Company ";
              if(CID!="")
              SqlStr += "  WHERE CID='"+CID+"'";
              OleDbParameter[] prams = {

                                             };
              DataSet ds = AccessHelper.ExecuteDataSet(strCon(), SqlStr, null);
              if (ds == null) return null;
              else return ds;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "公司资料", ex.Message);
              return null;
          }
      }

      public int DeleteBusiness_Main(H_Bus_MainEntity hce)
      {
          int intResult = 0;
          string strSql = "Delete from  H_Business_Main where CCID=@c1";
          OleDbParameter[] prams = {
                                             new OleDbParameter("@c1", hce.CCID)
                                         };
          intResult = AccessHelper.ExecuteNonQuery(strCon(), strSql, prams);
          return intResult;
      }

      public int DeleteBusiness_Detail(H_Bus_DetailEntity hce)
      {
          int intResult = 0;
          string strSql = "Delete from  H_Business_Detail where CCID=@c1 AND CDetailID=@c2";
          OleDbParameter[] prams = {
                                             new OleDbParameter("@c1", hce.CCID),
                                              new OleDbParameter("@c2", hce.CDetailID)
                                         };
          intResult = AccessHelper.ExecuteNonQuery(strCon(), strSql, prams);
          return intResult;
      }
      public int DeleteBusiness_Detail(string CCID,string CDetailID)
      {
          int intResult = 0;
          string strSql = "Delete from  H_Business_Detail where CCID=@c1 AND CDetailID=@c2";
          OleDbParameter[] prams = {
                                             new OleDbParameter("@c1", CCID),
                                              new OleDbParameter("@c2", CDetailID)
                                         };
          intResult = AccessHelper.ExecuteNonQuery(strCon(), strSql, prams);
          return intResult;
      }

      /// <summary>
      /// 公司
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public bool InsertBusiness_Detail(H_Bus_DetailEntity hce)
      {
          bool result = true;
          try
          {
              string SqlStr = "  " +
                  " Insert into H_Business_Detail (CCID,CDetailID,CWidth,CHigh,CTS, CPFS,CDAdress, DoTime) " +
                  " values(@c1,@c2,round(@c3,2),round(@c4,2),@c5,@c6,@c7,@8) ";
              OleDbParameter[] prams = {
                                                     new OleDbParameter("@c1", hce.CCID),
                                                     new OleDbParameter("@c2", hce.CDetailID),
                                                       new OleDbParameter("@c3", hce.CWidth),
                                                     new OleDbParameter("@c4", hce.CHigh),
                                                      new OleDbParameter("@c5", hce.CTS),
                                                      new OleDbParameter("@c6", hce.CPFS),
                                                      new OleDbParameter("@c7", hce.CDAdress),
                                                       new OleDbParameter("@c8", DateTime.Now.ToString())   };

              int intresult = AccessHelper.ExecuteNonQuery(strCon(), SqlStr, prams);
              if (intresult == 0) result = false;
              else result = true;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "公司明细", ex.Message);
              result = false;
          }
          return result;

      }

      /// <summary>
      /// 明细主表
      /// </summary>
      /// <param name="ue"></param>
      /// <returns></returns>
      public bool InsertBusiness_Main(H_Bus_MainEntity hcm)
      {
          bool result = true;
          try
          {
              string SqlStr = "  " +
                  " Insert into H_Business_Main (CCID, ZTS, TotalSquare, Price, TotalPrice, DoTime) " +
                  " values(@c1,@c2,@c3,@c4,@c5,@c6) ";
              OleDbParameter[] prams = {
                                                     new OleDbParameter("@c1", hcm.CCID),
                                                     new OleDbParameter("@c2", hcm.ZTS),
                                                       new OleDbParameter("@c3", hcm.TotalSquare),
                                                     new OleDbParameter("@c4", hcm.Price),
                                                       new OleDbParameter("@c5", hcm.TotalPrice),
                                                       new OleDbParameter("@c6", DateTime.Now.ToString())   };

              int intresult = AccessHelper.ExecuteNonQuery(strCon(), SqlStr, prams);
              if (intresult == 0) result = false;
              else result = true;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "明细主表H_Business_Main", ex.Message);
              result = false;
          }
          return result;

      }

      public DataSet GetDSBusiness_Main(string CCID)
      {
          try
          {
              string SqlStr = "SELECT * FROM H_Business_Main ";
              if (CCID != "")
                  SqlStr += "  WHERE CCID='" + CCID + "'";

              DataSet ds = AccessHelper.ExecuteDataSet(strCon(), SqlStr, null);
              if (ds == null) return null;
              else return ds;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库操作", "Business_Main" + CCID, ex.Message);
              return null;
          }
      }
      public DataSet GetDSBusiness_Detail(string CCID,
          string[] detailid)
      {
          try
          {
              string di="";
              for (int i = 0; i < 6; i++)
              {
                  if (detailid[i] != "") di = di+",'" + detailid[i]+"'";
              }
              if (di.Length > 0) di = di.Substring(1);
              string SqlStr = "SELECT * FROM H_Business_Detail ";
              if (CCID != "")
                  SqlStr += "  WHERE CCID='" + CCID + "'";
              if(di.Length>0)
                  SqlStr += "  AND CDetailID NOT IN( " + di + ")";

              DataSet ds = AccessHelper.ExecuteDataSet(strCon(), SqlStr, null);
              if (ds == null) return null;
              else return ds;

          }
          catch (Exception ex)
          {
              log.wrirteLog("数据库查询操作", "Detail" + CCID, ex.Message);
              return null;
          }
      }

     #region 分页
        /// <summary>
        /// 分页使用
        /// </summary>
        /// <param name="query"></param>
        /// <param name="passCount"></param>
        /// <returns></returns>
        private static string recordID(string query, int passCount)
        {

            using (OleDbConnection m_Conn = new OleDbConnection(StrCon))
            {
                m_Conn.Open();
                OleDbCommand cmd = new OleDbCommand(query, m_Conn);
                string result = string.Empty;
                using (OleDbDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        if (passCount < 1)
                        {
                            result += "," +dr[0];
                                //dr.GetInt32(0);
                        }
                        passCount--;
                    }
                }
                m_Conn.Close();
                m_Conn.Dispose();
                return result.Substring(1);
            }
        }
        /// <summary>
        /// ACCESS高效分页
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">分页容量</param>
        /// <param name="strKey">主键</param>
        /// <param name="showString">显示的字段</param>
        /// <param name="queryString">查询字符串,支持联合查询</param>
        /// <param name="whereString">查询条件,若有条件限制则必须以where 开头</param>
        /// <param name="orderString">排序规则</param>
        /// <param name="pageCount">传出参数:总页数统计</param>
        /// <param name="recordCount">传出参数:总记录统计</param>
        /// <returns>装载记录的DataTable</returns>
        public  DataTable ExecutePager(int pageIndex, int pageSize, string strKey,string showString, string queryString, string whereString, string orderString, out int pageCount, out int recordCount)
        {

            if (pageIndex < 1) pageIndex = 1;
            if (pageSize < 1) pageSize = 10;
            if (string.IsNullOrEmpty(showString)) showString = "*";
            if (string.IsNullOrEmpty(orderString)) orderString = strKey+" asc ";
            using (OleDbConnection m_Conn = new OleDbConnection(StrCon))
            {
                m_Conn.Open();
                string myVw = string.Format(" ( {0} ) tempVw ", queryString);
                OleDbCommand cmdCount = new OleDbCommand(string.Format(" select count(*) as recordCount from {0} {1}", myVw, whereString), m_Conn);

                recordCount = Convert.ToInt32(cmdCount.ExecuteScalar());

                if ((recordCount % pageSize) > 0)
                    pageCount = recordCount / pageSize + 1;
                else
                    pageCount = recordCount / pageSize;
                OleDbCommand cmdRecord;
                if (pageIndex == 1)//第一页
                {
                    cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, whereString, orderString), m_Conn);
                }
                else if (pageIndex > pageCount)//超出总页数
                {
                    cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, "where 1=2", orderString), m_Conn);
                }
                else
                {
                    int pageLowerBound = pageSize * pageIndex;
                    int pageUpperBound = pageLowerBound - pageSize;
                    string recordIDs = recordID(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageLowerBound, strKey, myVw, whereString, orderString), pageUpperBound);
                    cmdRecord = new OleDbCommand(string.Format("select {0} from {1} where {2} in ({3}) order by {4} ", showString, myVw,strKey, recordIDs, orderString), m_Conn);

                }
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmdRecord);
                DataTable dt = new DataTable();
                dataAdapter.Fill(dt);
                m_Conn.Close();
                m_Conn.Dispose();
            return dt;
            }
        }
        #endregion

        //public bool InsertDfdjzkOrder(H_CompanyEntity hce, out string errmsg)
      //{
      //    bool result = true;
      //    errmsg = "";
      //    string strCon = strCon();
      //    OleDbConnection con = new OleDbConnection(strCon);
      //    try
      //    {
      //        con.Open();
      //        OleDbTransaction tra = con.BeginTransaction(); //创建事务,开始执行事务
      //        if (DeleteCompany(tra, hce) != 1)
      //        {
      //            tra.Rollback();
      //            return false;
      //        }
      //        DfdjhmDA daDfdjhm = new DfdjhmDA();
      //        if (daDfdjhm.UpdateDfdjhm(tra, etyDfdjhm) != 1)
      //        {
      //            tra.Rollback();
      //            return false;
      //        }

      //        tra.Commit();//关闭事务
      //    }
      //    catch (Exception ex)
      //    {
      //        errmsg = ex.Message;
      //        return false;
      //    }
      //    finally
      //    {
      //        con.Close();
      //    }

      //    return result;

      //}

      //public int InsertCby(CbyEntity objCbyEntity)
      //{
      //    int intResult = 0;
      //    string strSql = "insert into cby (dh,xm)  values (@dh,@xm)";
      //    OleDbParameter[] prams = {
      //                                       new OleDbParameter("@dh", objCbyEntity.Dh),
      //                                       new OleDbParameter("@xm", objCbyEntity.Xm)
      //                                   };
      //    intResult = AccessHelper.ExecuteNonQuery(AccessHelper.conn_str, strSql, prams);
      //    return intResult;
      //}

  }
}


text:
package com.google.android.exoplayer2.util;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.Nullable;

/**
 * An interface to call through to a {@link Handler}. Instances must be created by calling {@link
 * Clock#createHandler(Looper, Handler.Callback)} on {@link Clock#DEFAULT} for all non-test cases.
 */
public interface HandlerWrapper {

  /** @see Handler#getLooper() */
  Looper getLooper();

  /** @see Handler#obtainMessage(int) */
  Message obtainMessage(int what);

  /** @see Handler#obtainMessage(int, Object) */
  Message obtainMessage(int what, @Nullable Object obj);

  /** @see Handler#obtainMessage(int, int, int) */
  Message obtainMessage(int what, int arg1, int arg2);

  /** @see Handler#obtainMessage(int, int, int, Object) */
  Message obtainMessage(int what, int arg1, int arg2, @Nullable Object obj);

  /** @see Handler#sendEmptyMessage(int) */
  boolean sendEmptyMessage(int what);

  /** @see Handler#sendEmptyMessageAtTime(int, long) */
  boolean sendEmptyMessageAtTime(int what, long uptimeMs);

  /** @see Handler#removeMessages(int) */
  void removeMessages(int what);

  /** @see Handler#removeCallbacksAndMessages(Object) */
  void removeCallbacksAndMessages(@Nullable Object token);

  /** @see Handler#post(Runnable) */
  boolean post(Runnable runnable);

  /** @see Handler#postDelayed(Runnable, long) */
  boolean postDelayed(Runnable runnable, long delayMs);
}

redpajama_set_name: RedPajamaGithub


text:
import {AmpStoryComponentManager} from './amp-story-component-manager';
import {AmpStoryPlayer} from './amp-story-player-impl';
import {onDocumentReady} from '../document-ready';

onDocumentReady(self.document, () => {
  const manager = new AmpStoryComponentManager(self);
  manager.loadPlayers();
});

globalThis.AmpStoryPlayer = AmpStoryPlayer;


text:
@interface CBDateCell : CBCell

@property (nonatomic,retain) IBOutlet UITextField *dateField;
@property (nonatomic,retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic,assign) CGFloat engagedHeight;
@property (nonatomic,assign) CGFloat clearButtonHeight;
@property (nonatomic,retain) IBOutlet UIButton *clearButton;

@end


text:
import scrapy
from ..items import Ad
from ..utils import FIELDS

class Immoscout24(scrapy.Spider):
    name = "immoscout24"

    def get_clean_url(self, url):
        """Returns clean ad url for storing in database
        """
        return url.split('?')[0]

    def start_requests(self):
        # the l parameter describes the canton id
        for i in range(1, 27):
            yield scrapy.Request(url='http://www.immoscout24.ch/de/suche/wohnung-haus-kaufen?s=1&t=2&l={}&se=16&pn=1&ps=120'.format(i), callback=self.parse)

    def parse(self, response):
        """ Parse the ad list """

        # find ads
        ad_link_path = '//a[@class="item-title"]/@href'

        for link in response.xpath(ad_link_path).extract():
            next_ad = response.urljoin(link)
            yield scrapy.Request(next_ad, callback=self.parse_ad)

        # find next page
        next_page_link = '//a[contains(@class, "next") and not(contains(@class, "disabled"))]/@href'
        next_page_url = response.xpath(next_page_link).extract_first()

        if next_page_url:
            self.logger.debug("Found next page: {}".format(next_page_url))
            next_page = response.urljoin(next_page_url)
            yield scrapy.Request(next_page, callback=self.parse)

    def parse_ad(self, response):
        ad = Ad()
        ad['crawler'] = 'immoscout24'
        ad['url'] = response.url
        ad['raw_data'] = response.body.decode()
        ad['objecttype'] = response.url.split("/")[5].split("-")[0]
        ad['additional_data'] = {}

        # price, number of rooms, living area
        for div in response.xpath('//div[contains(@class, "layout--columns")]/div[@class="column" and ./div[@class="data-label"]]'):
            key, value, *_ = [x.strip()
                              for x in div.xpath('div//text()').extract()]

            try:
                key = FIELDS[key]
                ad[key] = value
            except KeyError:
                self.logger.warning("Key not found: {}".format(key))
                ad['additional_data'][key] = value

        # location
        loc = response.xpath('//table//div[contains(@class, "adr")]')
        ad['street'] = loc.xpath('div[contains(@class, "street-address")]/text()').extract_first()
        ad['place'] = "{} {}".format(loc.xpath('span[contains(@class, "postal-code")]/text()').extract_first().strip(),
                                     loc.xpath('span[contains(@class, "locality")]/text()').extract_first())

        # description
        ad['description'] = ' '.join(response.xpath(
            '//div[contains(@class, "description")]//text()').extract()).strip()

        # more attributes
        ad['characteristics'] = {}

        for elm in response.xpath('//div[contains(@class, "description")]/following-sibling::h2[@class="title-secondary"]'):
            for entry in elm.xpath('./following-sibling::table[1]//tr'):
                key, value = entry.xpath('td')
                key = key.xpath('text()').extract_first()
                if len(value.xpath('span[contains(@class, "tick")]')) == 1:
                    # checkmark
                    value = True
                else:
                    # text
                    value = value.xpath('text()').extract_first()

                # write to additional data, or to structured field
                try:
                    key = FIELDS[key]
                    ad[key] = value
                except KeyError:
                    ad['characteristics'][key] = value

        yield ad


text:
package testutils

import (
	boshsys "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-utils/system"
)

func GenerateDeploymentManifest(deploymentManifestFilePath string, fs boshsys.FileSystem, manifestContents string) error {
	return fs.WriteFileString(deploymentManifestFilePath, manifestContents)
}


text:
//  Based on the three.js Curve classes created by [zz85](http://www.lab4games.net/zz85/blog)

var Class = require('../utils/Class');
var Curve = require('./Curve');
var FromPoints = require('../geom/rectangle/FromPoints');
var Rectangle = require('../geom/rectangle/Rectangle');
var Vector2 = require('../math/Vector2');

var tmpVec2 = new Vector2();

/**
 * @classdesc
 * [description]
 *
 * @class Line
 * @extends Phaser.Curves.Curve
 * @memberOf Phaser.Curves
 * @constructor
 * @since 3.0.0
 *
 * @param {(Phaser.Math.Vector2|number[])} p0 - [description]
 * @param {Phaser.Math.Vector2} [p1] - [description]
 */
var LineCurve = new Class({

    Extends: Curve,

    initialize:

    //  vec2s or array
    function LineCurve (p0, p1)
    {
        Curve.call(this, 'LineCurve');

        if (Array.isArray(p0))
        {
            p1 = new Vector2(p0[2], p0[3]);
            p0 = new Vector2(p0[0], p0[1]);
        }

        /**
         * [description]
         *
         * @name Phaser.Curves.Line#p0
         * @type {Phaser.Math.Vector2}
         * @since 3.0.0
         */
        this.p0 = p0;

        /**
         * [description]
         *
         * @name Phaser.Curves.Line#p1
         * @type {Phaser.Math.Vector2}
         * @since 3.0.0
         */
        this.p1 = p1;
    },

    /**
     * Returns a Rectangle where the position and dimensions match the bounds of this Curve.
     *
     * @method Phaser.Curves.Line#getBounds
     * @since 3.0.0
     *
     * @generic {Phaser.Geom.Rectangle} O - [out,$return]
     *
     * @param {Phaser.Geom.Rectangle} [out] - A Rectangle object to store the bounds in. If not given a new Rectangle will be created.
     *
     * @return {Phaser.Geom.Rectangle} A Rectangle object holding the bounds of this curve. If `out` was given it will be this object.
     */
    getBounds: function (out)
    {
        if (out === undefined) { out = new Rectangle(); }

        return FromPoints([ this.p0, this.p1 ], out);
    },

    /**
     * Gets the starting point on the curve.
     *
     * @method Phaser.Curves.Line#getStartPoint
     * @since 3.0.0
     *
     * @generic {Phaser.Math.Vector2} O - [out,$return]
     *
     * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created.
     *
     * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned.
     */
    getStartPoint: function (out)
    {
        if (out === undefined) { out = new Vector2(); }

        return out.copy(this.p0);
    },

    /**
     * [description]
     *
     * @method Phaser.Curves.Line#getResolution
     * @since 3.0.0
     *
     * @param {number} [divisions=1] - [description]
     *
     * @return {number} [description]
     */
    getResolution: function (divisions)
    {
        if (divisions === undefined) { divisions = 1; }

        return divisions;
    },

    /**
     * Get point at relative position in curve according to length.
     *
     * @method Phaser.Curves.Line#getPoint
     * @since 3.0.0
     *
     * @generic {Phaser.Math.Vector2} O - [out,$return]
     *
     * @param {float} t - The position along the curve to return. Where 0 is the start and 1 is the end.
     * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created.
     *
     * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned.
     */
    getPoint: function (t, out)
    {
        if (out === undefined) { out = new Vector2(); }

        if (t === 1)
        {
            return out.copy(this.p1);
        }

        out.copy(this.p1).subtract(this.p0).scale(t).add(this.p0);

        return out;
    },

    // Line curve is linear, so we can overwrite default getPointAt

    /**
     * [description]
     *
     * @method Phaser.Curves.Line#getPointAt
     * @since 3.0.0
     *
     * @generic {Phaser.Math.Vector2} O - [out,$return]
     *
     * @param {float} u - The position along the curve to return. Where 0 is the start and 1 is the end.
     * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the result in. If not given will be created.
     *
     * @return {Phaser.Math.Vector2} The coordinates of the point on the curve. If an `out` object was given this will be returned.
     */
    getPointAt: function (u, out)
    {
        return this.getPoint(u, out);
    },

    /**
     * [description]
     *
     * @method Phaser.Curves.Line#getTangent
     * @since 3.0.0
     *
     * @generic {Phaser.Math.Vector2} O - [out,$return]
     *
     * @return {Phaser.Math.Vector2} [description]
     */
    getTangent: function ()
    {
        var tangent = tmpVec2.copy(this.p1).subtract(this.p0);

        return tangent.normalize();
    },

    //  Override default Curve.draw because this is better than calling getPoints on a line!

    /**
     * Draws this curve on the given Graphics object.
     *
     * The curve is drawn using `Graphics.lineBetween` so will be drawn at whatever the present Graphics line color is.
     * The Graphics object is not cleared before the draw, so the curve will appear on-top of anything else already rendered to it.
     *
     * @method Phaser.Curves.Line#draw
     * @since 3.0.0
     *
     * @generic {Phaser.GameObjects.Graphics} G - [graphics,$return]
     *
     * @param {Phaser.GameObjects.Graphics} graphics - The Graphics instance onto which this curve will be drawn.
     *
     * @return {Phaser.GameObjects.Graphics} The Graphics object to which the curve was drawn.
     */
    draw: function (graphics)
    {
        graphics.lineBetween(this.p0.x, this.p0.y, this.p1.x, this.p1.y);

        //  So you can chain graphics calls
        return graphics;
    },

    /**
     * [description]
     *
     * @method Phaser.Curves.Line#toJSON
     * @since 3.0.0
     *
     * @return {JSONCurve} The JSON object containing this curve data.
     */
    toJSON: function ()
    {
        return {
            type: this.type,
            points: [
                this.p0.x, this.p0.y,
                this.p1.x, this.p1.y
            ]
        };
    }

});

/**
 * [description]
 *
 * @function Phaser.Curves.Line.fromJSON
 * @since 3.0.0
 *
 * @param {JSONCurve} data - The JSON object containing this curve data.
 *
 * @return {Phaser.Curves.Line} [description]
 */
LineCurve.fromJSON = function (data)
{
    var points = data.points;

    var p0 = new Vector2(points[0], points[1]);
    var p1 = new Vector2(points[2], points[3]);

    return new LineCurve(p0, p1);
};

module.exports = LineCurve;


text:
cask 'webstorm' do
  version '2017.2.3,172.3968.27'
  sha256 '518b74cf872e5fd51e0cba94b17d490faad23ef6a58160feea6f4be39bc4aa96'

  url "https://download.jetbrains.com/webstorm/WebStorm-#{version.before_comma}.dmg"
  appcast 'https://data.services.jetbrains.com/products/releases?code=WS&latest=true&type=release',
          checkpoint: '907ba10b8138d1695638ae904e960714fbe445ec5ff6d3ba92a9ca0d44677fff'
  name 'WebStorm'
  homepage 'https://www.jetbrains.com/webstorm/'

  auto_updates true

  app 'WebStorm.app'

  uninstall_postflight do
    ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'wstorm') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
  end

  zap delete: [
                "~/Library/Caches/WebStorm#{version.major_minor}",
                "~/Library/Logs/WebStorm#{version.major_minor}",
                '~/Library/Saved Application State/com.jetbrains.WebStorm.savedState',
              ],
      trash:  [
                "~/Library/Application Support/WebStorm#{version.major_minor}",
                "~/Library/Preferences/WebStorm#{version.major_minor}",
                '~/Library/Preferences/jetbrains.webstorm.aaac0500.plist',
              ]
end


text:
#pragma once
#include <QtCore/QHash>
#include <vector>
#include <qobjectdefs.h>

namespace SEGS_Enums
{
enum class SeqBitNames : uint32_t;
}
using namespace SEGS_Enums;

namespace SEGS_Enums_Power
{
Q_NAMESPACE

enum class StoredPower_Type
{
    Click       = 0,
    Auto        = 1,
    Toggle      = 2,
    Boost       = 3,
    Inspiration = 4,
};

enum class StoredEntEnum : uint32_t
{
    None                = 0,
    Caster              = 1,
    Player              = 2,
    DeadPlayer          = 3,
    Teammate            = 4,
    Enemy               = 5,
    DeadVillain         = 6,
    NPC                 = 7,
    Friend              = 8,
    Foe                 = 9,
    Location            = 10,
    Any                 = 11,
    DeadTeammate        = 12,
    DeadOrAliveTeammate = 13,
    Teleport            = 14,
};

enum StoredVisibility : uint32_t
{
    LineOfSight    = 0,
    VisibilityNone = 1,
};

enum class StoredAffectArea : uint32_t
{
    Character = 0,
    Cone      = 1,
    Sphere    = 2,
    Location  = 3,
};

enum class StoredAiReport : uint32_t
{
    Always   = 0,
    Never    = 1,
    HitsOnly = 2,
    MissOnly = 3,
};

enum DurationEnum : int32_t
{
    kInstant     = -1,
    kUntilKilled = 999999, // Until Shut Off
};

enum class AttribStackType
{
    Stack   = 0,
    Ignore  = 1,
    Extend  = 2,
    Replace = 3
};

enum class AttribModType : uint32_t
{
    Duration  = 0,
    Magnitude = 1,
    Constant  = 2,
};

enum class AttribModTarget : uint32_t
{
    Self   = 0,
    Target = 1,
};

enum class AttribMod_Aspect : uint32_t
{
    Current         = 0,
    Maximum         = 4,
    Strength        = 8,
    Resistance      = 0xC,
    Absolute        = 0x10,
    CurrentAbsolute = 0x10,
};

enum class PowerType : uint32_t
{
    Click       = 0,
    Auto        = 1,
    Toggle      = 2,
    Boost       = 3,
    Inspiration = 4,
    NumTypes    = 5,
};

// I'm unsure as to the validity of this
enum class AttackType : uint32_t {
    None = 0,
    Claw = 1,
    Kunfu = 2,
    Gun = 3,
    Blade = 4,
    Blunt = 5,
    Handgun = 6,
    Combat = 7,
    Weapon = 8,
    Speed = 9,
    Teleport = 10,
    Carry = 11,
    Club = 12,
    Ranged = 108,
    Melee = 112,
    Aoe = 116,
    Smashing = 120,
    Lethal = 124,
    Fire = 128,
    Cold = 132,
    Energy = 136,
    Negative_Energy = 140
};
Q_ENUM_NS(AttackType)

} // end of SEGS_Enums_Power namespace
using namespace SEGS_Enums_Power;

struct StoredAttribMod
{
    // Older combinations of Qt/moc/CMake require Q_GADGET macro and granting public access
    // to members. Otherwise, moc files are not generated properly under certain conditions.
    Q_GADGET
public:
    QByteArray         name             = "unknown";
    int                index_in_power;
    QByteArray         DisplayAttackerHit = "";
    QByteArray         DisplayVictimHit = "";
    struct Power_Data *parent_StoredPower;
    AttribModTarget    Target           = AttribModTarget::Target;
    QByteArray         Table            = "43"; //would be easier as int, since the tables are stored in an array
    float              Scale            = 1.0;
    int                Attrib           = 0; //
    AttribMod_Aspect   Aspect;
    AttribModType      Type             = AttribModType::Magnitude;
    float              Duration         = 0.0; // Special values in DurationEnum
    float              Magnitude        = 1.0;
    int                Delay            = 0;    //should be float, for now I'm just dividing by 1000
    int                Period           = 0;    //same
    int                Chance           = 100;  // are we sure this isn't a float?
    int                CancelOnMiss;            // bool?
    int                NearGround;              // bool?
    int                AllowStrength;           // bool?
    int                AllowResistance;         // bool?
    AttribStackType    StackType     = AttribStackType::Replace;
    std::vector<int>   ContinuingBits;
    QByteArray         ContinuingFX;
    std::vector<int>   ConditionalBits; // 5c
    QByteArray         ConditionalFX;
    QByteArray         EntityDef;
    QByteArray         PriorityListOffense;
    QByteArray         PriorityListDefense;
    QByteArray         PriorityListPassive;
};

struct Power_Data
{
    QByteArray                   m_Name;
    int                          ptr_powerset_available;
    struct Parse_PowerSet *      parent_StoredPowerSet;
    int                          category_idx;
    int                          powerset_idx;
    int                          power_index;
    QByteArray                   DisplayName;
    QByteArray                   DisplayHelp;
    QByteArray                   DisplayShortHelp;
    QByteArray                   DisplayAttackerAttack;
    QByteArray                   DisplayAttackerHit;
    QByteArray                   DisplayVictimHit;
    QByteArray                   IconName;
    std::vector<SeqBitNames>     ModeSeqBits;
    std::vector<SeqBitNames>     ActivationBits;
    std::vector<SeqBitNames>     WindUpBits; // 3c
    std::vector<SeqBitNames>     InitialAttackBits;
    std::vector<SeqBitNames>     AttackBits;
    std::vector<SeqBitNames>     HitBits;
    std::vector<SeqBitNames>     BlockBits;
    std::vector<SeqBitNames>     DeathBits;
    QByteArray                   ActivationFX;
    QByteArray                   WindUpFX;
    QByteArray                   InitialAttackFX;
    QByteArray                   AttackFX;
    QByteArray                   BlockFX;
    QByteArray                   HitFX;
    QByteArray                   DeathFX;
    int                          m_InitialFramesBeforeHit;
    int                          m_FramesBeforeHit;
    int                          m_AttackFrames;
    int                          DelayedHit;
    int                          ProjectileSpeed;
    PowerType                    Type;
    std::vector<AttackType>      AttackTypes;
    std::vector<QByteArray>      Requires;
    float                        Accuracy;
    int                          IgnoreStrength;
    int                          NearGround;
    int                          TargetNearGround;
    int                          CastableAfterDeath;
    int                          AIReport;
    StoredAffectArea             EffectArea;
    float                        Radius;
    float                        Arc;
    float                        Range;
    float                        RangeSecondary;
    float                        InitialFramesBeforeHit_seconds;
    float                        FramesBeforeHit_seconds;
    float                        TimeToActivate;
    float                        RechargeTime;
    float                        InterruptTime;
    float                        ActivatePeriod;
    float                        EnduranceCost;
    int                          DestroyOnLimit;
    int                          limited_use;
    int                          m_NumCharges;
    float                        m_UsageTime;
    int                          has_lifetime;
    float                        m_Lifetime;
    StoredVisibility             TargetVisibility;
    StoredEntEnum                Target;
    StoredEntEnum                TargetSecondary;
    std::vector<StoredEntEnum>   EntsAffected;
    std::vector<StoredEntEnum>   EntsAutoHit;
    std::vector<uint32_t>        BoostsAllowed;
    std::vector<uint32_t>        GroupMembership;
    std::vector<QByteArray>      AIGroups;
    std::vector<StoredAttribMod> pAttribMod;
    int                          fDamageGiven;
    int                          iCntUsed;
    int                          iCntHits;
    int                          iCntMisses;
};

struct Parse_PowerSet
{
    QByteArray                   m_Name;
    struct StoredPowerCategory * parent_PowerCategory;
    QByteArray                   DisplayName;
    QByteArray                   DisplayHelp;
    QByteArray                   DisplayShortHelp;
    QByteArray                   IconName;
    std::vector<Power_Data>      m_Powers;
    QHash<QString, Power_Data *> m_hash_table;
    std::vector<int32_t>         Available;
};

enum
{
    kCategory_Count = 3
};

struct StoredPowerCategory
{
    QByteArray                       name;
    QByteArray                       disp_name;
    QByteArray                       disp_help;
    QByteArray                       disp_short_help;
    std::vector<Parse_PowerSet>      m_PowerSets;
    QHash<QString, Parse_PowerSet *> m_powers_hash;
};

struct AllPowerCategories
{
    std::vector<StoredPowerCategory>      m_categories;
    QHash<QString, StoredPowerCategory *> categories_hash;
};


text:
package org.apache.commons.collections15;

/**
 * @param <T> Type of created entity
 * @author Lyor G.
 */
public interface ExtendedFactory<T> extends Factory<T> {
    Class<T> getInstanceType();
}


text:
<?php

namespace common\extensions\phppdo\drivers;
class phppdo_mssql extends phppdo_base
{
    private $autocommit;

    public function __construct(&$dsn, &$username, &$password, &$driver_options)
    {
        if(!extension_loaded('mssql'))
        {
            throw new PDOException('could not find extension');
        }

        parent::__construct($dsn, $username, $password, $driver_options);
        $this->driver_quote_type = 1;
    }

    public function beginTransaction()
    {
        parent::beginTransaction();

        if(!mssql_query('BEGIN TRANSACTION', $this->link))
        {
            $this->set_driver_error(null, PDO::ERRMODE_EXCEPTION, 'beginTransaction');
        }

        return true;
    }

    public function commit()
    {
        parent::commit();

        if(!mssql_query('COMMIT', $this->link))
        {
            $this->set_driver_error(null, PDO::ERRMODE_EXCEPTION, 'commit');
        }

        $this->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
        return true;
    }

    public function exec(&$statement)
    {
        if($result = @mssql_query($statement, $this->link))
        {
            if(is_resource($result))
            {
                mssql_free_result($result);
                return 0;
            }

            return mssql_rows_affected($this->link);
        }

        return false;
    }

    public function getAttribute($attribute, &$source = null, $func = 'PDO::getAttribute', &$last_error = null)
    {
        switch($attribute)
        {
            case PDO::ATTR_AUTOCOMMIT:
                return $this->autocommit;
            break;

            case PDO::ATTR_TIMEOUT:
                return intval(ini_get('mssql.connect_timeout'));
            break;

            default:
                return parent::getAttribute($attribute, $source, $func, $last_error);
            break;
        }

        return false;
    }

    public function lastInsertId($name = '')
    {
        $sql = $name ? 'SELECT IDENT_CURRENT('.$this->quote($name).')' : 'SELECT @@IDENTITY';
        if($result = mssql_query($sql, $this->link))
        {
            $row = mssql_fetch_row($result);
            if($row[0] === null) return -1;
            return $row[0];
        }

        return false;
    }

    public function quote(&$param, $parameter_type = -1)
    {
        switch($parameter_type)
        {
            case PDO::PARAM_BOOL:
                return $param ? 1 : 0;
            break;

            case PDO::PARAM_NULL:
                return 'NULL';
            break;

            case PDO::PARAM_INT:
                return is_null($param) ? 'NULL' : (is_int($param) ? $param : (float)$param);
            break;

            default:
                return '\'' . str_replace('\'', '\'\'', $param) . '\'';
            break;
        }
    }

    public function rollBack()
    {
        parent::rollback();

        if(!mssql_query('ROLLBACK', $this->link))
        {
            $this->set_driver_error(null, PDO::ERRMODE_EXCEPTION, 'rollBack');
        }

        $this->setAttribute(PDO::ATTR_AUTOCOMMIT, $this->driver_options[PDO::ATTR_AUTOCOMMIT]);
        return true;
    }

    public function setAttribute($attribute, $value, &$source = null, $func = 'PDO::setAttribute', &$last_error = null)
    {
        if($source == null) $source =& $this->driver_options;

        switch($attribute)
        {
            case PDO::ATTR_AUTOCOMMIT:
                $this->autocommit = $value ? 1 : 0;
                return true;
            break;

            case PDO::ATTR_TIMEOUT:
                $value = intval($value);
                if($value > 1 && @ini_set('mssql.connect_timeout', $value))
                {
                    return true;
                }
            break;

            default:
                return parent::setAttribute($attribute, $value, $source, $func, $last_error);
            break;
        }

        return false;
    }

    public function set_driver_error($state = null, $mode = PDO::ERRMODE_SILENT, $func = '')
    {
        if($state === null) $state = 'HY000';
        $this->set_error(-1, mssql_get_last_message(), $state, $mode, $func);
    }

    protected function connect(&$username, &$password, &$driver_options)
    {
        $this->set_attributes(array
        (
            PDO::ATTR_TIMEOUT,
        ), $driver_options);

        $host       = isset($this->dsn['host'])         ? $this->dsn['host']                : 'localhost';
        $dbname     = isset($this->dsn['dbname'])       ? $this->dsn['dbname']              : '';
        $port       = isset($this->dsn['port'])         ? intval($this->dsn['port'])        : 0;

        if($port)
        {
            $host .= ',' . $port;
        }

        if(isset($driver_options[PDO::ATTR_PERSISTENT]) && $driver_options[PDO::ATTR_PERSISTENT])
        {
            $this->link = @mssql_pconnect($host, $username, $password);
        }
        else
        {
            $this->link = @mssql_connect($host, $username, $password, true);
        }

        if(!$this->link)
        {
            $this->set_driver_error('28000', PDO::ERRMODE_EXCEPTION, '__construct');
        }

        if($dbname)
        {
            if(!@mssql_select_db($dbname, $this->link))
            {
                $this->set_driver_error(null, PDO::ERRMODE_EXCEPTION, '__construct');
            }
        }
    }

    protected function disconnect()
    {
        mssql_close($this->link);
    }
}
?>


text:
package com.google.cloud.dataflow.sdk.transforms.windowing;

import com.google.cloud.dataflow.sdk.annotations.Experimental;
import com.google.cloud.dataflow.sdk.coders.InstantCoder;
import com.google.cloud.dataflow.sdk.transforms.Min;
import com.google.cloud.dataflow.sdk.transforms.SerializableFunction;
import com.google.cloud.dataflow.sdk.transforms.windowing.Trigger.OnceTrigger;
import com.google.cloud.dataflow.sdk.util.state.CombiningValueState;
import com.google.cloud.dataflow.sdk.util.state.StateTag;
import com.google.cloud.dataflow.sdk.util.state.StateTags;
import com.google.common.collect.ImmutableList;

import org.joda.time.Duration;
import org.joda.time.Instant;

import java.util.List;

/**
 * Support for manipulating the time at which time-based {@link Trigger}s fire.
 *
 * @param <W> {@link BoundedWindow} subclass used to represent the windows used.
 * @param <T> {@code TimeTrigger} subclass produced by modifying the current {@code TimeTrigger}.
 *     Typically, this is the self type.
 */
@Experimental(Experimental.Kind.TRIGGER)
public abstract class TimeTrigger<W extends BoundedWindow, T extends TimeTrigger<W, T>>
    extends OnceTrigger<W> {

  protected static final StateTag<CombiningValueState<Instant, Instant>> DELAYED_UNTIL_TAG =
      StateTags.makeSystemTagInternal(StateTags.combiningValue(
          "delayed", InstantCoder.of(), Min.MinFn.<Instant>naturalOrder()));

  private static final long serialVersionUID = 0L;

  protected static final List<SerializableFunction<Instant, Instant>> IDENTITY;
  static {
    IDENTITY = ImmutableList.<SerializableFunction<Instant, Instant>>of();
  }

  /**
   * A list of timestampMappers m1, m2, m3, ... m_n considered to be composed in sequence. The
   * overall mapping for an instance `instance` is `m_n(... m3(m2(m1(instant))`,
   * implemented via #computeTargetTimestamp
   */
  protected final List<SerializableFunction<Instant, Instant>> timestampMappers;

  protected TimeTrigger(
      List<SerializableFunction<Instant, Instant>> timestampMappers) {
    super(null);
    this.timestampMappers = timestampMappers;
  }

  protected Instant computeTargetTimestamp(Instant time) {
    Instant result = time;
    for (SerializableFunction<Instant, Instant> timestampMapper : timestampMappers) {
      result = timestampMapper.apply(result);
    }
    return result;
  }

  /**
   * Adds some delay to the original target time.
   *
   * @param delay the delay to add
   * @return An updated time trigger that will wait the additional time before firing.
   */
  public T plusDelayOf(final Duration delay) {
    return newWith(delayFn(delay));
  }

  private static SerializableFunction<Instant, Instant> delayFn(final Duration delay) {
    return new SerializableFunction<Instant, Instant>() {
      private static final long serialVersionUID = 0L;

      @Override
      public Instant apply(Instant input) {
        return input.plus(delay);
      }
    };
  }

  /**
   * Aligns timestamps to the smallest multiple of {@code size} since the {@code offset} greater
   * than the timestamp.
   *
   *
 TODO: Consider sharing this with FixedWindows, and bring over the equivalent of
   * CalendarWindows.
   */
  public T alignedTo(final Duration size, final Instant offset) {
    return newWith(alignFn(size, offset));
  }

  private static SerializableFunction<Instant, Instant> alignFn(
      final Duration size, final Instant offset) {
    return new SerializableFunction<Instant, Instant>() {
      private static final long serialVersionUID = 0L;

      @Override
      public Instant apply(Instant point) {
        long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis();
        return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart);
      }
    };
  }

  /**
   * Aligns the time to be the smallest multiple of {@code size} greater than the timestamp
   * since the epoch.
   */
  public T alignedTo(final Duration size) {
    return alignedTo(size, new Instant(0));
  }

  /**
   * Adjust the time at which the trigger will fire.
   *
   *
The {@code timestampMapper} function must have the following properties for all values
   * {@code a} and {@code b}:
   *
   *

   *
 Deterministic: If {@code a = b} then {@code timestampMapper(a) = timestampMapper(b)}
   *
 Monotonicity: If {@code a < b} then {@code timestampMapper(a) <= timestampMapper(b)}
   *

   *
   * @param timestampMapper Function that will be invoked on the proposed trigger time to determine
   *        the time at which the trigger should actually fire.
   */
  public T mappedTo(SerializableFunction<Instant, Instant> timestampMapper) {
    return newWith(timestampMapper);
  }

  @Override
  public boolean isCompatible(Trigger<?> other) {
    if (!getClass().equals(other.getClass())) {
      return false;
    }

    TimeTrigger<?, ?> that = (TimeTrigger<?, ?>) other;
    return this.timestampMappers.equals(that.timestampMappers);
  }

  private T newWith(SerializableFunction<Instant, Instant> timestampMapper) {
    return newWith(ImmutableList.<SerializableFunction<Instant, Instant>>builder()
        .addAll(timestampMappers)
        .add(timestampMapper)
        .build());
  }

  /**
   * Method to create an updated version of this {@code TimeTrigger} modified to use the specified
   * {@code transform}.
   *
   * @param transform The new transform to apply to target times.
   * @return a new {@code TimeTrigger}.
   */
  protected abstract T newWith(List<SerializableFunction<Instant, Instant>> transform);
}


text:
<?php
session_start();
if(isset($_SESSION['id'])){
	if($_SESSION['level']>1){
		die ("not admin");
	}
	else{
		//only continue if admin
	}

}
else{
	die ("not logged in");
}
$userId = $_GET['user'];
include_once '../sys/dbconnect.php';
$res=$dbh->prepare("SELECT * FROM `pending_users` WHERE id=".$userId);
$res->execute();
$row=$res->fetch(PDO::FETCH_ASSOC);
if($res->rowCount()==1){
	$userName = $row['user_name'];
	$fullName = $row['full_name'];
	$email = $row['email'];
	$passToken = $row['pass_token'];

	try{
		$sth = $dbh->prepare ("INSERT INTO `projectdatabase`.`users` (`user_name`, `full_name`, `email`, `pass_token`, `level`) VALUES ('$userName', '$fullName', '$email', '$passToken', '2')");
		$sth->execute();
	}
	catch (PDOException $e){
		echo "Error accessing database";
		echo ("getMessage(): " . $e->getMessage () . "\n");
	}
	if($sth->rowCount()==1){
		echo "Confirmed!";
	}

	$trans = $dbh->prepare("DELETE FROM `projectdatabase`.`pending_users` WHERE `pending_users`.`id` =".$userId);
	$trans->execute();
	if($trans->rowCount()==1){
		echo "done!";
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface com.wiris.plugin.configuration.ConfigurationUpdater (WIRIS plugin API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
com.wiris.plugin.configuration.ConfigurationUpdater

Packages that use ConfigurationUpdater

com.wiris.plugin.configuration

Uses of ConfigurationUpdater in com.wiris.plugin.configuration

Subinterfaces of ConfigurationUpdater in com.wiris.plugin.configuration

 interface
ConfigurationUpdater2

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
normalize-license
=================

Attempts to normalize all the different ways people put license information in their package.json files.

usage
-----

```javascript

var format = require('normalize-license');

var license = format(json);
```

There is also a "guessing" feature:

`format(json, true);`

This will attempt to look into the `json.readme` property to "Guess" the license.

build
-----

[![Build Status](https://travis-ci.org/yahoo/normalize-license.png?branch=master)](https://travis-ci.org/yahoo/normalize-license)


text:
{template 'common/header-base'}

					{IMS_VERSION}

				<form action="" method="post" role="form" id="form1" onsubmit="return formcheck();">

						<input name="username" type="text" class="form-control" placeholder="请输入用户名登录">

						<input name="password" type="password" class="form-control " placeholder="请输入登录密码">

					{if !empty($_W['setting']['copyright']['verifycode'])}

						<input name="verify" type="text" class="form-control" placeholder="请输入验证码">

					{/if}

						<input type="checkbox" value="true" id="rember" name="rember">
						记住用户名

						<input type="submit" id="submit" name="submit" value="登录" class="btn btn-primary" />
						{if !$_W['siteclose'] && $setting['register']['open']}
						注册
						{/if}
						<input name="token" value="{$_W['token']}" type="hidden" />

				</form>

{template 'common/footer-base'}


text:
Curso sobre desenvolvimento WEB ministrado na XIV SECOMPP (Semana da Computação da UNESP Presidente Prudente)

## 1. Arquitetura web
  Estrutura, hardware, serviços, protocolos, e requisições
### 1.1 Endereços
  IP, DNS e as URLs
### 1.2 Software
  Navegadores, servidor e linguagens
### 1.3 Arquitetura Cliente-Servidor
#### 1.3.1 Estrutura do cliente
  Codificador/decodificador http, rederizador html/css e interpretador javascript
#### 1.3.2 Estrutura do servidor
  Servidor web apache, IIS ou PWS, codificador/decodificador http, processador de requisições e ambiente de execução de linguagens
## 2. Estrutura e visão geral de uma aplicação
  html, css, javascript
## 3. HTML
  DOM e renderização, protocolo, estrutura, elementos, tags, atributos
## 4. CSS
### 4.1 O que é CSS
### 4.2 Porquê usar CSS
### 4.3 Sintaxe
### 4.4 Comentários
### 4.5 Seletores
### 4.6 Propriedades
### 4.7 Background
### 4.8 Text
### 4.9 Font
### 4.10 Link
### 4.11 List
### 4.12 Table
### 4.13 Box
### 4.14 Border
### 4.15 Padding
### 4.16 Dimensions
### 4.17 Display
### 4.18 Position
### 4.19 Float
### 4.20 Pseudoelements
### 4.21 Images
## 5. JS
  Manipulação de DOM, seletores, eventos
## 6. Desenvolvendo uma aplicação "Hello World"
## 7. Desenvolvendo uma Aplicação com os conceitos ensinados


text:
goog.provide('goog.net.jsloaderTest');
goog.setTestOnly('goog.net.jsloaderTest');

goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.net.jsloader');
goog.require('goog.net.jsloader.ErrorCode');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.jsunit');

// Initialize the AsyncTestCase.
var testCase = goog.testing.AsyncTestCase.createAndInstall(document.title);
testCase.stepTimeout = 5 * 1000; // 5 seconds

testCase.setUp = function() {
  goog.provide = goog.nullFunction;
};

testCase.tearDown = function() {
  // Remove all the fake scripts.
  var scripts = goog.array.clone(
      document.getElementsByTagName(goog.dom.TagName.SCRIPT));
  for (var i = 0; i < scripts.length; i++) {
    if (scripts[i].src.indexOf('testdata') != -1) {
      goog.dom.removeNode(scripts[i]);
    }
  }
};

// Sunny day scenario for load function.
function testLoad() {
  testCase.waitForAsync('testLoad');

  window.test1 = null;
  var testUrl = 'testdata/jsloader_test1.js';
  var result = goog.net.jsloader.load(testUrl);
  result.addCallback(function() {
    testCase.continueTesting();

    var script = result.defaultScope_.script_;

    assertNotNull('script created', script);
    assertEquals('encoding is utf-8', 'UTF-8', script.charset);

    // Check that the URI matches ours.
    assertTrue('server URI', script.src.indexOf(testUrl) >= 0);

    // Check that the script was really loaded.
    assertEquals('verification object', 'Test #1 loaded', window.test1);
  });
}

// Sunny day scenario for loadAndVerify function.
function testLoadAndVerify() {
  testCase.waitForAsync('testLoadAndVerify');

  var testUrl = 'testdata/jsloader_test2.js';
  var result = goog.net.jsloader.loadAndVerify(testUrl, 'test2');
  result.addCallback(function(verifyObj) {
    testCase.continueTesting();

    // Check that the verification object has passed ok.
    assertEquals('verification object', 'Test #2 loaded', verifyObj);
  });
}

// What happens when the verification object is not set by the loaded script?
function testLoadAndVerifyError() {
  testCase.waitForAsync('testLoadAndVerifyError');

  var testUrl = 'testdata/jsloader_test2.js';
  var result = goog.net.jsloader.loadAndVerify(testUrl, 'fake');
  result.addErrback(function(error) {
    testCase.continueTesting();

    // Check that the error code is right.
    assertEquals('verification error', goog.net.jsloader.ErrorCode.VERIFY_ERROR,
        error.code);
  });
}

// Tests that callers can cancel the deferred without error.
function testLoadAndVerifyCancelled() {
  var testUrl = 'testdata/jsloader_test2.js';
  var result = goog.net.jsloader.loadAndVerify(testUrl, 'test2');
  result.cancel();
}

// Test the loadMany function.
function testLoadMany() {
  testCase.waitForAsync('testLoadMany');

  // Load test #3 and then #1.
  window.test1 = null;
  window.test4 = null;
  var testUrls1 = ['testdata/jsloader_test3.js', 'testdata/jsloader_test1.js'];
  var result = goog.net.jsloader.loadMany(testUrls1);

  window.test3Callback = function(msg) {
    testCase.continueTesting();

    // Check that the 1st test was not loaded yet.
    assertEquals('verification object', null, window.test1);

    // check that result has not fired yet
    assertFalse('deferred has fired', result.hasFired());

    // Load test #4, which is supposed to wait for #1 to load.
    testCase.waitForAsync('testLoadMany');
    var testUrls2 = ['testdata/jsloader_test4.js'];
    goog.net.jsloader.loadMany(testUrls2);
  };

  window.test4Callback = function(msg) {
    testCase.continueTesting();

    // Check that the 1st test was already loaded.
    assertEquals('verification object', 'Test #1 loaded', window.test1);

    // all scripts loaded - verify that result has fired
    assertTrue('deferred has fired', result.hasFired());

    // on last script loaded, set variable
    window.test4 = msg;

    testCase.waitForAsync('testLoadMany');
  };

  result.addCallback(function() {
    testCase.continueTesting();

    // verify that the last loaded script callback has executed
    assertEquals('verification object', 'Test #4 loaded', window.test4);
  });
}

// Test the load function with additional options.
function testLoadWithOptions() {
  testCase.waitForAsync('testLoadWithOptions');

  var testUrl = 'testdata/jsloader_test1.js';
  var options = {
    attributes: {
      'data-attr1' : 'enabled',
      'data-attr2' : 'disabled',
    },
    timeout: undefined,  // Use default
    cleanupWhenDone: undefined,  // Use default
    document: undefined  // Use default
  };
  var result = goog.net.jsloader.load(testUrl, options);
  result.addCallback(function() {
    testCase.continueTesting();

    var script = result.defaultScope_.script_;

    // Check that the URI matches ours.
    assertTrue('server URI', script.src.indexOf(testUrl) >= 0);

    // Check that the attributes specified are set on the script tag.
    assertEquals('attribute option not applied for attr1',
        'enabled', script.getAttribute('data-attr1'));
    assertEquals('attribute option not applied for attr2',
        'disabled', script.getAttribute('data-attr2'));
  });
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Руслан
 * Date: 02.10.2016
 * Time: 21:16
 */

namespace maestroprog\tplmaster\abstracts;

abstract class Singleton implements \maestroprog\tplmaster\interfaces\Singleton
{
    protected static $instance;

    /**
     * @return static
     */
    public static function instance(): \maestroprog\tplmaster\interfaces\Singleton
    {
        static::$instance or static::$instance = new static();
        return static::$instance;
    }

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    private function __sleep()
    {
    }
}


text:
{
  return el.classList.remove(c);
}


text:
package com.carrotsearch.hppcrt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

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

/**
 *
 */
public class AbstractIteratorTest
{
    public static class RangeIterator extends AbstractIterator<Integer>
    {
        int start;
        int count;

        public RangeIterator(final int start, final int count)
        {
            this.start = start;
            this.count = count;
        }

        @Override
        protected Integer fetch()
        {
            if (this.count == 0)
            {
                return done();
            }

            this.count--;
            return this.start++;
        }
    }

    @Test
    public void testEmpty()
    {
        final RangeIterator i = new RangeIterator(1, 0);
        Assert.assertFalse(i.hasNext());
        Assert.assertFalse(i.hasNext());
    }

    @Test(expected = NoSuchElementException.class)
    public void testEmptyExceptionOnNext()
    {
        final RangeIterator i = new RangeIterator(1, 0);
        i.next();
    }

    @Test
    public void testNonEmpty()
    {
        final RangeIterator i = new RangeIterator(1, 1);
        Assert.assertTrue(i.hasNext());
        Assert.assertTrue(i.hasNext());
        i.next();
        Assert.assertFalse(i.hasNext());
        Assert.assertFalse(i.hasNext());
        try
        {
            i.next();
            Assert.fail();
        } catch (final NoSuchElementException e)
        {
            // expected.
        }
    }

    @Test
    public void testValuesAllRight()
    {
        Assert.assertEquals(Arrays.asList(1), AbstractIteratorTest.addAll(new RangeIterator(1, 1)));
        Assert.assertEquals(Arrays.asList(1, 2), AbstractIteratorTest.addAll(new RangeIterator(1, 2)));
        Assert.assertEquals(Arrays.asList(1, 2, 3), AbstractIteratorTest.addAll(new RangeIterator(1, 3)));
    }

    private static <T> List<T> addAll(final Iterator<T> i)
    {
        final List<T> t = new ArrayList<T>();
        while (i.hasNext()) {
            t.add(i.next());
        }
        return t;
    }
}


text:
Why Rust?
=========

Why write an operating system in Rust? Why even write in Rust?

Rust has enormous advantages, because for operating systems _safety matters_. A lot, actually.

Since operating systems are such an integrated part of computing, they are a very security critical component.

There have been numerous bugs and vulnerabilities in Linux, BSD, Glibc, Bash, X, etc. throughout time, simply due to the lack of memory and type safety. Rust does this right, by enforcing memory safety statically.

Design does matter, but so does implementation. Rust attempts to avoid these unexpected memory unsafe conditions (which are a major source of security critical bugs). Design is a very transparent source of issues. You know what is going on, you know what was intended and what was not.

The basic design of the kernel/userspace separation is fairly similar to genuine Unix-like systems, at this point. The idea is roughly the same: you seperate kernel and userspace, through strict enforcement by the kernel, which manages memory and other critical resources.

However, we have an advantage: enforced memory and type safety. This is Rust's strong side, a large number of "unexpected bugs" (for example, undefined behavior) are eliminated.

The design of Linux and BSD is secure. The implementation is not:

- [Linux kernel vulnerabilities](https://www.cvedetails.com/vulnerability-list.php?vendor_id=33&product_id=47&version_id=&page=1&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=7&cvssscoremax=7.99&year=0&month=0&cweid=0&order=3&trc=269&sha=27cc1be095dd1cc4189b3d337cc787289500c13e)

- [Glibc vulnerabilities](https://www.cvedetails.com/vulnerability-list.php?vendor_id=72&product_id=767&version_id=&page=1&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=0&cvssscoremax=0&year=0&month=0&cweid=0&order=3&trc=62&sha=5e0c40399ffafd65f77e6b537bcc0f50474eeed3)

- [Bash vulnerabilities](http://www.cvedetails.com/vulnerability-list.php?vendor_id=72&product_id=21050&version_id=&page=1&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=0&cvssscoremax=0&year=0&month=0&cweid=0&order=3&trc=10&sha=b7da5775428a703fdead6c27fbca76cd40b7c596)

- [X vulnerabilities](https://www.cvedetails.com/vulnerability-list.php?vendor_id=8216&product_id=&version_id=&page=1&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=0&cvssscoremax=0&year=0&month=0&cweid=0&order=3&trc=55&sha=a68a1ced1b67444749733b7fa9e1438ff0c42810)

Click on the above links. You'll probably notice that many are bugs originating in unsafe conditions (which Rust effectively eliminates) like buffer overflows, not the overall design.

We hope that using Rust will produce a more secure operating system in the end.

<!-- TODO Rust doesn't make your code designed correct; that's impossible. However, it is possible to formally prove a design to be sound (like sel4 did), and this is something we're working on. -->


text:
namespace Foxtrot.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class increasing_column_size_for_title : DbMigration
    {
        public override void Up()
        {
            AlterColumn("dbo.EmployeeProfiles", "Title", c => c.String(maxLength: 75));
        }

        public override void Down()
        {
            AlterColumn("dbo.EmployeeProfiles", "Title", c => c.String(maxLength: 30));
        }
    }
}


text:
<?php

namespace common\models\base;

use Yii;

/**
 * This is the model class for table "partners_family_values".
 *
 * @property integer $ID
 * @property integer $user_id
 * @property integer $family_values_id
 * @property string $created_on
 * @property string $modified_on
 */
class basePartnersFamilyValues extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'partners_family_values';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'family_values_id'], 'required'],
            [['user_id', 'family_values_id'], 'integer'],
            [['created_on', 'modified_on'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'user_id' => 'User ID',
            'family_values_id' => 'Family Values ID',
            'created_on' => 'Created On',
            'modified_on' => 'Modified On',
        ];
    }
}


text:
namespace CoinNews.Administration {

    @Serenity.Decorators.registerEditor()
    export class RoleCheckEditor extends Serenity.CheckTreeEditor<Serenity.CheckTreeItem<any>, any> {

        private searchText: string;

        constructor(div: JQuery) {
            super(div);
        }

        protected createToolbarExtensions() {
            super.createToolbarExtensions();

            Serenity.GridUtils.addQuickSearchInputCustom(this.toolbar.element, (field, text) => {
                this.searchText = Select2.util.stripDiacritics(text || '').toUpperCase();
                this.view.setItems(this.view.getItems(), true);
            });
        }

        protected getButtons() {
            return [];
        }

        protected getTreeItems() {
            return RoleRow.getLookup().items.map(role => <Serenity.CheckTreeItem<any>>{
                id: role.RoleId.toString(),
                text: role.RoleName
            });
        }

        protected onViewFilter(item) {
            return super.onViewFilter(item) &&
                (Q.isEmptyOrNull(this.searchText) ||
                 Select2.util.stripDiacritics(item.text || '')
                     .toUpperCase().indexOf(this.searchText) >= 0);
        }
    }
}


text:
Bluetooth advertizing frame viewer for Android :

* start / stop scan
* list all advertizing frame received
* highlight manufacturer data (often used to advertize static or dynamic data)
* filter frame by device name
* compatible from Android 4.3+ (works fine on Android TV)

![screenshot](https://raw.github.com/bertrandmartel/bluetooth-advert-viewer/master/screen2.png)

Contributors

* Aïman Salmi
* Bertrand Martel

External libraries

* Bluetooth AD frame decode https://github.com/bertrandmartel/bluetooth-ad-frame-decoder


text:
/**
* Helper functions for working with regex/
* @param {object} exports The object to export the public API onto.
*/
(function regexpModule(exports) {
    'use strict';
    var oencode, odecode;

    // Expose the public API
    exports.encode = rexpEncode;
    exports.decode = rexpDecode;
    exports.register = register;
    exports.deregister = deregister;

    /**
    * Encodes a string so it can appear literally inside of a regular expression
    * @param {string} str The string to escase.
    */
    function rexpEncode(str) {
        return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    /**
    * Decodes a string previously encoded by rexpEncode.
    * @param {string} str The string to unescase.
    */
    function rexpDecode(str) {
        return str.replace(/\\([-\\^$*+?.()|[\]{}])/g, '$1');
    }

    /**
    * Adds the escaping functions from the regexp constructor, and saves
    *   references to the originals for restoration on deregister.
    */
    function register() {
        if (RegExp.encode !== rexpEncode) {
            oencode = RegExp.encode;
            odecode = RegExp.decode;
            RegExp.encode = rexpEncode;
            RegExp.decode = rexpDecode;
        }
    }

    /**
    * Removes the escaping functions from the regexp constructor, and restores
    *   the originals.
    */
    function deregister() {
        if (RegExp.encode === rexpEncode) {
            RegExp.encode = oencode;
            RegExp.decode = odecode;
            oencode = undefined;
            odecode = undefined;
        }
    }
}(module.exports));


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Get the getdns runtime API version information in string format.</title>

php_getdns_get_api_version_number

php_getdns_get_errorstr_by_id

getdns Functions

PHP Manual

php_getdns_get_api_version

(PECL getdns >= 0.11.0)

php_getdns_get_api_version — Get the getdns runtime API version information in string format.

Description

   string php_getdns_get_api_version
    ( void
   )

   This function returns the runtime getdns API version information in string format.
   Note that this will give you the version of the library that you're currently
   linked against, not the version of the headers used to compile the library.
   Compile-time information can be found using the phpinfo() function once
   the getdns extension has been loaded by PHP. The version information should
   be consistent for reliable operation.

Parameters

This function has no parameters.

Return Values

   This function returns an string representation of the runtime getdns API
   version information. The format includes the month and year associated
   with the API version number. For example, the API version of July 2015
   has a string representation of "July 2015".

php_getdns_get_api_version_number

php_getdns_get_errorstr_by_id

getdns Functions

PHP Manual


text:
import java.io.{File => JFile, FileFilter => JFileFilter}

import org.apache.commons.io.filefilter.WildcardFileFilter
import sbt._

import scala.annotation.tailrec

object CommonUtils {

  def versionWriter(paramsResolver: () => Seq[String])(projectVersion: String, basePath: String = "target"): Unit = {
    println("\n== Writing Version File ==")
    val args: Seq[String] = paramsResolver()
    println(s"The project version is $projectVersion.")

    import IO._

    val filename = args.headOption.map(Prefix(basePath) + _).getOrElse("target/version.tmp")
    val versionFile = new sbt.File(filename)
    println(s"write $projectVersion into the file: $versionFile")

    write(versionFile, projectVersion, utf8, append = false)
    println("Done: Writing Version File\n")
  }

  def wildcardFilter(names: Seq[String]): JFileFilter =
    new WildcardFileFilter(names.toArray).asInstanceOf[JFileFilter]

  //  def getAllSubDirs(dir: File): Array[File] = dir.listFiles(DirectoryFilter).flatMap(x => x +: getAllSubDirs(x))
  def getAllSubDirs(dir: File): Seq[File] = {
    @tailrec
    def getAllSubDirs(dirs: Array[File],
                      acc: Vector[File]): Vector[File] = dirs match {
      case Array() =>
        acc
      case Array(x) =>
        getAllSubDirs(x.listFiles(DirectoryFilter), acc :+ x)
      case array @ Array(x, _*) =>
        getAllSubDirs(array.drop(1) ++ x.listFiles(DirectoryFilter), acc :+ x)
    }
    getAllSubDirs(dir.listFiles(DirectoryFilter), Vector.empty)
    //    dir.listFiles(DirectoryFilter).flatMap(x => x +: getAllSubDirs(x))
  }

  object BasePath {
    def apply(base: File, dir: String): BasePath = BasePath(base, Option(dir))
    def apply(base: File): BasePath = BasePath(base, None)
  }

  case class BasePath(base: File, dir: Option[String] = None) {
    lazy val pathLength: Int = {
      val thePath = base / dir.getOrElse("")
      val basePath = thePath.getPath
      basePath.length + (if (basePath.endsWith(JFile.separator)) 0 else 1)
    }
  }

  object Prefix {
    def apply(value: String): Prefix = Option(value).fold[Prefix](NoPrefix)(PrefixVal)
    def apply(): Prefix = NoPrefix
  }

  sealed trait Prefix {
    def value: String
    def isEmpty: Boolean
    def fold(defaultVal: => String)(f: String => String): String = if (isEmpty) defaultVal else f(value)
    def +(path: => String): String = fold(path)(prefix => s"$prefix/$path")
  }

  case object NoPrefix extends Prefix { val isEmpty = true; val value = "" }
  private case class PrefixVal(value: String) extends Prefix { val isEmpty = false }

}


text:
package org.tud.inf.st.pccs;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Assignment'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.tud.inf.st.pccs.Assignment#getTo To}

 *
{@link org.tud.inf.st.pccs.Assignment#getFrom From}

 *

 *

 *
 * @see org.tud.inf.st.pccs.PccsPackage#getAssignment()
 * @model
 * @generated
 */
public interface Assignment extends EObject {
	/**
	 * Returns the value of the 'To' attribute.
	 *
	 *

	 * If the meaning of the 'To' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'To' attribute.
	 * @see #setTo(String)
	 * @see org.tud.inf.st.pccs.PccsPackage#getAssignment_To()
	 * @model required="true"
	 * @generated
	 */
	String getTo();

	/**
	 * Sets the value of the '{@link org.tud.inf.st.pccs.Assignment#getTo To}' attribute.
	 *
	 *
	 * @param value the new value of the 'To' attribute.
	 * @see #getTo()
	 * @generated
	 */
	void setTo(String value);

	/**
	 * Returns the value of the 'From' containment reference.
	 *
	 *

	 * If the meaning of the 'From' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'From' containment reference.
	 * @see #setFrom(ComposableMapping)
	 * @see org.tud.inf.st.pccs.PccsPackage#getAssignment_From()
	 * @model containment="true" required="true"
	 * @generated
	 */
	ComposableMapping getFrom();

	/**
	 * Sets the value of the '{@link org.tud.inf.st.pccs.Assignment#getFrom From}' containment reference.
	 *
	 *
	 * @param value the new value of the 'From' containment reference.
	 * @see #getFrom()
	 * @generated
	 */
	void setFrom(ComposableMapping value);

} // Assignment


text:
package org.maripo.xctestresultparser.parser;

class CacheParser extends XMLParser{

}


text:
package state

import (
	"context"
	"errors"
	"github.com/lastbackend/lastbackend/tools/logger"
	"sync"

	"github.com/lastbackend/lastbackend/internal/pkg/models"
)

const logPodPrefix = "node:state:pods:>"

type PodState struct {
	lock       sync.RWMutex
	stats      PodStateStats
	local      map[string]bool
	containers map[string]*models.PodContainer
	pods       map[string]*models.PodStatus
	watchers   map[chan string]bool
}

type PodStateStats struct {
	pods       int
	containers int
}

func (s *PodState) dispatch(pod string) {
	for w := range s.watchers {
		w <- pod
	}
}

func (s *PodState) Watch(watcher chan string, done chan bool) {
	s.watchers[watcher] = true
	defer delete(s.watchers, watcher)
	<-done
}

func (s *PodState) GetPodsCount() int {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: get pods count: %d", logPodPrefix, s.stats.pods)
	return s.stats.pods
}

func (s *PodState) GetContainersCount() int {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: get containers count: %d", logPodPrefix, s.stats.containers)
	return s.stats.containers
}

func (s *PodState) GetPods() map[string]*models.PodStatus {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: get pods", logPodPrefix)
	return s.pods
}

func (s *PodState) SetPods(pods map[string]*models.PodStatus) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: set pods: %d", logPodPrefix, len(pods))
	for key, pod := range pods {
		state(pod)
		s.pods[key] = pod
		s.stats.pods++
	}
}

func (s *PodState) GetPod(key string) *models.PodStatus {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: get pod: %s", logPodPrefix, key)
	s.lock.Lock()
	defer s.lock.Unlock()
	pod, ok := s.pods[key]
	if !ok {
		return nil
	}
	return pod
}

func (s *PodState) AddPod(key string, pod *models.PodStatus) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: add pod: %s: %s ", logPodPrefix, key, pod.Status)
	s.SetPod(key, pod)
}

func (s *PodState) SetLocal(key string) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: set pod: %s as local", logPodPrefix, key)
	s.lock.Lock()
	defer s.lock.Unlock()
	s.local[key] = true
}

func (s *PodState) IsLocal(key string) bool {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: check pod: %s is local", logPodPrefix, key)
	s.lock.Lock()
	defer s.lock.Unlock()
	if _, ok := s.local[key]; ok {
		return true
	}

	return false
}

func (s *PodState) SetPod(key string, pod *models.PodStatus) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: set pod %s: %s", logPodPrefix, key, pod.Status)

	s.lock.Lock()
	if _, ok := s.pods[key]; ok {
		delete(s.pods, key)
		s.stats.pods--
	}

	s.pods[key] = pod
	s.stats.pods++

	s.lock.Unlock()
	for _, c := range pod.Runtime.Services {
		s.SetContainer(c)
	}

	s.lock.Lock()
	state(pod)
	s.lock.Unlock()
	s.dispatch(key)
}

func (s *PodState) DelPod(key string) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: del pod: %s", logPodPrefix, key)
	s.lock.Lock()
	if _, ok := s.pods[key]; ok {
		delete(s.pods, key)
		s.stats.pods--
	}
	s.lock.Unlock()
	s.dispatch(key)
}

func (s *PodState) GetContainer(id string) *models.PodContainer {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: get container: %s", logPodPrefix, id)
	c, ok := s.containers[id]
	if !ok {
		return nil
	}
	return c
}

func (s *PodState) AddContainer(c *models.PodContainer) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: add container: %s", logPodPrefix, c.ID)
	s.lock.Lock()
	if _, ok := s.containers[c.ID]; !ok {
		s.stats.containers++
	}
	s.containers[c.ID] = c

	s.lock.Unlock()
}

func (s *PodState) SetContainer(c *models.PodContainer) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: set container: %s", logPodPrefix, c.ID)
	s.lock.Lock()

	if _, ok := s.containers[c.ID]; !ok {
		s.stats.containers++
	}
	s.containers[c.ID] = c

	s.lock.Unlock()
}

func (s *PodState) DelContainer(c *models.PodContainer) {
	log := logger.WithContext(context.Background())
	log.Debugf("%s: del container: %s", logPodPrefix, c.ID)
	s.lock.Lock()
	if _, ok := s.containers[c.ID]; ok {
		delete(s.containers, c.ID)
		s.stats.containers--
	}
	s.lock.Unlock()
	pod := s.GetPod(c.Pod)
	if pod == nil {
		return
	}

	s.lock.Lock()
	delete(pod.Runtime.Services, c.ID)
	state(pod)
	s.lock.Unlock()
}

func state(s *models.PodStatus) {

	var sts = make(map[string]int)
	var ems string

	switch s.State {
	case models.StateExited:
		return
	case models.StateDestroyed:
		return
	case models.StateError:
		return
	case models.StateProvision:
		return
	case models.StateCreated:
		return
	case models.StatusPull:
		return
	}

	if len(s.Runtime.Services) == 0 {
		s.State = models.StateDegradation
		return
	}

	for _, cn := range s.Runtime.Services {

		switch true {
		case cn.State.Error.Error:
			sts[models.StateError] += 1
			ems = cn.State.Error.Message
			break
		case cn.State.Stopped.Stopped:
			sts[models.StatusStopped] += 1
			break
		case cn.State.Started.Started:
			sts[models.StateStarted] += 1
			break
		}
	}

	switch true {
	case len(s.Runtime.Services) == sts[models.StateError]:
		s.SetError(errors.New(ems))
		break
	case len(s.Runtime.Services) == sts[models.StateStarted]:
		s.SetRunning()
		break
	case len(s.Runtime.Services) == sts[models.StatusStopped]:
		s.SetStopped()
		break
	}
}


text:
package loon.stg;

import loon.canvas.LColor;
import loon.font.LFont;
import loon.geom.RectBox;
import loon.stg.effect.Picture;
import loon.utils.ObjectMap;
import loon.utils.timer.LTimer;

public class STGPlane {

	boolean view = false;

	boolean animation = false;

	public float posX = 0;

	public float posY = 0;

	public float rotation = 0;

	public LColor drawColor = new LColor(LColor.white);

	int animeNo;

	int[] animeList;

	int planeMode = 0;

	float scaleX = 1;

	float scaleY = 1;

	RectBox rect;

	ObjectMap<Integer, Integer> images = new ObjectMap<Integer, Integer>();

	LTimer delay = new LTimer(100);

	String str;

	LFont font;

	LColor color;

	Picture draw;

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <string-array name="otr_options">
    <item>Forcer / Exiger</item>
    <item>Tenter automatiquement</item>
    <item>Sur demande</item>
    <item>Désactivé / Jamais</item>
  </string-array>
</resources>