code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
/** * * Licensed Property to China UnionPay Co., Ltd. * * (C) Copyright of China UnionPay Co., Ltd. 2010 * All Rights Reserved. * * * Modification History: * ============================================================================= * Author Date Description * ------------ ---------- --------------------------------------------------- * xshu 2014-05-28 MPI插件包常量定义 * ============================================================================= */ package com.boyuanitsm.pay.unionpay.config; public class SDKConstants { public final static String COLUMN_DEFAULT = "-"; public final static String KEY_DELIMITER = "#"; /** memeber variable: blank. */ public static final String BLANK = ""; /** member variabel: space. */ public static final String SPACE = " "; /** memeber variable: unline. */ public static final String UNLINE = "_"; /** memeber varibale: star. */ public static final String STAR = "*"; /** memeber variable: line. */ public static final String LINE = "-"; /** memeber variable: add. */ public static final String ADD = "+"; /** memeber variable: colon. */ public final static String COLON = "|"; /** memeber variable: point. */ public final static String POINT = "."; /** memeber variable: comma. */ public final static String COMMA = ","; /** memeber variable: slash. */ public final static String SLASH = "/"; /** memeber variable: div. */ public final static String DIV = "/"; /** memeber variable: left . */ public final static String LB = "("; /** memeber variable: right. */ public final static String RB = ")"; /** memeber variable: rmb. */ public final static String CUR_RMB = "RMB"; /** memeber variable: .page size */ public static final int PAGE_SIZE = 10; /** memeber variable: String ONE. */ public static final String ONE = "1"; /** memeber variable: String ZERO. */ public static final String ZERO = "0"; /** memeber variable: number six. */ public static final int NUM_SIX = 6; /** memeber variable: equal mark. */ public static final String EQUAL = "="; /** memeber variable: operation ne. */ public static final String NE = "!="; /** memeber variable: operation le. */ public static final String LE = "<="; /** memeber variable: operation ge. */ public static final String GE = ">="; /** memeber variable: operation lt. */ public static final String LT = "<"; /** memeber variable: operation gt. */ public static final String GT = ">"; /** memeber variable: list separator. */ public static final String SEP = "./"; /** memeber variable: Y. */ public static final String Y = "Y"; /** memeber variable: AMPERSAND. */ public static final String AMPERSAND = "&"; /** memeber variable: SQL_LIKE_TAG. */ public static final String SQL_LIKE_TAG = "%"; /** memeber variable: @. */ public static final String MAIL = "@"; /** memeber variable: number zero. */ public static final int NZERO = 0; public static final String LEFT_BRACE = "{"; public static final String RIGHT_BRACE = "}"; /** memeber variable: string true. */ public static final String TRUE_STRING = "true"; /** memeber variable: string false. */ public static final String FALSE_STRING = "false"; /** memeber variable: forward success. */ public static final String SUCCESS = "success"; /** memeber variable: forward fail. */ public static final String FAIL = "fail"; /** memeber variable: global forward success. */ public static final String GLOBAL_SUCCESS = "$success"; /** memeber variable: global forward fail. */ public static final String GLOBAL_FAIL = "$fail"; public static final String UTF_8_ENCODING = "UTF-8"; public static final String GBK_ENCODING = "GBK"; public static final String CONTENT_TYPE = "Content-type"; public static final String APP_XML_TYPE = "application/xml;charset=utf-8"; public static final String APP_FORM_TYPE = "application/x-www-form-urlencoded;charset="; /******************************************** 5.0报文接口定义 ********************************************/ /** 版本号. */ public static final String param_version = "version"; /** 证书ID. */ public static final String param_certId = "certId"; /** 签名. */ public static final String param_signature = "signature"; /** 编码方式. */ public static final String param_encoding = "encoding"; /** 交易类型. */ public static final String param_txnType = "txnType"; /** 交易子类. */ public static final String param_txnSubType = "txnSubType"; /** 业务类型. */ public static final String param_bizType = "bizType"; /** 前台通知地址 . */ public static final String param_frontUrl = "frontUrl"; /** 后台通知地址. */ public static final String param_backUrl = "backUrl"; /** 接入类型. */ public static final String param_accessType = "accessType"; /** 收单机构代码. */ public static final String param_acqInsCode = "acqInsCode"; /** 商户类别. */ public static final String param_merCatCode = "merCatCode"; /** 商户类型. */ public static final String param_merType = "merType"; /** 商户代码. */ public static final String param_merId = "merId"; /** 商户名称. */ public static final String param_merName = "merName"; /** 商户简称. */ public static final String param_merAbbr = "merAbbr"; /** 二级商户代码. */ public static final String param_subMerId = "subMerId"; /** 二级商户名称. */ public static final String param_subMerName = "subMerName"; /** 二级商户简称. */ public static final String param_subMerAbbr = "subMerAbbr"; /** Cupsecure 商户代码. */ public static final String param_csMerId = "csMerId"; /** 商户订单号. */ public static final String param_orderId = "orderId"; /** 交易时间. */ public static final String param_txnTime = "txnTime"; /** 发送时间. */ public static final String param_txnSendTime = "txnSendTime"; /** 订单超时时间间隔. */ public static final String param_orderTimeoutInterval = "orderTimeoutInterval"; /** 支付超时时间. */ public static final String param_payTimeoutTime = "payTimeoutTime"; /** 默认支付方式. */ public static final String param_defaultPayType = "defaultPayType"; /** 支持支付方式. */ public static final String param_supPayType = "supPayType"; /** 支付方式. */ public static final String param_payType = "payType"; /** 自定义支付方式. */ public static final String param_customPayType = "customPayType"; /** 物流标识. */ public static final String param_shippingFlag = "shippingFlag"; /** 收货地址-国家. */ public static final String param_shippingCountryCode = "shippingCountryCode"; /** 收货地址-省. */ public static final String param_shippingProvinceCode = "shippingProvinceCode"; /** 收货地址-市. */ public static final String param_shippingCityCode = "shippingCityCode"; /** 收货地址-地区. */ public static final String param_shippingDistrictCode = "shippingDistrictCode"; /** 收货地址-详细. */ public static final String param_shippingStreet = "shippingStreet"; /** 商品总类. */ public static final String param_commodityCategory = "commodityCategory"; /** 商品名称. */ public static final String param_commodityName = "commodityName"; /** 商品URL. */ public static final String param_commodityUrl = "commodityUrl"; /** 商品单价. */ public static final String param_commodityUnitPrice = "commodityUnitPrice"; /** 商品数量. */ public static final String param_commodityQty = "commodityQty"; /** 是否预授权. */ public static final String param_isPreAuth = "isPreAuth"; /** 币种. */ public static final String param_currencyCode = "currencyCode"; /** 账户类型. */ public static final String param_accType = "accType"; /** 账号. */ public static final String param_accNo = "accNo"; /** 支付卡类型. */ public static final String param_payCardType = "payCardType"; /** 发卡机构代码. */ public static final String param_issInsCode = "issInsCode"; /** 持卡人信息. */ public static final String param_customerInfo = "customerInfo"; /** 交易金额. */ public static final String param_txnAmt = "txnAmt"; /** 余额. */ public static final String param_balance = "balance"; /** 地区代码. */ public static final String param_districtCode = "districtCode"; /** 附加地区代码. */ public static final String param_additionalDistrictCode = "additionalDistrictCode"; /** 账单类型. */ public static final String param_billType = "billType"; /** 账单号码. */ public static final String param_billNo = "billNo"; /** 账单月份. */ public static final String param_billMonth = "billMonth"; /** 账单查询要素. */ public static final String param_billQueryInfo = "billQueryInfo"; /** 账单详情. */ public static final String param_billDetailInfo = "billDetailInfo"; /** 账单金额. */ public static final String param_billAmt = "billAmt"; /** 账单金额符号. */ public static final String param_billAmtSign = "billAmtSign"; /** 绑定标识号. */ public static final String param_bindId = "bindId"; /** 风险级别. */ public static final String param_riskLevel = "riskLevel"; /** 绑定信息条数. */ public static final String param_bindInfoQty = "bindInfoQty"; /** 绑定信息集. */ public static final String param_bindInfoList = "bindInfoList"; /** 批次号. */ public static final String param_batchNo = "batchNo"; /** 总笔数. */ public static final String param_totalQty = "totalQty"; /** 总金额. */ public static final String param_totalAmt = "totalAmt"; /** 文件类型. */ public static final String param_fileType = "fileType"; /** 文件名称. */ public static final String param_fileName = "fileName"; /** 批量文件内容. */ public static final String param_fileContent = "fileContent"; /** 商户摘要. */ public static final String param_merNote = "merNote"; /** 商户自定义域. */ // public static final String param_merReserved = "merReserved";//接口变更删除 /** 请求方保留域. */ public static final String param_reqReserved = "reqReserved";// 新增接口 /** 保留域. */ public static final String param_reserved = "reserved"; /** 终端号. */ public static final String param_termId = "termId"; /** 终端类型. */ public static final String param_termType = "termType"; /** 交互模式. */ public static final String param_interactMode = "interactMode"; /** 发卡机构识别模式. */ // public static final String param_recognitionMode = "recognitionMode"; public static final String param_issuerIdentifyMode = "issuerIdentifyMode";// 接口名称变更 /** 商户端用户号. */ public static final String param_merUserId = "merUserId"; /** 持卡人IP. */ public static final String param_customerIp = "customerIp"; /** 查询流水号. */ public static final String param_queryId = "queryId"; /** 原交易查询流水号. */ public static final String param_origQryId = "origQryId"; /** 系统跟踪号. */ public static final String param_traceNo = "traceNo"; /** 交易传输时间. */ public static final String param_traceTime = "traceTime"; /** 清算日期. */ public static final String param_settleDate = "settleDate"; /** 清算币种. */ public static final String param_settleCurrencyCode = "settleCurrencyCode"; /** 清算金额. */ public static final String param_settleAmt = "settleAmt"; /** 清算汇率. */ public static final String param_exchangeRate = "exchangeRate"; /** 兑换日期. */ public static final String param_exchangeDate = "exchangeDate"; /** 响应时间. */ public static final String param_respTime = "respTime"; /** 原交易应答码. */ public static final String param_origRespCode = "origRespCode"; /** 原交易应答信息. */ public static final String param_origRespMsg = "origRespMsg"; /** 应答码. */ public static final String param_respCode = "respCode"; /** 应答码信息. */ public static final String param_respMsg = "respMsg"; // 新增四个报文字段merUserRegDt merUserEmail checkFlag activateStatus /** 商户端用户注册时间. */ public static final String param_merUserRegDt = "merUserRegDt"; /** 商户端用户注册邮箱. */ public static final String param_merUserEmail = "merUserEmail"; /** 验证标识. */ public static final String param_checkFlag = "checkFlag"; /** 开通状态. */ public static final String param_activateStatus = "activateStatus"; /** 加密证书ID. */ public static final String param_encryptCertId = "encryptCertId"; /** 用户MAC、IMEI串号、SSID. */ public static final String param_userMac = "userMac"; /** 关联交易. */ // public static final String param_relationTxnType = "relationTxnType"; /** 短信类型 */ public static final String param_smsType = "smsType"; /** 风控信息域 */ public static final String param_riskCtrlInfo = "riskCtrlInfo"; /** IC卡交易信息域 */ public static final String param_ICTransData = "ICTransData"; /** VPC交易信息域 */ public static final String param_VPCTransData = "VPCTransData"; /** 安全类型 */ public static final String param_securityType = "securityType"; /** 银联订单号 */ public static final String param_tn = "tn"; /** 分期付款手续费率 */ public static final String param_instalRate = "instalRate"; /** 分期付款手续费率 */ public static final String param_mchntFeeSubsidy = "mchntFeeSubsidy"; }
smjie2800/spring-cloud-microservice-redis-activemq-hibernate-mysql
microservice-provider-pay/src/main/java/com/boyuanitsm/pay/unionpay/config/SDKConstants.java
Java
mit
13,548
33.225275
102
0.670332
false
require 'faraday' require 'simple_ratings/foursquare/meta/venue' module SimpleRatings class Foursquare < Faraday::Connection def initialize super(url: 'https://api.foursquare.com/v2/') end def default_params { client_id: ENV['FOURSQUARE_CLIENT_ID'], client_secret: ENV['FOURSQUARE_CLIENT_SECRET'], v: 20130214 } end def search(params) get('venues/search', default_params.merge(params)) end def get(url = nil, params = nil, headers = nil) params ||= {} params = default_params.merge(params) super(url, params, headers) end # def get(*args) # super(*build_default_request_arguments(*args)) # end # def build_default_request_arguments(url = nil, params = nil, headers = nil) # params ||= {} # params = default_params.merge(params) # [url, params, headers] # end end end
benastan/simple_ratings
lib/simple_ratings/foursquare.rb
Ruby
mit
918
20.880952
81
0.610022
false
// // Copyright (C) 2006-2008 Mateusz Loskot // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef SOCI_PLATFORM_H_INCLUDED #define SOCI_PLATFORM_H_INCLUDED #if defined(_MSC_VER) || defined(__MINGW32__) #define LL_FMT_FLAGS "I64" #else #define LL_FMT_FLAGS "ll" #endif // Portability hacks for Microsoft Visual C++ compiler #ifdef _MSC_VER #include <stdlib.h> // Define if you have the vsnprintf variants. #if _MSC_VER < 1500 # define vsnprintf _vsnprintf #endif // Define if you have the snprintf variants. #if _MSC_VER < 1900 #define snprintf _snprintf #endif // Define if you have the strtoll and strtoull variants. #if _MSC_VER < 1300 # error "Visual C++ versions prior 1300 don't support _strtoi64 and _strtoui64" #elif _MSC_VER >= 1300 && _MSC_VER < 1800 namespace std { inline long long strtoll(char const* str, char** str_end, int base) { return _strtoi64(str, str_end, base); } inline unsigned long long strtoull(char const* str, char** str_end, int base) { return _strtoui64(str, str_end, base); } } #endif // _MSC_VER < 1800 #endif // _MSC_VER #if defined(__CYGWIN__) || defined(__MINGW32__) #include <stdlib.h> namespace std { using ::strtoll; using ::strtoull; } #endif #endif // SOCI_PLATFORM_H_INCLUDED
LedgerHQ/lib-ledger-core
core/lib/soci/core/soci-platform.h
C
mit
1,445
23.350877
81
0.653287
false
using System; using System.Text; namespace ExifLibrary { /// <summary> /// Represents an enumerated value. /// </summary> public class ExifEnumProperty<T> : ExifProperty { protected T mValue; protected bool mIsBitField; protected override object _Value { get { return Value; } set { Value = (T)value; } } public new T Value { get { return mValue; } set { mValue = value; } } public bool IsBitField { get { return mIsBitField; } } static public implicit operator T(ExifEnumProperty<T> obj) { return (T)obj.mValue; } public override string ToString() { return mValue.ToString(); } public ExifEnumProperty(ExifTag tag, T value, bool isbitfield) : base(tag) { mValue = value; mIsBitField = isbitfield; } public ExifEnumProperty(ExifTag tag, T value) : this(tag, value, false) { ; } public override ExifInterOperability Interoperability { get { ushort tagid = ExifTagFactory.GetTagID(mTag); Type type = typeof(T); Type basetype = Enum.GetUnderlyingType(type); if (type == typeof(FileSource) || type == typeof(SceneType)) { // UNDEFINED return new ExifInterOperability(tagid, 7, 1, new byte[] { (byte)((object)mValue) }); } else if (type == typeof(GPSLatitudeRef) || type == typeof(GPSLongitudeRef) || type == typeof(GPSStatus) || type == typeof(GPSMeasureMode) || type == typeof(GPSSpeedRef) || type == typeof(GPSDirectionRef) || type == typeof(GPSDistanceRef)) { // ASCII return new ExifInterOperability(tagid, 2, 2, new byte[] { (byte)((object)mValue), 0 }); } else if (basetype == typeof(byte)) { // BYTE return new ExifInterOperability(tagid, 1, 1, new byte[] { (byte)((object)mValue) }); } else if (basetype == typeof(ushort)) { // SHORT return new ExifInterOperability(tagid, 3, 1, ExifBitConverter.GetBytes((ushort)((object)mValue), BitConverterEx.SystemByteOrder, BitConverterEx.SystemByteOrder)); } else throw new UnknownEnumTypeException(); } } } /// <summary> /// Represents an ASCII string. (EXIF Specification: UNDEFINED) Used for the UserComment field. /// </summary> public class ExifEncodedString : ExifProperty { protected string mValue; private Encoding mEncoding; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value; } } public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } } static public implicit operator string(ExifEncodedString obj) { return obj.mValue; } public override string ToString() { return mValue; } public ExifEncodedString(ExifTag tag, string value, Encoding encoding) : base(tag) { mValue = value; mEncoding = encoding; } public override ExifInterOperability Interoperability { get { string enc = ""; if (mEncoding == null) enc = "\0\0\0\0\0\0\0\0"; else if (mEncoding.EncodingName == "US-ASCII") enc = "ASCII\0\0\0"; else if (mEncoding.EncodingName == "Japanese (JIS 0208-1990 and 0212-1990)") enc = "JIS\0\0\0\0\0"; else if (mEncoding.EncodingName == "Unicode") enc = "Unicode\0"; else enc = "\0\0\0\0\0\0\0\0"; byte[] benc = Encoding.ASCII.GetBytes(enc); byte[] bstr = (mEncoding == null ? Encoding.ASCII.GetBytes(mValue) : mEncoding.GetBytes(mValue)); byte[] data = new byte[benc.Length + bstr.Length]; Array.Copy(benc, 0, data, 0, benc.Length); Array.Copy(bstr, 0, data, benc.Length, bstr.Length); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, (uint)data.Length, data); } } } /// <summary> /// Represents an ASCII string formatted as DateTime. (EXIF Specification: ASCII) Used for the date time fields. /// </summary> public class ExifDateTime : ExifProperty { protected DateTime mValue; protected override object _Value { get { return Value; } set { Value = (DateTime)value; } } public new DateTime Value { get { return mValue; } set { mValue = value; } } static public implicit operator DateTime(ExifDateTime obj) { return obj.mValue; } public override string ToString() { return mValue.ToString("yyyy.MM.dd HH:mm:ss"); } public ExifDateTime(ExifTag tag, DateTime value) : base(tag) { mValue = value; } public override ExifInterOperability Interoperability { get { return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 2, (uint)20, ExifBitConverter.GetBytes(mValue, true)); } } } /// <summary> /// Represents the exif version as a 4 byte ASCII string. (EXIF Specification: UNDEFINED) /// Used for the ExifVersion, FlashpixVersion, InteroperabilityVersion and GPSVersionID fields. /// </summary> public class ExifVersion : ExifProperty { protected string mValue; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value.Substring(0, 4); } } public ExifVersion(ExifTag tag, string value) : base(tag) { if (value.Length > 4) mValue = value.Substring(0, 4); else if (value.Length < 4) mValue = value + new string(' ', 4 - value.Length); else mValue = value; } public override string ToString() { return mValue; } public override ExifInterOperability Interoperability { get { if (mTag == ExifTag.ExifVersion || mTag == ExifTag.FlashpixVersion || mTag == ExifTag.InteroperabilityVersion) return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, Encoding.ASCII.GetBytes(mValue)); else { byte[] data = new byte[4]; for (int i = 0; i < 4; i++) data[i] = byte.Parse(mValue[0].ToString()); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, data); } } } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 2xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifPointSubjectArea : ExifUShortArray { protected new ushort[] Value { get { return mValue; } set { mValue = value; } } public ushort X { get { return mValue[0]; } set { mValue[0] = value; } } public ushort Y { get { return mValue[1]; } set { mValue[1] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d})", mValue[0], mValue[1]); return sb.ToString(); } public ExifPointSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifPointSubjectArea(ExifTag tag, ushort x, ushort y) : base(tag, new ushort[] { x, y }) { ; } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 3xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifCircularSubjectArea : ExifPointSubjectArea { public ushort Diamater { get { return mValue[2]; } set { mValue[2] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d}) {2:d}", mValue[0], mValue[1], mValue[2]); return sb.ToString(); } public ExifCircularSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifCircularSubjectArea(ExifTag tag, ushort x, ushort y, ushort d) : base(tag, new ushort[] { x, y, d }) { ; } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 4xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifRectangularSubjectArea : ExifPointSubjectArea { public ushort Width { get { return mValue[2]; } set { mValue[2] = value; } } public ushort Height { get { return mValue[3]; } set { mValue[3] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d}) ({2:d} x {3:d})", mValue[0], mValue[1], mValue[2], mValue[3]); return sb.ToString(); } public ExifRectangularSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifRectangularSubjectArea(ExifTag tag, ushort x, ushort y, ushort w, ushort h) : base(tag, new ushort[] { x, y, w, h }) { ; } } /// <summary> /// Represents GPS latitudes and longitudes (EXIF Specification: 3xRATIONAL) /// </summary> public class GPSLatitudeLongitude : ExifURationalArray { protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } } public MathEx.UFraction32 Degrees { get { return mValue[0]; } set { mValue[0] = value; } } public MathEx.UFraction32 Minutes { get { return mValue[1]; } set { mValue[1] = value; } } public MathEx.UFraction32 Seconds { get { return mValue[2]; } set { mValue[2] = value; } } public static explicit operator float(GPSLatitudeLongitude obj) { return obj.ToFloat(); } public float ToFloat() { return (float)Degrees + ((float)Minutes) / 60.0f + ((float)Seconds) / 3600.0f; } public override string ToString() { return string.Format("{0:F2}°{1:F2}'{2:F2}\"", (float)Degrees, (float)Minutes, (float)Seconds); } public GPSLatitudeLongitude(ExifTag tag, MathEx.UFraction32[] value) : base(tag, value) { ; } public GPSLatitudeLongitude(ExifTag tag, float d, float m, float s) : base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(d), new MathEx.UFraction32(m), new MathEx.UFraction32(s) }) { ; } } /// <summary> /// Represents a GPS time stamp as UTC (EXIF Specification: 3xRATIONAL) /// </summary> public class GPSTimeStamp : ExifURationalArray { protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } } public MathEx.UFraction32 Hour { get { return mValue[0]; } set { mValue[0] = value; } } public MathEx.UFraction32 Minute { get { return mValue[1]; } set { mValue[1] = value; } } public MathEx.UFraction32 Second { get { return mValue[2]; } set { mValue[2] = value; } } public override string ToString() { return string.Format("{0:F2}:{1:F2}:{2:F2}\"", (float)Hour, (float)Minute, (float)Second); } public GPSTimeStamp(ExifTag tag, MathEx.UFraction32[] value) : base(tag, value) { ; } public GPSTimeStamp(ExifTag tag, float h, float m, float s) : base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(h), new MathEx.UFraction32(m), new MathEx.UFraction32(s) }) { ; } } /// <summary> /// Represents an ASCII string. (EXIF Specification: BYTE) /// Used by Windows XP. /// </summary> public class WindowsByteString : ExifProperty { protected string mValue; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value; } } static public implicit operator string(WindowsByteString obj) { return obj.mValue; } public override string ToString() { return mValue; } public WindowsByteString(ExifTag tag, string value) : base(tag) { mValue = value; } public override ExifInterOperability Interoperability { get { byte[] data = Encoding.Unicode.GetBytes(mValue); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 1, (uint)data.Length, data); } } } }
ahzf/ExifLibrary
ExifLibrary/ExifExtendedProperty.cs
C#
mit
13,977
36.463807
182
0.554458
false
using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; using ShowFinder.Models; namespace ShowFinder.Repositories.Interfaces { public interface IMongoRepository { IMongoDatabase Database(string name); Task<BsonDocument> GetUserProfile(IMongoCollection<BsonDocument> userProfilesCollection, string hash); Task<bool> UpdateShows(IMongoCollection<BsonDocument> userProfilesCollection, string userHash, IEnumerable<string> showList); Task<bool> UpdateDownloadedEpisode(IMongoCollection<BsonDocument> userProfilesCollection, string profileId, string episodeId, string filteredShowName, DownloadedEpisode downloadedEpisodeData); Task<bool> DeleteDownloadedEpisode(IMongoCollection<BsonDocument> userProfilesCollection, string profileId, string episodeId, string filtereShowdName); Task<bool> UpdateTimeSpan(IMongoCollection<BsonDocument> userProfilesCollection, UserProfile profile); Task<BsonDocument> GetFromCache(IMongoCollection<BsonDocument> collection, string id); Task<bool> SetToCache(IMongoCollection<BsonDocument> collection, string id, BsonDocument doc, int daysToExpire); } }
YanivHaramati/ShowFinder
ShowFinder/Repositories/Interfaces/IMongoRepository.cs
C#
mit
1,257
55.136364
133
0.775299
false
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>/home/pavm/programming/lib/gft/src/gft_stack.cpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#namespaces">Namespaces</a> &#124; <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">gft_stack.cpp File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="gft__stack_8h_source.html">gft_stack.h</a>&quot;</code><br/> </div><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:namespacegft"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft.html">gft</a></td></tr> <tr class="memdesc:namespacegft"><td class="mdescLeft">&#160;</td><td class="mdescRight">Base namespace for common definitions and prototypes. <br/></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:namespacegft_1_1Stack"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html">gft::Stack</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:aae4b11552918128f72c2c0ce6769ea00"><td class="memItemLeft" align="right" valign="top">Stack *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#aae4b11552918128f72c2c0ce6769ea00">gft::Stack::Create</a> (int n)</td></tr> <tr class="separator:aae4b11552918128f72c2c0ce6769ea00"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac9833a76111d61f284fe131a8439ea79"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#ac9833a76111d61f284fe131a8439ea79">gft::Stack::Destroy</a> (Stack **S)</td></tr> <tr class="separator:ac9833a76111d61f284fe131a8439ea79"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9d1618c9defa1ad3e683b7c57d0e3075"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#a9d1618c9defa1ad3e683b7c57d0e3075">gft::Stack::Push</a> (Stack *S, int p)</td></tr> <tr class="separator:a9d1618c9defa1ad3e683b7c57d0e3075"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a58729721489e11127a35700782ed0ae2"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacegft_1_1Stack.html#a58729721489e11127a35700782ed0ae2">gft::Stack::Pop</a> (Stack *S)</td></tr> <tr class="separator:a58729721489e11127a35700782ed0ae2"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Feb 25 2015 10:27:50 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
ademirtc/bandeirantes
lib/gft/doc/html/gft__stack_8cpp.html
HTML
mit
4,861
65.589041
291
0.687924
false
// // BABAudioPlaylist.h // Pods // // Created by Bryn Bodayle on May/12/2015. // // #import <Foundation/Foundation.h> @interface BABAudioPlaylist : NSObject + (instancetype)audioPlaylistWithArray:(NSArray *)array; - (instancetype)initWithArray:(NSArray *)array; - (id)objectAtIndexedSubscript:(NSUInteger)idx; - (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx; @property (nonatomic, readonly) NSInteger count; @end
brynbodayle/BABAudioPlayer
Pod/Classes/BABAudioPlaylist.h
C
mit
437
18.863636
61
0.743707
false
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
riyadhalnur/keystone
fields/types/datearray/DateArrayType.js
JavaScript
mit
3,038
20.394366
101
0.640882
false
# -*- coding: utf-8 -*- require "em-websocket" require "eventmachine-tail" module Tailer # Extends FileTail to push data tailed to an EM::Channel. All open websockets # subscribe to a channel for the request stack and this pushes the data to # all of them at once. class StackTail < EventMachine::FileTail def initialize(filename, channel, startpos=-1) super(filename, startpos) @channel = channel @buffer = BufferedTokenizer.new end # This method is called whenever FileTail receives an inotify event for # the tailed file. It breaks up the data per line and pushes a line at a # time. This is to prevent the last javascript line from being broken up # over 2 pushes thus breaking the eval on the front end. def receive_data(data) # replace non UTF-8 characters with ? data.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '�') @buffer.extract(data).each do |line| @channel.push line end end end # Checks if stack log symlink exists and creates Tailer for it def self.stack_tail(stack, channel, channel_count) if Deployinator.get_visible_stacks.include?(stack) filename = "#{Deployinator::Helpers::RUN_LOG_PATH}current-#{stack}" start_pos = (channel_count == 0) ? 0 : -1 File.exists?(filename) ? StackTail.new(filename, channel, start_pos) : false end end end
etsy/deployinator
lib/deployinator/stack-tail.rb
Ruby
mit
1,403
36.864865
82
0.685939
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_05) on Thu Jul 03 13:49:54 PDT 2008 --> <TITLE> edu.sdsc.inca </TITLE> <META NAME="keywords" CONTENT="edu.sdsc.inca package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../edu/sdsc/inca/package-summary.html" target="classFrame">edu.sdsc.inca</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="Consumer.html" title="class in edu.sdsc.inca" target="classFrame">Consumer</A> <BR> <A HREF="ConsumerTest.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest</A> <BR> <A HREF="ConsumerTest.ConsumerTester.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.ConsumerTester</A> <BR> <A HREF="ConsumerTest.MockAgent.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.MockAgent</A> <BR> <A HREF="ConsumerTest.MockDepot.html" title="class in edu.sdsc.inca" target="classFrame">ConsumerTest.MockDepot</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
IncaProject/IncaProject.github.io
releases/2.4/docs/javadocs/inca-consumers/edu/sdsc/inca/package-frame.html
HTML
mit
1,321
32.025
127
0.69947
false
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels.Sockets { using System; using System.Diagnostics.Contracts; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; public class DefaultDatagramChannelConfig : DefaultChannelConfiguration, IDatagramChannelConfig { const int DefaultFixedBufferSize = 2048; readonly Socket socket; public DefaultDatagramChannelConfig(IDatagramChannel channel, Socket socket) : base(channel, new FixedRecvByteBufAllocator(DefaultFixedBufferSize)) { Contract.Requires(socket != null); this.socket = socket; } public override T GetOption<T>(ChannelOption<T> option) { if (ChannelOption.SoBroadcast.Equals(option)) { return (T)(object)this.Broadcast; } if (ChannelOption.SoRcvbuf.Equals(option)) { return (T)(object)this.ReceiveBufferSize; } if (ChannelOption.SoSndbuf.Equals(option)) { return (T)(object)this.SendBufferSize; } if (ChannelOption.SoReuseaddr.Equals(option)) { return (T)(object)this.ReuseAddress; } if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { return (T)(object)this.LoopbackModeDisabled; } if (ChannelOption.IpMulticastTtl.Equals(option)) { return (T)(object)this.TimeToLive; } if (ChannelOption.IpMulticastAddr.Equals(option)) { return (T)(object)this.Interface; } if (ChannelOption.IpMulticastIf.Equals(option)) { return (T)(object)this.NetworkInterface; } if (ChannelOption.IpTos.Equals(option)) { return (T)(object)this.TrafficClass; } return base.GetOption(option); } public override bool SetOption<T>(ChannelOption<T> option, T value) { if (base.SetOption(option, value)) { return true; } if (ChannelOption.SoBroadcast.Equals(option)) { this.Broadcast = (bool)(object)value; } else if (ChannelOption.SoRcvbuf.Equals(option)) { this.ReceiveBufferSize = (int)(object)value; } else if (ChannelOption.SoSndbuf.Equals(option)) { this.SendBufferSize = (int)(object)value; } else if (ChannelOption.SoReuseaddr.Equals(option)) { this.ReuseAddress = (bool)(object)value; } else if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { this.LoopbackModeDisabled = (bool)(object)value; } else if (ChannelOption.IpMulticastTtl.Equals(option)) { this.TimeToLive = (short)(object)value; } else if (ChannelOption.IpMulticastAddr.Equals(option)) { this.Interface = (EndPoint)(object)value; } else if (ChannelOption.IpMulticastIf.Equals(option)) { this.NetworkInterface = (NetworkInterface)(object)value; } else if (ChannelOption.IpTos.Equals(option)) { this.TrafficClass = (int)(object)value; } else { return false; } return true; } public int SendBufferSize { get { try { return this.socket.SendBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SendBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int ReceiveBufferSize { get { try { return this.socket.ReceiveBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.ReceiveBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int TrafficClass { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool ReuseAddress { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) != 0; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, value ? 1 : 0); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool Broadcast { get { try { return this.socket.EnableBroadcast; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.EnableBroadcast = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool LoopbackModeDisabled { get { try { return !this.socket.MulticastLoopback; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.MulticastLoopback = !value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public short TimeToLive { get { try { return (short)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public EndPoint Interface { get { try { return this.socket.LocalEndPoint; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { this.socket.Bind(value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public NetworkInterface NetworkInterface { get { try { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); int value = (int)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface); int index = IPAddress.NetworkToHostOrder(value); if (interfaces.Length > 0 && index >= 0 && index < interfaces.Length) { return interfaces[index]; } return null; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { int index = this.GetNetworkInterfaceIndex(value); if (index >= 0) { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface, index); } } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } internal SocketOptionLevel AddressFamilyOptionLevel { get { if (this.socket.AddressFamily == AddressFamily.InterNetwork) { return SocketOptionLevel.IP; } if (this.socket.AddressFamily == AddressFamily.InterNetworkV6) { return SocketOptionLevel.IPv6; } throw new NotSupportedException($"Socket address family {this.socket.AddressFamily} not supported, expecting InterNetwork or InterNetworkV6"); } } internal int GetNetworkInterfaceIndex(NetworkInterface networkInterface) { Contract.Requires(networkInterface != null); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); for (int index = 0; index < interfaces.Length; index++) { if (interfaces[index].Id == networkInterface.Id) { return index; } } return -1; } } }
dragonphoenix/proto-java-csharp
DotNetty/DotNetty.Transport/Channels/Sockets/DefaultDatagramChannelConfig.cs
C#
mit
14,695
29.108607
158
0.419519
false
/* * Search first occurence of a particular string in a given text [Finite Automata] * Author: Progyan Bhattacharya <progyanb@acm.org> * Repo: Design-And-Analysis-of-Algorithm [MIT LICENSE] */ #include "Search.h" static int NextState(int m, char* pattern, int state, int symbol) { if (state < m && pattern[state] == symbol) { return state + 1; } for (int next = state, prev = next - 1, i = 0; next > 0; next--) { if (pattern[prev] == symbol) { for (i = 0; i < prev; i++) { if (pattern[i] != pattern[state - next + 1 + i]) { break; } } if (i == prev) { return next; } } } return 0; } static void GenerateTable(int m, char* pattern, int Table[m][CHAR_MAX]) { for (int state = 0, symbol = 0; symbol < CHAR_MAX || (symbol = 0, ++state) < m; symbol++) { Table[state][symbol] = NextState(m, pattern, state, symbol); } } int Search(int n, char* haystack, int m, char* needle) { int Table[m + 1][CHAR_MAX], state = 0; GenerateTable(m + 1, needle, Table); for (int i = 0; i < n; i++) { state = Table[state][haystack[i]]; if (state == m) { return (i - m + 1); } } return -1; }
Progyan1997/Design-and-Analysis-of-Algorithm
String Search/Finite Automata/Search.c
C
mit
1,307
28.704545
95
0.509564
false
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') class Video include Claire::Client::Item end describe Claire::Client::Item do #@session.should_receive(:post).with("url", "data", "headers") #@session = mock("session") before do Claire::Client.stub(:get).with('videos/id').and_return xml :item @video = Video.new(hash_from_xml(:item)) end describe "its initializer" do describe "its base_url class attribute" do it "should default to the class name, pluralized" do Video.base_url.should == "videos" end it "should accept manual overwrite on the class" do Video.base_url = "lists" Video.base_url.should == "lists" Video.base_url = nil Video.base_url.should == "videos" end it "if the class is in a module, it should get the class name only" do eval %( module Testing class Video include Claire::Client::Item end end ) Testing::Video.base_url.should == "videos" end end context "upon receiving a Hash" do before :each do @video = Video.new(hash_from_xml(:item)) end it "should set partial do true" do @video.should be_partial end it "should skip the <rss> container if it is present" do @video.title.should be_a_kind_of String @video.should_not respond_to :rss end it "should skip the <channel> container if its present" do video = Video.new(hash_from_xml(:item_with_channel)) video.title.should be_a_kind_of String video.should_not respond_to :channel end it "should never set 'items' attributes " do %w(item item_with_channel).each do |type| video = Video.new(hash_from_xml(type)) video.should_not respond_to :item video.title.should be_a_kind_of String end end it "should set the link attribute properly (eg ignoring links to other objects/pages)" do video = Video.new hash_from_xml :item_with_channel video.link.should be_a_kind_of String end it "should set its key/values as properties of the element" do %w(title link category keywords description).each do |item| @video.send(item).should be_a_kind_of String end %w(thumbnail content).each{ |item| @video.send(item).should be_a_kind_of Array } end it "should fail if there is not a link attribute" do lambda { Video.new( {:rss => {:item => {:name => 'bla'}}} ) }.should raise_error Claire::Error end end context "upon receiving a String" do before { @video = Video.new 'id' } it "should open the given string" do lambda { Video.new "" }.should raise_error lambda { Video.new "id" }.should_not raise_error end it "should parse the result using the XML parsing rules" do @video.title.should be_a_kind_of String end it "should set partial to false" do @video.should_not be_partial end end end describe "its comparison (spaceship) operator" do it "should be defined" do @video.should respond_to '<=>' end it "should compare items by title" do @video2 = @video.clone (@video <=> @video2).should be 0 end end context "when an undefined method is called" do it "it should raise error if partial is false" context "if the item is partial" do it "should request the full object from server, and replace itself" it "should return the asked attribute" end end it "should have a list of its children as the children class attribute" do Claire::Client::Item.children.include?(Video).should be true end end
memuller/claire.client
spec/claire_client/item_spec.rb
Ruby
mit
3,595
27.09375
98
0.654798
false
<?php namespace Zanson\SMParser\Traits\Song; use Zanson\SMParser\SMException; trait Banner { public $banner = ''; /** * @return string */ public function getBanner() { return $this->banner; } /** * @param string $banner * * @return $this * @throws SMException */ public function setBanner($banner) { if (!is_string($banner)) { throw new SMException("Banner must be a string"); } $this->banner = $banner; return $this; } }
jasonwatt/SMParser
src/Traits/Song/Banner.php
PHP
mit
541
16.483871
61
0.537893
false
if ( !window.console ) window.console = { log:function(){} }; jQuery(document).ready(function($) { console.log('Keep being awesome.'); });
shampine/180
public/js/src/script.js
JavaScript
mit
143
19.571429
61
0.643357
false
package parser import ( "monkey/ast" "monkey/token" ) func (p *Parser) parseStringLiteralExpression() ast.Expression { return &ast.StringLiteral{Token: p.curToken, Value: p.curToken.Literal} } func (p *Parser) parseInterpolatedString() ast.Expression { is := &ast.InterpolatedString{Token: p.curToken, Value: p.curToken.Literal, ExprMap: make(map[byte]ast.Expression)} key := "0"[0] for { if p.curTokenIs(token.LBRACE) { p.nextToken() expr := p.parseExpression(LOWEST) is.ExprMap[key] = expr key++ } p.nextInterpToken() if p.curTokenIs(token.ISTRING) { break } } return is }
mayoms/monkey
parser/strings.go
GO
mit
612
20.103448
116
0.694444
false
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Timers; using System.Diagnostics; namespace ForumHelper { public partial class ToastForm : Form { public ToastForm() { InitializeComponent(); TopMost = true; ShowInTaskbar = false; timer = new System.Windows.Forms.Timer(); timer.Interval = 500; timer.Tick += timer_Tick; } private System.Windows.Forms.Timer timer; private int startPosX; private int startPosY; private void ToastForm_Load(object sender, EventArgs e) { } protected override void OnLoad(EventArgs e) { startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width; startPosY = Screen.PrimaryScreen.WorkingArea.Height - Height; SetDesktopLocation(startPosX, startPosY); pageLinkLabel.Text = URLEventArgs.Url; // base.OnLoad(e); timer.Start(); } void timer_Tick(object sender, EventArgs e) { startPosY -= 50; if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height) timer.Stop(); else { SetDesktopLocation(startPosX, startPosY); timer.Stop(); } } private void ToastForm_Click(object sender, EventArgs e) { this.Close(); } private void pageLinkLabelClick(object sender, EventArgs e) { Process.Start(this.pageLinkLabel.Text); this.Close(); } } }
ttitto/PersonalProjects
ForumHelper/ForumHelper/ToastForm.cs
C#
mit
1,852
25.61194
91
0.551351
false
<?php /* * The MIT License (MIT) * * Copyright (c) 2014-2018 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ use Base64Url\Base64Url; use Jose\Decrypter; use Jose\Encrypter; use Jose\Factory\JWEFactory; use Jose\Loader; use Jose\Object\JWEInterface; use Jose\Object\JWK; use Jose\Object\JWKSet; use Jose\Test\Stub\FakeLogger; use Jose\Test\BaseTestCase; /** * Class EncrypterTest. * * @group Encrypter * @group Functional */ class EncrypterBaseTest extends BaseTestCase { public function testEncryptWithJWTInput() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'FOO', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testCreateCompactJWEUsingFactory() { $jwe = JWEFactory::createJWEToCompactJSON( 'FOO', $this->getRSARecipientKey(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ] ); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testCreateFlattenedJWEUsingFactory() { $jwe = JWEFactory::createJWEToFlattenedJSON( 'FOO', $this->getRSARecipientKey(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [ 'foo' => 'bar', ], [ 'plic' => 'ploc', ], 'A,B,C,D' ); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertEquals('bar', $loaded->getSharedHeader('foo')); self::assertEquals('A,B,C,D', $loaded->getAAD('foo')); self::assertEquals('ploc', $loaded->getRecipient(0)->getHeader('plic')); self::assertNull($loaded->getPayload()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertEquals('FOO', $loaded->getPayload()); } public function testEncryptAndLoadFlattenedWithAAD() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( $this->getKeyToEncrypt(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload())); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Compression method "FIP" not supported */ public function testCompressionAlgorithmNotSupported() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( $this->getKeyToEncrypt(), [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'FIP', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey()); $encrypter->encrypt($jwe); } public function testMultipleInstructionsNotAllowedWithCompactSerialization() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP', 'RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKeyWithAlgorithm(), ['alg' => 'RSA-OAEP']); $jwe = $jwe->addRecipientInformation($this->getRSARecipientKey(), ['alg' => 'RSA-OAEP-256']); $encrypter->encrypt($jwe); self::assertEquals(2, $jwe->countRecipients()); } public function testMultipleInstructionsNotAllowedWithFlattenedSerialization() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey(), ['kid' => '123456789', 'alg' => 'RSA-OAEP-256'] ); $encrypter->encrypt($jwe); self::assertEquals(2, $jwe->countRecipients()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Foreign key management mode forbidden. */ public function testForeignKeyManagementModeForbidden() { $encrypter = Encrypter::createEncrypter(['dir', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'enc' => 'A256CBC-HS512', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getDirectKey(), ['kid' => 'DIR_1', 'alg' => 'dir'] ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Key cannot be used to encrypt */ public function testOperationNotAllowedForTheKey() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'Foo', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getSigningKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Key is only allowed for algorithm "RSA-OAEP". */ public function testAlgorithmNotAllowedForTheKey() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'FOO', [ 'enc' => 'A256CBC-HS512', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKeyWithAlgorithm() ); $encrypter->encrypt($jwe); } public function testEncryptAndLoadFlattenedWithDeflateCompression() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256'], ['A128CBC-HS256'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeySetToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A128CBC-HS256', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); $encrypted = $jwe->toCompactJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('RSA-OAEP-256', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A128CBC-HS256', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('DEF', $loaded->getSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeySetToEncrypt(), new JWKSet($loaded->getPayload())); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Parameter "alg" is missing. */ public function testAlgParameterIsMissing() { $encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A256CBC-HS512', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Parameter "enc" is missing. */ public function testEncParameterIsMissing() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The key encryption algorithm "A256CBC-HS512" is not supported or not a key encryption algorithm instance. */ public function testNotAKeyEncryptionAlgorithm() { $encrypter = Encrypter::createEncrypter(['A256CBC-HS512'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'A256CBC-HS512', 'alg' => 'A256CBC-HS512', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The content encryption algorithm "RSA-OAEP-256" is not supported or not a content encryption algorithm instance. */ public function testNotAContentEncryptionAlgorithm() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256'], [], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => '123456789', 'enc' => 'RSA-OAEP-256', 'alg' => 'RSA-OAEP-256', 'zip' => 'DEF', ]); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey() ); $encrypter->encrypt($jwe); } public function testEncryptAndLoadCompactWithDirectKeyEncryption() { $encrypter = Encrypter::createEncrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['dir'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE($this->getKeyToEncrypt()); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'DIR_1', 'enc' => 'A192CBC-HS384', 'alg' => 'dir', ]); $jwe = $jwe->addRecipientInformation( $this->getDirectKey() ); $encrypter->encrypt($jwe); $encrypted = $jwe->toFlattenedJSON(0); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($encrypted); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('dir', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getSymmetricKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_array($loaded->getPayload())); self::assertEquals($this->getKeyToEncrypt(), new JWK($loaded->getPayload())); } public function testEncryptAndLoadCompactKeyAgreement() { $encrypter = Encrypter::createEncrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['ECDH-ES'], ['A192CBC-HS384'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE(['user_id' => '1234', 'exp' => time() + 3600]); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A192CBC-HS384', 'alg' => 'ECDH-ES', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A192CBC-HS384', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue($loaded->hasClaims()); self::assertTrue($loaded->hasClaim('user_id')); self::assertEquals('1234', $loaded->getClaim('user_id')); } public function testEncryptAndLoadCompactKeyAgreementWithWrappingCompact() { $encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders([ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A256CBC-HS512', 'alg' => 'ECDH-ES+A256KW', ]); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } public function testEncryptAndLoadWithGCMAndAAD() { $encrypter = Encrypter::createEncrypter(['ECDH-ES+A256KW'], ['A256GCM'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE( 'Live long and Prosper.', [ 'kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'enc' => 'A256GCM', 'alg' => 'ECDH-ES+A256KW', ], [], 'foo,bar,baz' ); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey() ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toFlattenedJSON(0)); $decrypter = Decrypter::createDecrypter(['A256GCM'], ['ECDH-ES+A256KW'], ['DEF'], new FakeLogger()); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('ECDH-ES+A256KW', $loaded->getSharedProtectedHeader('alg')); self::assertEquals('A256GCM', $loaded->getSharedProtectedHeader('enc')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } public function testEncryptAndLoadCompactKeyAgreementWithWrapping() { $encrypter = Encrypter::createEncrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $decrypter = Decrypter::createDecrypter(['RSA-OAEP-256', 'ECDH-ES+A256KW'], ['A256CBC-HS512'], ['DEF'], new FakeLogger()); $jwe = JWEFactory::createJWE('Live long and Prosper.'); $jwe = $jwe->withSharedProtectedHeaders(['enc' => 'A256CBC-HS512']); $jwe = $jwe->addRecipientInformation( $this->getECDHRecipientPublicKey(), ['kid' => 'e9bc097a-ce51-4036-9562-d2ade882db0d', 'alg' => 'ECDH-ES+A256KW'] ); $jwe = $jwe->addRecipientInformation( $this->getRSARecipientKey(), ['kid' => '123456789', 'alg' => 'RSA-OAEP-256'] ); $encrypter->encrypt($jwe); $loader = new Loader(new FakeLogger()); $loaded = $loader->load($jwe->toJSON()); self::assertEquals(2, $loaded->countRecipients()); self::assertInstanceOf(JWEInterface::class, $loaded); self::assertEquals('A256CBC-HS512', $loaded->getSharedProtectedHeader('enc')); self::assertEquals('ECDH-ES+A256KW', $loaded->getRecipient(0)->getHeader('alg')); self::assertEquals('RSA-OAEP-256', $loaded->getRecipient(1)->getHeader('alg')); self::assertFalse($loaded->hasSharedHeader('zip')); self::assertFalse($loaded->hasSharedProtectedHeader('zip')); self::assertNull($loaded->getPayload()); $decrypter->decryptUsingKeySet($loaded, $this->getPrivateKeySet(), $index); self::assertEquals(0, $index); self::assertTrue(is_string($loaded->getPayload())); self::assertEquals('Live long and Prosper.', $loaded->getPayload()); } /** * @return JWK */ private function getKeyToEncrypt() { $key = new JWK([ 'kty' => 'EC', 'use' => 'enc', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); return $key; } /** * @return JWKSet */ private function getKeySetToEncrypt() { $key = new JWK([ 'kty' => 'EC', 'use' => 'enc', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); $key_set = new JWKSet(); $key_set->addKey($key); return $key_set; } /** * @return JWK */ private function getRSARecipientKey() { $key = new JWK([ 'kty' => 'RSA', 'use' => 'enc', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', ]); return $key; } /** * @return JWK */ private function getRSARecipientKeyWithAlgorithm() { $key = new JWK([ 'kty' => 'RSA', 'use' => 'enc', 'alg' => 'RSA-OAEP', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', ]); return $key; } /** * @return JWK */ private function getSigningKey() { $key = new JWK([ 'kty' => 'EC', 'key_ops' => ['sign', 'verify'], 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI', ]); return $key; } /** * @return JWK */ private function getECDHRecipientPublicKey() { $key = new JWK([ 'kty' => 'EC', 'key_ops' => ['encrypt', 'decrypt'], 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', ]); return $key; } /** * @return JWK */ private function getDirectKey() { $key = new JWK([ 'kid' => 'DIR_1', 'key_ops' => ['encrypt', 'decrypt'], 'kty' => 'oct', 'k' => Base64Url::encode(hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F')), ]); return $key; } }
Spomky-Labs/jose
tests/Functional/EncrypterBaseTest.php
PHP
mit
25,820
34.225102
364
0.578273
false
// Fill out your copyright notice in the Description page of Project Settings. using UnrealBuildTool; using System.Collections.Generic; public class UnrealCamDemoTarget : TargetRules { public UnrealCamDemoTarget(TargetInfo Target) : base(Target) { Type = TargetType.Game; ExtraModuleNames.AddRange( new string[] { "UnrealCamDemo" } ); } }
mrayy/UnityCam
UnrealCamDemo/Source/UnrealCamDemo.Target.cs
C#
mit
349
23.928571
78
0.767908
false
package br.com.gamemods.tutorial.ctf; import org.bukkit.plugin.java.JavaPlugin; public class CTFGameMods extends JavaPlugin { }
joserobjr/CTFGameMods
src/main/java/br/com/gamemods/tutorial/ctf/CTFGameMods.java
Java
mit
131
15.375
43
0.801527
false
--- category: Components type: Navigation title: Dropdown cover: https://gw.alipayobjects.com/zos/alicdn/eedWN59yJ/Dropdown.svg --- A dropdown list. ## When To Use When there are more than a few options to choose from, you can wrap them in a `Dropdown`. By hovering or clicking on the trigger, a dropdown menu will appear, which allows you to choose an option and execute the relevant action. ## API ### Dropdown | Property | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | arrow | Whether the dropdown arrow should be visible | boolean \| { pointAtCenter: boolean } | false | | | disabled | Whether the dropdown menu is disabled | boolean | - | | | destroyPopupOnHide | Whether destroy dropdown when hidden | boolean | false | | | getPopupContainer | To set the container of the dropdown menu. The default is to create a div element in body, but you can reset it to the scrolling area and make a relative reposition. [Example on CodePen](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | (triggerNode: HTMLElement) => HTMLElement | () => document.body | | | overlay | The dropdown menu | [Menu](/components/menu) \| () => Menu | - | | | overlayClassName | The class name of the dropdown root element | string | - | | | overlayStyle | The style of the dropdown root element | CSSProperties | - | | | placement | Placement of popup menu: `bottom` `bottomLeft` `bottomRight` `top` `topLeft` `topRight` | string | `bottomLeft` | | | trigger | The trigger mode which executes the dropdown action. Note that hover can't be used on touchscreens | Array&lt;`click`\|`hover`\|`contextMenu`> | \[`hover`] | | | visible | Whether the dropdown menu is currently visible | boolean | - | | | onVisibleChange | Called when the visible state is changed. Not trigger when hidden by click item | (visible: boolean) => void | - | | You should use [Menu](/components/menu/) as `overlay`. The menu items and dividers are also available by using `Menu.Item` and `Menu.Divider`. > Warning: You must set a unique `key` for `Menu.Item`. > > Menu of Dropdown is unselectable by default, you can make it selectable via `<Menu selectable>`. ### Dropdown.Button | Property | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | buttonsRender | Custom buttons inside Dropdown.Button | (buttons: ReactNode\[]) => ReactNode\[] | - | | | loading | Set the loading status of button | boolean \| { delay: number } | false | | | disabled | Whether the dropdown menu is disabled | boolean | - | | | icon | Icon (appears on the right) | ReactNode | - | | | overlay | The dropdown menu | [Menu](/components/menu) | - | | | placement | Placement of popup menu: `bottom` `bottomLeft` `bottomRight` `top` `topLeft` `topRight` | string | `bottomLeft` | | | size | Size of the button, the same as [Button](/components/button/#API) | string | `default` | | | trigger | The trigger mode which executes the dropdown action | Array&lt;`click`\|`hover`\|`contextMenu`> | \[`hover`] | | | type | Type of the button, the same as [Button](/components/button/#API) | string | `default` | | | visible | Whether the dropdown menu is currently visible | boolean | - | | | onClick | The same as [Button](/components/button/#API): called when you click the button on the left | (event) => void | - | | | onVisibleChange | Called when the visible state is changed | (visible: boolean) => void | - | |
ant-design/ant-design
components/dropdown/index.en-US.md
Markdown
mit
3,428
63.679245
330
0.682905
false
/************************ BUBBLE SORT Author:Rhysn Date:2015 *************************/ #include <stdio.h> #include <stdlib.h> typedef int ElemType; void swap(ElemType *left,ElemType *right){ ElemType temp = *left; *left = *right; *right = temp; } void BubbleSort(ElemType *array,int num){ if(num == 1) return; ElemType *left = array,*right = array + 1; int key = num; while(--key){ if(*left > *right) swap(left,right); left++; right++; } BubbleSort(array,--num); } int main(){ int a[14]; int *b=a; int num = 14; srand((unsigned)time(NULL)); while (num--) *b++ = rand()%10; b=a; num=14; while(num--){ printf("%d ",*b++ ); } printf("\n"); BubbleSort(a,14); num = 14; b=a; while(num--){ printf("%d ",*b++ ); } printf("\n"); return 0; }
Rhysn/Data-Structure-And-Algorithm
Sort/BubbleSort.c
C
mit
917
15.087719
46
0.462377
false
/** * Keyframes. */ @-webkit-keyframes rotation { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes rotation { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @-webkit-keyframes rotation-reverse { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(-360deg); -ms-transform: rotate(-360deg); -webkit-transform: rotate(-360deg); transform: rotate(-360deg); } } @keyframes rotation-reverse { 0% { -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -moz-transform: rotate(-360deg); -ms-transform: rotate(-360deg); -webkit-transform: rotate(-360deg); transform: rotate(-360deg); } } body { background-color: #000; } #sun { background-color: #aa0; height: 50px; left: calc(50% - 25px); position: absolute; top: calc(50% - 25px); width: 50px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 10px 2px #aa5500; -webkit-box-shadow: 0 0 10px 2px #aa5500; box-shadow: 0 0 10px 2px #aa5500; } #mercury-orbit { -webkit-animation: rotation 8s linear infinite; animation: rotation 8s linear infinite; height: 10%; left: 45%; position: absolute; top: 45%; width: 10%; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; } #mercury { background: #953; height: 10px; width: 10px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px 1px #222222; -webkit-box-shadow: inset 0 0 5px 1px #222222; box-shadow: inset 0 0 5px 1px #222222; } #venus-orbit { -webkit-animation: rotation-reverse 16s linear infinite; animation: rotation-reverse 16s linear infinite; height: 14%; left: 43%; position: absolute; top: 43%; width: 14%; } #venus { background: #db5; height: 15px; width: 15px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 3px 0 #ffff88; -webkit-box-shadow: 0 0 3px 0 #ffff88; box-shadow: 0 0 3px 0 #ffff88; } #earth-orbit { -webkit-animation: rotation 24s linear infinite; animation: rotation 24s linear infinite; height: 20%; left: 40%; position: absolute; top: 40%; width: 20%; } #earth { background-color: #0bf; height: 20px; width: 20px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 8px 1px white; -webkit-box-shadow: 0 0 8px 1px white; box-shadow: 0 0 8px 1px white; } #mars-orbit { -webkit-animation: rotation 44s linear infinite; animation: rotation 44s linear infinite; height: 30%; left: 35%; position: absolute; top: 35%; width: 30%; } #mars { background-color: #833; height: 18px; width: 18px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px #220000; -webkit-box-shadow: inset 0 0 5px #220000; box-shadow: inset 0 0 5px #220000; } #jupiter-orbit { -webkit-animation: rotation 68s linear infinite; animation: rotation 68s linear infinite; height: 40%; left: 30%; position: absolute; top: 30%; width: 40%; } #jupiter { background-color: #ffa500; height: 40px; width: 40px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 10px 1px black; -webkit-box-shadow: inset 0 0 10px 1px black; box-shadow: inset 0 0 10px 1px black; } #jupiter-spot { background-color: rgba(160, 0, 0, 0.5); height: 8px; left: 20px; position: absolute; top: 19px; width: 8px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: 0 0 5px 0 #990000; -webkit-box-shadow: 0 0 5px 0 #990000; box-shadow: 0 0 5px 0 #990000; } #saturn-orbit { -webkit-animation: rotation 80s linear infinite; animation: rotation 80s linear infinite; height: 48%; left: 26%; position: absolute; top: 26%; width: 48%; } #saturn { background-color: #ab5; height: 36px; width: 36px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px #445511; -webkit-box-shadow: inset 0 0 5px #445511; box-shadow: inset 0 0 5px #445511; } #uranus-orbit { -webkit-animation: rotation 100s linear infinite; animation: rotation 100s linear infinite; height: 60%; left: 20%; position: absolute; top: 20%; width: 60%; } #uranus { background-color: #3da; height: 30px; width: 30px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 5px #445511; -webkit-box-shadow: inset 0 0 5px #445511; box-shadow: inset 0 0 5px #445511; } #neptune-orbit { -webkit-animation: rotation 120s linear infinite; animation: rotation 120s linear infinite; height: 70%; left: 15%; position: absolute; top: 15%; width: 70%; } #neptune { background-color: #05a; height: 32px; width: 32px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 10px 1px black; -webkit-box-shadow: inset 0 0 10px 1px black; box-shadow: inset 0 0 10px 1px black; } #pluto-orbit { -webkit-animation: rotation 120s linear infinite; animation: rotation 120s linear infinite; height: 70%; left: 15%; position: absolute; top: 15%; width: 70%; } #pluto { background-color: #7a7474; height: 10px; width: 10px; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-box-shadow: inset 0 0 10px 1px black; -webkit-box-shadow: inset 0 0 10px 1px black; box-shadow: inset 0 0 10px 1px black; }
jonahkirangi/solarsystem
css/style.css
CSS
mit
6,321
20.282828
58
0.650688
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./b89c9c584be36686b5c8c1699d0ab37f2ca82f649a1f817843cceb1bafd56a45.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/c5cb57467c267c20a35f92318f4692026c064ad7ef73843ba6db5d1bcd65b843.html
HTML
mit
550
28
98
0.581818
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./111c39a5fd93aebe64e0345eaa4a3fa383b808cd19ce3e292b38f80817041e92.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/cfa46991bdb810d48aaad070e86d32606ad11ab98dba37c82ee2433179f9b2ce.html
HTML
mit
550
28
98
0.581818
false
/**************************************************************** Copyright (C) 2014 All rights reserved. > File Name: < echo_server.c > > Author: < Sean Guo > > Mail: < iseanxp+code@gmail.com > > Created Time: < 2014/06/19 > > Last Changed: < 2015/11/30 > > Description: echo server for ARM //{{{ int bind(int sockfd, struct sockaddr * my_addr, int addrlen); bind()用来设置给参数sockfd 的socket 一个名称. 此名称由参数my_addr 指向一个sockaddr 结构, 对于不同的socket domain 定义了一个通用的数据结构 struct sockaddr { unsigned short int sa_family; char sa_data[14]; }; 1、sa_family 为调用socket()时的domain 参数, 即AF_xxxx 值. 2、sa_data 最多使用14 个字符长度. 此sockaddr 结构会因使用不同的socket domain 而有不同结构定义, 例如使用AF_INET domain,其socketaddr 结构定义便为 struct socketaddr_in { unsigned short int sin_family; uint16_t sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }; struct in_addr { uint32_t s_addr; }; 1、sin_family 即为sa_family 2、sin_port 为使用的port 编号 3、sin_addr. s_addr 为IP 地址 sin_zero 未使用. 参数 addrlen 为sockaddr 的结构长度. 返回值:成功则返回0, 失败返回-1, 错误原因存于errno 中. 错误代码: 1、EBADF 参数sockfd 非合法socket 处理代码. 2、EACCESS 权限不足 3、ENOTSOCK 参数sockfd 为一文件描述词, 非socket. //}}} Usage: ./echo_server ****************************************************************/ //{{{ include files #include <stdio.h> #include <sys/socket.h> #include <sys/wait.h> // waitpid() #include <stdlib.h> // exit(); #include <string.h> // bzero(); #include <netinet/in.h> // struct sockaddr_in; #include <time.h> // time(); #include <arpa/inet.h> // inet_pton(); #include <unistd.h> // write(); #include <errno.h> // errno #include <signal.h> // SIGCHLD //}}} #define MAXLINE 4096 /* max text line length */ #define LISTENQ 1024 /* 2nd argument to listen() , 排队的最大连接数*/ #define LISTEN_PORT 9669 //服务器监听端口 //参数: 已连接的socket描述符. //功能: echo此socket发送的一切数据; //阻塞函数, 直到对方socket关闭. void str_echo(int sockfd); //信号处理函数, 将等待一个子进程的结束。 void sig_child(int signo); int main(int argc, char **argv) //{{{ { int listenfd, connfd; struct sockaddr_in server_addr, client_addr; socklen_t addr_len; char buffer[MAXLINE]; pid_t child_pid; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(LISTEN_PORT); // int bind(int sockfd, struct sockaddr * my_addr, int addrlen); // bind()用来设置给参数sockfd 的socket 一个名称. // 此名称由参数my_addr 指向一个sockaddr 结构, 对于不同的socket domain 定义了一个通用的数据结构 bind(listenfd, (struct sockaddr *) &server_addr, sizeof(server_addr)); // int listen(int s, int backlog); // listen()用来监听描述符s 的socket连接请求. // 参数backlog 指定同时能处理的最大连接要求, 如果连接数目达此上限则client 端将收到ECONNREFUSED 的错误. // listen()并未开始接收连接请求, 只设置socket 为listen 模式,真正接收client 端连线的是accept(). // 通常listen()会在socket(), bind()之后调用, 接着才调用accept(). // 成功则返回0, 失败返回-1, 错误原因存于errno // listen()只适用SOCK_STREAM 或SOCK_SEQPACKET 的socket 类型. // 如果socket 为AF_INET 则参数backlog 最大值可设至128. listen(listenfd, LISTENQ); signal(SIGCHLD, sig_child); //为SIGCHLD匹配自定义的函数, 使得处理子进程僵死的问题. //主进程就为一个监听端口, 为每个连接fork一个新的进程. for ( ; ; ) { addr_len = sizeof(client_addr); // int accept(int s, struct sockaddr * addr, int * addrlen); // accept()用来接受描述符s 的socket连接请求. // socket 必需先经bind()、listen()函数处理过, // 当有连接请求进来时, accept()会返回一个新的socket 处理代码, 往后的数据传送与读取就是经由新的socket处理, // 而原来参数s 的socket 能继续使用accept()来接受新的连线要求. // 连线成功时, 参数addr 所指的结构会被系统填入远程主机的地址数据, 参数addrlen 为scokaddr 的结构长度. // 成功则返回新的socket 处理代码, 失败返回-1, 错误原因存于errno 中. connfd = accept(listenfd, (struct sockaddr *) &client_addr, &addr_len); //创建子进程处理客户端请求, 主进程继续监听. child_pid = fork(); if(child_pid < 0) //failed to fork a process. { fprintf(stderr, "error: failed in fork()\n"); exit(1); } else if(child_pid == 0) //the child process. { close(listenfd); //close listenfd in child process. str_echo(connfd); //the task of child process - As a echo server. exit(0); } else // the parent process. close(connfd); //close connfd in parent process. //调用close()只会减少对应socket描述符的引用数, 当引用数为0才会清楚对应的socket. } }//}}} void str_echo(int sockfd) //{{{ { ssize_t n; char buf[1024]; again: while( (n = read(sockfd, buf, 1024)) > 0) //不断从sockfd中读取数据 write(sockfd, buf, n); if(n < 0 && errno == EINTR) //由于信号中断(EINTR)而没有读取到数据时, 返回while循环. goto again; else if( n < 0) //无法读取数据 perror("str_echo: read error"); }//}}} //信号处理函数, 将等待一个子进程的结束。 void sig_child(int signo) //{{{ { pid_t pid; int state; //pid = wait(&state); //等待一个子进程的结束 while( (pid = waitpid(-1, &state, WNOHANG)) > 0) //使用非阻塞的waitpid等待可结束的所有子进程 printf("child pid[%d] terminated.\n", pid); }//}}}
SeanXP/ARM-Tiny6410
linux/linux-example/socket_echo_server/echo_server.c
C
mit
6,157
26.761628
76
0.644398
false
'use strict'; var emojiArr = require('./emojis'); var i = 0; var existingRules = {}; var generateEmoji = function(selector) { if (!existingRules[selector]) { existingRules[selector] = emojiArr[i]; if (i !== emojiArr.length) { i++ } else { i = 0; } } return existingRules[selector]; } module.exports = generateEmoji;
thuongvu/postcss-emoji
emojify.js
JavaScript
mit
382
19.105263
47
0.565445
false
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsBesselIRequest. /// </summary> public partial class WorkbookFunctionsBesselIRequest : BaseRequest, IWorkbookFunctionsBesselIRequest { /// <summary> /// Constructs a new WorkbookFunctionsBesselIRequest. /// </summary> public WorkbookFunctionsBesselIRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsBesselIRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsBesselIRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsBesselIRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsBesselIRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
ginach/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsBesselIRequest.cs
C#
mit
3,043
34.8
153
0.583963
false
# -*- coding: utf-8 -*- require 'helper' class TestRegressionSetColumn07 < Test::Unit::TestCase def setup setup_dir_var end def teardown File.delete(@xlsx) if File.exist?(@xlsx) end def test_set_column07 @xlsx = 'set_column07.xlsx' workbook = WriteXLSX.new(@xlsx) worksheet = workbook.add_worksheet bold = workbook.add_format(:bold => 1) italic = workbook.add_format(:italic => 1) bold_italic = workbook.add_format(:bold => 1, :italic => 1) data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15] ] worksheet.write('A1', 'Foo', italic) worksheet.write('B1', 'Bar', bold) worksheet.write('A2', data) worksheet.set_row(12, nil, italic) worksheet.set_column('F:F', nil, bold) worksheet.write('F13', nil, bold_italic) worksheet.insert_image('E12', File.join(@test_dir, 'regression', 'images/logo.png')) workbook.close compare_xlsx_for_regression(File.join(@regression_output, @xlsx), @xlsx) end end
Orphist/write_xlsx
test/regression/test_set_column07.rb
Ruby
mit
1,095
23.333333
81
0.573516
false
var fractal = fractal || {}; fractal.workerPaths = { "mandelbrot": "public/js/mandel.js", }; fractal.Fractal = function (canvas, workerCount) { this.canvas = canvas; this.workerCount = workerCount; this.workerDoneCount = 0; this.ctx = canvas.getContext("2d"); this.width = canvas.width; this.height = canvas.height; this.workerPath = fractal.workerPaths["mandelbrot"]; this.topLeft = new Complex(-1.5, 1.1); this.bottomRight = new Complex(0.8, -1.1); this.maxIter = 1200; var lingrad = this.ctx.createLinearGradient(0, 0, this.width, 0); lingrad.addColorStop(0, '#00f'); lingrad.addColorStop(0.1, '#fa0'); lingrad.addColorStop(0.5, '#ff0'); lingrad.addColorStop(0.7, '#f1b'); lingrad.addColorStop(1, '#fff'); this.ctx.fillStyle = lingrad; this.ctx.fillRect(0, 0, this.width, 2); this.gradientImage = this.ctx.getImageData(0, 0, this.width, 1); this.imgData = this.ctx.getImageData(0, 0, this.width, this.height); this.ondone = null; this.workers = []; }; fractal.Fractal.prototype = function () { var computeRow = function (workerIndex, row) { var args = { action: "computeRow", row: row, workerIndex: workerIndex }; this.workers[workerIndex].postMessage(args); }; var initializeWorker = function (workerIndex) { var drow = (this.bottomRight.imag - this.topLeft.imag) / this.height; var dcol = (this.bottomRight.real - this.topLeft.real) / this.width; var args = { action: "setup", maxIter: this.maxIter, width: this.width, height: this.height, topLeft: this.topLeft, bottomRight: this.bottomRight, drow: drow, dcol: dcol, workerIndex: workerIndex, juliaPoint: this.juliaPoint }; this.workers[workerIndex].postMessage(args); }; var createWorkers = function (workerPath) { var obj = this; var rowData = obj.ctx.createImageData(obj.width, 1); for (var workerIndex = 0; workerIndex < obj.workerCount; workerIndex++) { obj.workers[workerIndex] = new Worker(obj.workerPath); this.workers[workerIndex].onmessage = function (event) { if (event.data.logData) { console.log("Worker: " + event.data.logData); } if (event.data.row >= 0) { var wIndex = event.data.workerIndex; for (var index = 0; index < obj.width; index++) { var color = getColor.call(obj, event.data.iterData[index]); var destIndex = 4 * index; rowData.data[destIndex] = color.red; rowData.data[destIndex + 1] = color.green; rowData.data[destIndex + 2] = color.blue; rowData.data[destIndex + 3] = color.alpha; } obj.ctx.putImageData(rowData, 0, event.data.row); if (obj.nextRow < obj.height) { console.log("Worker: " + wIndex, " nextRow: " + obj.nextRow); computeRow.call(obj, wIndex, obj.nextRow); obj.nextRow = obj.nextRow + 1; } else { obj.workerDoneCount++; if (obj.workerDoneCount == obj.workerCount) { var duration = new Date().getTime() - obj.startTime; if (typeof obj.ondone === 'function') { obj.ondone(duration); } } } } }; } }; var getColor = function (iter) { if (iter == this.maxIter) { return { red: 0, green: 0, blue: 0, alpha: 255 }; } var index = (iter % this.gradientImage.width) * 4; return { red: this.gradientImage.data[index], green: this.gradientImage.data[index + 1], blue: this.gradientImage.data[index + 2], alpha: this.gradientImage.data[index + 3] }; }, render = function () { this.startTime = new Date().getTime(); this.workerDoneCount = 0; createWorkers.call(this, this.workerPath); this.nextRow = this.workerCount; for (var workerIndex = 0; workerIndex < this.workerCount; workerIndex++) { initializeWorker.call(this, workerIndex); computeRow.call(this, workerIndex, workerIndex); } } return { render: render }; } (); jQuery(function($) { var fra = new fractal.Fractal(document.getElementById("fractal"), 2); $('#draw-fractal').on('click',function() { fra.render(); }); });
hectoregm/hectoregm
Practica3/public/js/canvas_fractal.js
JavaScript
mit
4,312
28.737931
78
0.604824
false
describe('raureif', function () { it('test', function () { }); });
chrmod/raureif
tests/node/index-test.js
JavaScript
mit
71
16.75
33
0.521127
false
/** * @file ui/core/styleguide/index//html/01-body/40-main/main.js * @description Listeners on the body, iframe, and rightpull bar. */ /* istanbul ignore if */ if (typeof window === 'object') { document.addEventListener('DOMContentLoaded', () => { const $orgs = FEPPER_UI.requerio.$orgs; const { uiFns, uiProps } = FEPPER_UI; $orgs['#sg-rightpull'].on('mouseenter', function () { $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-hover'); }); $orgs['#sg-rightpull'].on('mouseleave', function () { $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); }); // Handle manually resizing the viewport. // 1. On "mousedown" store the click location. // 2. Make a hidden div visible so that the cursor doesn't get lost in the iframe. // 3. On "mousemove" calculate the math, save the results to a cookie, and update the viewport. $orgs['#sg-rightpull'].on('mousedown', function (e) { uiProps.sgRightpull.posX = e.pageX; uiProps.sgRightpull.vpWidth = uiProps.vpWidth; // Show the cover. $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-drag'); }); // Add the mouse move event and capture data. Also update the viewport width. $orgs['#patternlab-body'].on('mousemove', function (e) { if ($orgs['#sg-cover'].getState().classArray.includes('shown-by-rightpull-drag')) { let vpWidthNew = uiProps.sgRightpull.vpWidth; if (uiProps.dockPosition === 'bottom') { vpWidthNew += 2 * (e.pageX - uiProps.sgRightpull.posX); } else { vpWidthNew += e.pageX - uiProps.sgRightpull.posX; } if (vpWidthNew > uiProps.minViewportWidth) { uiFns.sizeIframe(vpWidthNew, false); } } }); // Handle letting go of rightpull bar after dragging to resize. $orgs['#patternlab-body'].on('mouseup', function () { uiProps.sgRightpull.posX = null; uiProps.sgRightpull.vpWidth = null; $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-drag'); }); }); }
electric-eloquence/fepper-npm
ui/core/styleguide/index/html/01-body/40-main/main.js
JavaScript
mit
2,224
35.459016
99
0.626799
false
<div> <table class="table table-bordered"> <tr> <td> <div km-term-check name="root-traits" locales="locales" required ng-change="onRootTraitsChange()" ng-model="rootTraits" terms="options.rootTraits()" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['81799D15-669E-4346-9AEC-6834893D2BE4'].selected"> <td> <legend>Resistencia a enfermedades y plagas</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['81799D15-669E-4346-9AEC-6834893D2BE4'].items" ng-change="onTraitsChange()" terms="options.traits('81799D15-669E-4346-9AEC-6834893D2BE4')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['0C74FEB2-78E8-4163-81EF-2D410FB2FBBC'].selected"> <td> <legend>Resistencia a herbicidas</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['0C74FEB2-78E8-4163-81EF-2D410FB2FBBC'].items" ng-change="onTraitsChange()" terms="options.traits('0C74FEB2-78E8-4163-81EF-2D410FB2FBBC')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['87D98E42-4757-42DE-9C3F-815BFAA35218'].selected"> <td> <legend>Resistencia a los antibióticos</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['87D98E42-4757-42DE-9C3F-815BFAA35218'].items" ng-change="onTraitsChange()" terms="options.traits('87D98E42-4757-42DE-9C3F-815BFAA35218')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['31396BD1-9E3E-4EB3-A29E-9A22B7230221'].selected"> <td> <legend>Tolerancia al estrés abiótico</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['31396BD1-9E3E-4EB3-A29E-9A22B7230221'].items" ng-change="onTraitsChange()" terms="options.traits('31396BD1-9E3E-4EB3-A29E-9A22B7230221')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['337747E5-522D-42DF-8C57-FE626C1572EC'].selected"> <td> <legend>Cambios en la fisiología y/o producción</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['337747E5-522D-42DF-8C57-FE626C1572EC'].items" ng-change="onTraitsChange()" terms="options.traits('337747E5-522D-42DF-8C57-FE626C1572EC')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['3B427EA6-5260-47F1-B424-FAAA5960FB52'].selected"> <td> <legend>Cambios en la calidad y/o el contenido metabólico</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['3B427EA6-5260-47F1-B424-FAAA5960FB52'].items" ng-change="onTraitsChange()" terms="options.traits('3B427EA6-5260-47F1-B424-FAAA5960FB52')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['5B9DB3B4-90A1-451A-A10C-E3A47995344F'].selected"> <td> <legend>Producción de compuestos médicos o farmacéuticos (humanos o animales)</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['5B9DB3B4-90A1-451A-A10C-E3A47995344F'].items" ng-change="onTraitsChange()" terms="options.traits('5B9DB3B4-90A1-451A-A10C-E3A47995344F')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['C8C662E2-D633-4C69-96EA-C9853997A3A5'].selected"> <td> <legend>Uso en aplicaciones industriales</legend> <div km-term-check name="traits" locales="locales" required ng-model="traits['C8C662E2-D633-4C69-96EA-C9853997A3A5'].items" ng-change="onTraitsChange()" terms="options.traits('C8C662E2-D633-4C69-96EA-C9853997A3A5')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['75DE5726-4C52-442C-8BF8-B77A6EBE48E2'].selected"> <td> <legend>Modificación genética por aplicación de impulsores genéticos</legend> <div km-term-check name="traits" locales="locales" required ng-change="onTraitsChange()" ng-model="traits['75DE5726-4C52-442C-8BF8-B77A6EBE48E2'].items" terms="options.traits('75DE5726-4C52-442C-8BF8-B77A6EBE48E2')" binding-type="term[]"></div> </td> </tr> <tr ng-if="traits['traitsOtherSection'].selected"> <td> <div km-term-check name="traits" locales="locales" required ng-change="onTraitsChange()" ng-model="traits['traitsOtherSection'].items" terms="options.traitsOtherSection()" binding-type="term[]"> </div> </td> </tr> <tr ng-if="traits['0C74FEB2-78E8-4163-81EF-2D410FB2FBBC'].selected"> <td> </td> </tr> </table> </div>
scbd/absch.cbd.int
i18n/es/app/views/forms/directives/traits-selector.directive.html
HTML
mit
5,390
56.180851
175
0.569302
false
<?php namespace Checkdomain\Holiday; use Checkdomain\Holiday\Model\Holiday; /** * Class Util */ class Util { /** * Instantiates a provider for a given iso code * * @param string $iso * * @return ProviderInterface */ protected function getProvider($iso) { $instance = null; $class = '\\Checkdomain\\Holiday\\Provider\\' . $iso; if (class_exists($class)) { $instance = new $class; } return $instance; } /** * @param \DateTime|string $date * * @return \DateTime */ protected function getDateTime($date) { if (!$date instanceof \DateTime) { $date = new \DateTime($date); } return $date; } /** * @param string $iso * * @return string */ protected function getIsoCode($iso) { return strtoupper($iso); } /** * Checks wether a given date is a holiday * * This method can be used to check whether a specific date is a holiday * in a specified country and state * * @param string $iso * @param \DateTime|string $date * @param string $state * * @return bool */ public function isHoliday($iso, $date = 'now', $state = null) { return ($this->getHoliday($iso, $date, $state) !== null); } /** * Provides detailed information about a specific holiday * * @param string $iso * @param \DateTime|string $date * @param string $state * * @return Holiday|null */ public function getHoliday($iso, $date = 'now', $state = null) { $iso = $this->getIsoCode($iso); $date = $this->getDateTime($date); $provider = $this->getProvider($iso); $holiday = $provider->getHolidayByDate($date, $state); return $holiday; } }
checkdomain/Holiday
src/Util.php
PHP
mit
1,932
19.774194
76
0.52588
false
namespace Votter.Services { using System; using System.Linq; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(Votter.Services.Startup))] public partial class Startup { public void Configuration(IAppBuilder app) { this.ConfigureAuth(app); } } }
Team-Papaya-Web-Services-and-Cloud/Web-Services-and-Cloud-Teamwork-2014
Votter/Votter.Services/Startup.cs
C#
mit
331
18.411765
60
0.620061
false
#ifndef BUTTONS_H #define BUTTONS_H #include "FreeRTOS.h" /* hardware button state */ struct button_state_t { /* STATE WRITTEN IN IRQ HANDLER */ /* current button state: 0 (up, released) or 1 (down, pressed) */ int st; /* the cpu-tick time when the current state (up or down) was recorded */ TickType_t tick; /* STATE UPDATED IN OS TASK */ /* the cpu-tick time when the button was last pressed; * used for detecting short and long button clicks in ButtonTask */ TickType_t kdwn_tick; /* the cpu-tick time when the event BTN_LONGCLICK was last sent */ TickType_t longclick_sent_tick; }; /* buttons identification */ #define BTN0 0 #define BTN1 1 #define BTN2 2 /* mask for BTNx */ #define BTNx_M 0xFF /* button event */ #define BTN_DOWN 0x100 #define BTN_UP 0x200 #define BTN_SHORTCLICK 0x400 #define BTN_LONGCLICK 0x800 /* hardware ports and pins */ #define HW_BTN0_Port GPIOB #define HW_BTN1_Port GPIOB #define HW_BTN2_Port GPIOB #define HW_BTN0_Pin GPIO_Pin_5 #define HW_BTN1_Pin GPIO_Pin_6 #define HW_BTN2_Pin GPIO_Pin_7 /* dead time in milliseconds - supress hardware glitches */ #define BUTTON_DEAD_TM 10 /* max short click time in miliseconds */ #define BUTTON_SHORTCLICK_TM 1000 /* repetition time of BTN_LONGCLICK events once long-click is recognized */ #define BUTTON_LONGCLICK_REPE_TM 800 /* current button state */ extern struct button_state_t btnsts[3]; /* IRQ handler for button state change */ void EXTI9_5_IRQHandler(void); /* OS task handling buttons events */ void ButtonsTask(void *pvParameters); #endif
jsyk/PIP-Watch
pipwatch_zero-fw/buttons.h
C
mit
1,579
22.220588
75
0.712476
false
<div class="panel panel-default movie-container"> <div class="panel-body"> <div class="row top-part"> <div class="col-xs-12 col-md-4 movie-image"> <img ng-show="movie.Poster" class="img-rounded" src="{{movie.Poster}}" /> <div ng-show="!movie.Poster" class="img-rounded img-alt"> <span>{{movie.Title}}</span> </div> </div> <div class="col-xs-12 col-md-8 movie-desc"> <h2 ng-show="movie.Title">{{movie.Title}}<span ng-show="movie.Year">-{{movie.Year}}</span></h2> <p ng-show="movie.Plot"><span ng-show="movie.Type"><strong>In this {{movie.Type}}, </strong></span>{{movie.Plot}}</p> <p ng-hide="!movie.Released && !movie.Runtime && !movie.Rated"> <span ng-show="movie.Released && movie.Released!=='N/A'" class="badge">{{movie.Released}}</span> <span ng-show="movie.Runtime && movie.Runtime!=='N/A'" class="badge">{{movie.Runtime}}</span> <span ng-show="movie.Rated && movie.Rated!=='N/A'" class="badge">{{movie.Rated}}</span> </p> <p class="movieGenra" ng-show="movie.Genre[0]!==''"> <span ng-repeat="Genre in movie.Genre" class="badge">{{Genre}}</span> </p> <p class="movieActors" ng-show="movie.Actors[0]!==''"> <span><strong>Starring - </strong></span> <span ng-repeat="Actors in movie.Actors">{{Actors}}<span ng-hide="$index===(movie.Actors.length-1)">,</span></span> </p> <p class="movieDirector" ng-show="movie.Director[0] !== ''"> <span><strong>Directed By - </strong></span> <span ng-repeat="Director in movie.Director">{{Director}}</span> </p> <p class="movieWriter" ng-show="movie.Writer[0] !== ''"> <span><strong>Written By -</strong></span> <span ng-repeat="Writer in movie.Writer">{{Writer}}<span ng-hide="$index===(movie.Writer.length-1)">,</span></span> </p> </div> </div> <div class="bottom-part"> <div class="row"> <div class="col-xs-12 col-md-6 languageAc"> <div class="panel-group" id="langAccordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="langHeading"> <h4 class="panel-title"> <a data-toggle="collapse" onclick="return false;" data-parent="#langAccordion" href="#Lcollapse" aria-expanded="true" aria-controls="Lcollapse"> Language Availability </a> </h4> </div> <div id="Lcollapse" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="langHeading"> <div class="panel-body"> <span ng-repeat="lan in movie.Language">{{lan}}<span ng-hide="$index===(movie.Language.length-1)">,</span></span> </div> </div> </div> </div> </div> <div class="col-xs-12 col-md-6 countryAc"> <div class="panel-group" id="counAccordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="conHeading"> <h4 class="panel-title"> <a data-toggle="collapse" onclick="return false;" data-parent="#counAccordion" href="#Ccollapse" aria-expanded="true" aria-controls="Ccollapse"> Country Availability </a> </h4> </div> <div id="Ccollapse" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="conHeading"> <div class="panel-body"> <span ng-repeat="con in movie.Country">{{con}}<span ng-hide="$index===(movie.Country.length-1)">,</span></span> </div> </div> </div> </div> </div> </div> <div class="row imdbrow"> <div class="col-xs-12 col-md-12 imdbAc"> <div class="panel-group" id="imdbAccordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="imdbHeading"> <h4 class="panel-title"> <a data-toggle="collapse" onclick="return false;" data-parent="#imdbAccordion" href="#imdbcollapse" aria-expanded="true" aria-controls="imdbcollapse"> IMDB DATA </a> </h4> </div> <div id="imdbcollapse" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="imdbHeading"> <div class="panel-body"> <div class="col-xs-12 col-md-6"> <span>IMDB Rating -</span><span>> {{movie.imdbRating}}</span> <!-- rating --> <div class="critic-rating"> <h5>Relative Star Rating</h5> <div class="rating star-{{movie.imdbRating | getRatingClass}}"> <i class="fa fa-star star-1-on"></i> <i class="fa fa-star star-off star-1-off"></i> <i class="fa fa-star-half star-1-half"></i> <i class="fa fa-star star-2-on"></i> <i class="fa fa-star star-off star-2-off"></i> <i class="fa fa-star-half star-2-half"></i> <i class="fa fa-star star-3-on"></i> <i class="fa fa-star star-off star-3-off"></i> <i class="fa fa-star-half star-3-half"></i> <i class="fa fa-star star-4-on"></i> <i class="fa fa-star star-off star-4-off"></i> <i class="fa fa-star-half star-4-half"></i> <i class="fa fa-star star-5-on"></i> <i class="fa fa-star star-off star-5-off"></i> <i class="fa fa-star-half star-5-half"></i> <!-- commented as we created half equivalent 5 star according to IMDB data <i class="fa fa-star star-6-on"></i> <i class="fa fa-star star-off star-6-off"></i> <i class="fa fa-star-half star-6-half"></i> <i class="fa fa-star star-7-on"></i> <i class="fa fa-star star-off star-7-off"></i> <i class="fa fa-star-half star-7-half"></i> <i class="fa fa-star star-8-on"></i> <i class="fa fa-star star-off star-8-off"></i> <i class="fa fa-star-half star-8-half"></i> <i class="fa fa-star star-9-on"></i> <i class="fa fa-star star-off star-9-off"></i> <i class="fa fa-star-half star-9-half"></i> <i class="fa fa-star star-10-on"></i> <i class="fa fa-star star-off star-10-off"></i> <i class="fa fa-star-half star-10-half"></i> --> </div> </div> <!-- end rating--> </div> <div class="col-xs-12 col-md-6"> <span>IMDB Votes-</span><span>> {{movie.imdbVotes}}</span> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div>
bhavindesai20/MovieBazar
public/templates/movie.html
HTML
mit
9,600
62.157895
186
0.383854
false
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CharCounterMain{ final static Charset enc = StandardCharsets.US_ASCII ; public CharCounterMain(String ch, String filedir){ if(ch.length() != 1){ System.out.println("The first argument needs to be a char, found string of length "+ch.length()); System.exit(1); } char c = ch.charAt(0); if( c != ' ' && c != '.' && Character.getNumericValue(c) < 97 && Character.getNumericValue(c) > 122 ){ //compare against the ascii integer values System.out.println("Need a character in range a-z (lowercase only) or a whitespace or a dot, found "+c+"!"); System.exit(1); } Path p = Paths.get(filedir); try { BufferedReader bf = Files.newBufferedReader(p,enc); String line; String line2 = null ; while((line = bf.readLine()) != null){ line2 += line ; } CharCounter cc = new CharCounter(c,line2); int freq = cc.getFrequency(); System.out.println(String.format("Frequency of character %c was %d", c,freq)); } catch (IOException e) { e.printStackTrace(); } System.out.println("Finished, exiting..."); } public static void main(String[] args){ if(args.length != 2){ System.out.println("Usage : CharCounterMain <char-to-look-for> <text-file-dir>"); }else{ new CharCounterMain(args[0],args[1]); } } }
dperezmavro/courseworks_uni
year_3/large_scale_and_distributed_systems/src/CharCounterMain.java
Java
mit
1,792
31.811321
154
0.56529
false
"use strict"; (function() { // "todos-angular" is just a hard-code id for storage var LOCAL_STORAGE_KEY = 'todos-angular'; var ENTER_KEY = 13; var ESC_KEY = 27; var internalFilters = { active: function(toDoItem) { return !toDoItem.completed; }, completed: function(toDoItem) { return toDoItem.completed; } }; angular.module('ToDoAngular', ['ngRoute']) .service('storage', function($q) { // Storage service return { save: function(toDoCollection) { localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(toDoCollection)); }, load: function() { var itemCollectionString = localStorage.getItem(LOCAL_STORAGE_KEY); return itemCollectionString && JSON.parse(itemCollectionString) || []; } } }) .directive('escHandler', function() { // Define directive for esc key return { restrict: 'A', link: function(scope, iElement, iAttrs) { function keyEventHandler(event) { if (event.keyCode === ESC_KEY) { scope.$apply(iAttrs.escHandler); } } iElement.on('keydown', keyEventHandler); scope.$on('$destroy', function() { iElement.off('keydown', keyEventHandler); }); } }; }) .directive('enterHandler', function() { // Define directive for enter key return { restrict: 'A', link: function (scope, iElement, iAttrs) { function keyEventHandler(event) { if (event.keyCode === ENTER_KEY) { scope.$apply(iAttrs.enterHandler); } } iElement.on('keydown', keyEventHandler); scope.$on('$destroy', function () { iElement.off('keydown', keyEventHandler); }); } }; }) .directive('selectAndFocus', function($timeout) { // Define directive for focus return { restrict: 'A', link: function(scope, iElement, iAttrs) { var focusPromise; scope.$watch(iAttrs.selectAndFocus, function(newValue) { if (newValue && !focusPromise) { focusPromise = $timeout(function focus() { focusPromise = null; iElement[0].focus(); }, 0, false); } }); scope.$on('$destroy', function() { if (focusPromise) { $timeout.cancel(focusPromise); focusPromise = null; } }); } }; }) .directive('toDoItem', function() { // Define directive for to-do item return { restrict: 'A', templateUrl: 'angular-item-template.html', scope: { itemViewModel: '=toDoItem' }, link: function (scope, iElement, iAttrs) { scope.editing = false; scope.originalTitle = ''; scope.$watch('itemViewModel.toDoItem.completed', function(newCompleted) { iElement.toggleClass('completed', newCompleted); }); scope.$watch('editing', function(newEditing) { iElement.toggleClass('editing', newEditing); }); scope.$watch('itemViewModel.isHidden', function(newHidden) { iElement.toggleClass('hidden', newHidden); }); scope.$watchGroup([ 'itemViewModel.toDoItem.title', 'itemViewModel.toDoItem.completed'], function() { scope.$emit('item-updated'); }); scope.destroy = function() { scope.$emit('remove-item', scope.itemViewModel); }; scope.edit = function() { scope.originalTitle = scope.itemViewModel.toDoItem.title; scope.editing = true; }; scope.update = function() { var title = scope.itemViewModel.toDoItem.title || ''; var trimmedTitle = title.trim(); if (scope.editing) { if (title !== trimmedTitle) { scope.itemViewModel.toDoItem.title = trimmedTitle; } if (!trimmedTitle) { scope.destroy(); } scope.editing = false; } }; scope.revert = function() { scope.editing = false; scope.itemViewModel.toDoItem.title = scope.originalTitle; }; } }; }) .controller('AppController', function AppController( $scope, $routeParams, storedToDoCollection, storage) { // Define app controller $scope.toDoCollection = storedToDoCollection.map(function(storedToDo) { return { toDoItem: storedToDo, isHidden: $scope.filter ? !$scope.filter(storedToDo): false }; }); $scope.currentTitle = ''; $scope.$on('$routeChangeSuccess', function() { var filterString = $routeParams.filter; if (filterString && (filterString in internalFilters)) { $scope.filterString = filterString; $scope.filter = internalFilters[filterString]; } else { $scope.filterString = ''; $scope.filter = null; } }); function save() { storage.save($scope.toDoCollection.map(function(toDoViewModel) { return toDoViewModel.toDoItem; })); } $scope.$watch('filter', function(newFilter) { $scope.toDoCollection.forEach(function(toDoViewModel) { toDoViewModel.isHidden = newFilter ? !newFilter(toDoViewModel.toDoItem) : false; }); }); $scope.$watch(function() { return $scope.toDoCollection.filter(function(toDoViewModel){ return !toDoViewModel.toDoItem.completed; }).length; }, function(newValue) { if (newValue == null) { $scope.remainingLabel = ''; } else { $scope.remainingLabel = newValue === 1 ? (newValue + ' item left') : (newValue + ' items left'); } }); $scope.$watchCollection('toDoCollection', function() { save(); }); $scope.$on('item-updated', function() { save(); }); $scope.$on('remove-item', function(scope, toDoViewModel) { for(var index = 0; index < $scope.toDoCollection.length; index++) { if ($scope.toDoCollection[index] === toDoViewModel) { $scope.toDoCollection.splice(index, 1); return; } } }); $scope.create = function() { var currentTitle = $scope.currentTitle.trim(); if (currentTitle) { var toDoItem = { title: currentTitle, completed: false }; var toDoItemViewModel = { toDoItem: toDoItem, isHidden: $scope.filter ? !$scope.filter(toDoItem): false }; $scope.toDoCollection.push(toDoItemViewModel); $scope.currentTitle = ''; } }; }) .config(function($routeProvider) { // Define routing var routeConfig = { controller: 'AppController', templateUrl: 'angular-app-template.html', resolve: { storedToDoCollection: function(storage) { return storage.load(); } } }; $routeProvider .when('/', routeConfig) .when('/:filter', routeConfig) .otherwise({ redirectTo: '/' }); }); })();
sasyomaru/advanced-javascript-training-material
module3/scripts/angular-app.js
JavaScript
mit
9,478
36.611111
100
0.420658
false
<?php namespace Params; /** * @codeCoverageIgnore */ trait SafeAccess { public function __set($name, $value) { throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't set it"); } public function __get($name) { throw new \Exception("Property [$name] doesn't exist for class [".get_class($this)."] so can't get it"); } }
Danack/Blog
vendor/danack/params/lib/Params/SafeAccess.php
PHP
mit
403
20.210526
112
0.595533
false
html{ height: 100%; margin: 0; background-color:#323232; } body{ font-family: 'Lato', sans-serif; font-size: 11pt; font-weight: 300; color: #C8C8C8 } ul { list-style: none; } a:link {color:#6c6c6c;} a:visited {color:#757575;} a:hover {color:white;} a:active {color:white;} .header{ text-align: center; padding-top: 10%; color: white; } .user_info{ text-align: center; padding-top: 1% } .profile_pic{ height: 25%; width: auto; } input:not([type=submit]):not([type=file]) { border: none; padding: 5px; background: rgba(255,255,255,0.08); margin: 0 0 10px 0; }
prinnb/cs242-final-project
restaurant/static/restaurant/account.css
CSS
mit
602
13
43
0.629568
false
from decimal import Decimal from django import forms from django.template.loader import render_to_string from django.template.defaultfilters import slugify class BaseWidget(forms.TextInput): """ Base widget. Do not use this directly. """ template = None instance = None def get_parent_id(self, name, attrs): final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) return final_attrs['id'] def get_widget_id(self, prefix, name, key=''): if self.instance: opts = self.instance._meta widget_id = '%s-%s-%s_%s-%s' % (prefix, name, opts.app_label, opts.module_name, self.instance.pk) else: widget_id = '%s-%s' % (prefix, name) if key: widget_id = '%s_%s' % (widget_id, slugify(key)) return widget_id def get_values(self, min_value, max_value, step=1): decimal_step = Decimal(str(step)) value = Decimal(str(min_value)) while value <= max_value: yield value value += decimal_step class SliderWidget(BaseWidget): """ Slider widget. In order to use this widget you must load the jQuery.ui slider javascript. This widget triggers the following javascript events: - *slider_change* with the vote value as argument (fired when the user changes his vote) - *slider_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('slider_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, default='', template='ratings/slider_widget.html', attrs=None): """ The argument *default* is used when the initial value is None. """ super(SliderWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.step = step self.instance = instance self.can_delete_vote = can_delete_vote self.read_only = read_only self.default = default self.template = template self.key = key def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value*, *step* and *value* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'default': self.default, 'parent': super(SliderWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'has_value': bool(value), 'slider_id': self.get_widget_id('slider', name, self.key), 'label_id': 'slider-label-%s' % name, 'remove_id': 'slider-remove-%s' % name, } def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context) class StarWidget(BaseWidget): """ Starrating widget. In order to use this widget you must download the jQuery Star Rating Plugin available at http://www.fyneworks.com/jquery/star-rating/#tab-Download and then load the required javascripts and css, e.g.:: <link href="/path/to/jquery.rating.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/path/to/jquery.MetaData.js"></script> <script type="text/javascript" src="/path/to/jquery.rating.js"></script> This widget triggers the following javascript events: - *star_change* with the vote value as argument (fired when the user changes his vote) - *star_delete* without arguments (fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('star_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=True, key='', read_only=False, template='ratings/star_widget.html', attrs=None): super(StarWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.step = step self.instance = instance self.can_delete_vote = can_delete_vote self.read_only = read_only self.template = template self.key = key def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value* and *step* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' split_value = int(1 / self.step) if split_value == 1: values = range(1, self.max_value+1) split = u'' else: values = self.get_values(self.min_value, self.max_value, self.step) split = u' {split:%d}' % split_value return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'step': str(self.step), 'can_delete_vote': self.can_delete_vote, 'read_only': self.read_only, 'values': values, 'split': split, 'parent': super(StarWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': self._get_value(value, split_value), 'star_id': self.get_widget_id('star', name, self.key), } def _get_value(self, original, split): if original: value = round(original * split) / split return Decimal(str(value)) def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context) class LikeWidget(BaseWidget): def __init__(self, min_value, max_value, instance=None, can_delete_vote=True, template='ratings/like_widget.html', attrs=None): super(LikeWidget, self).__init__(attrs) self.min_value = min_value self.max_value = max_value self.instance = instance self.can_delete_vote = can_delete_vote self.template = template def get_context(self, name, value, attrs=None): # here we convert *min_value*, *max_value* and *step* # to string to avoid odd behaviours of Django localization # in the template (and, for backward compatibility we do not # want to use the *unlocalize* filter) attrs['type'] = 'hidden' return { 'min_value': str(self.min_value), 'max_value': str(self.max_value), 'can_delete_vote': self.can_delete_vote, 'parent': super(LikeWidget, self).render(name, value, attrs), 'parent_id': self.get_parent_id(name, attrs), 'value': str(value), 'like_id': self.get_widget_id('like', name), } def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs or {}) return render_to_string(self.template, context)
redsolution/django-generic-ratings
ratings/forms/widgets.py
Python
mit
7,704
36.955665
109
0.591641
false
define(function() { return { draw: function(context, t) { var x = this.getNumber("x", t, 100), y = this.getNumber("y", t, 100), size = this.getNumber("size", t, 60), h = this.getNumber("h", t, 40), colorLeft = this.getColor("colorLeft", t, "#999999"), colorRight = this.getColor("colorRight", t, "#cccccc"), colorTop = this.getColor("colorTop", t, "#eeeeee"), scaleX = this.getNumber("scaleX", t, 1), scaleY = this.getNumber("scaleY", t, 1); context.translate(x, y); context.scale(scaleX, scaleY); if(h >= 0) { context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, -1); context.lineTo(0, size / 4 - 1); context.lineTo(-size / 2, -1); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorRight; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); } else { // clip path context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(-size / 2, 0); context.clip(); context.fillStyle = colorRight; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); } } } });
bit101/gifloopcoder
src/src/app/render/shapes/isobox.js
JavaScript
mit
2,755
28.611111
59
0.565517
false
<?php namespace BoundedContext\Contracts\Generator; use BoundedContext\Contracts\ValueObject\Identifier as IdentifierVO; interface Identifier extends ValueObject { /** * Generates a new random Identifier. * * @return IdentifierVO */ public function generate(); /** * Generates a null Identifier. * * @return IdentifierVO */ public function null(); /** * Generates a new Identifier from a string. * * @param string $identifier * @return IdentifierVO */ public function string($identifier); }
lyonscf/bounded-context
src/Contracts/Generator/Identifier.php
PHP
mit
587
17.935484
68
0.637138
false
<?php return array ( 'id' => 'softbank_v702nk2_ver1', 'fallback' => 'softbank_generic', 'capabilities' => array ( 'physical_screen_height' => '41', 'columns' => '15', 'physical_screen_width' => '34', 'max_image_width' => '176', 'rows' => '6', 'resolution_width' => '176', 'resolution_height' => '208', 'max_image_height' => '173', 'colors' => '262144', 'max_deck_size' => '357000', 'mms_max_size' => '307200', 'mms_max_width' => '640', 'mms_max_height' => '480', 'nokia_series' => '60', 'nokia_feature_pack' => '2', 'nokia_edition' => '2', 'model_name' => '702NKII(NOKIA 6680)', 'uaprof' => 'http://nds1.nds.nokia.com/uaprof/N6680r100-VFKK3G.xml', 'model_extra_info' => 'Vodafone', 'release_date' => '2005_may', 'directdownload_support' => 'true', 'oma_support' => 'true', 'aac' => 'true', 'mp3' => 'true', 'oma_v_1_0_separate_delivery' => 'true', 'flash_lite_version' => '', 'xhtml_file_upload' => 'supported', ), );
cuckata23/wurfl-data
data/softbank_v702nk2_ver1.php
PHP
mit
1,037
28.628571
72
0.532305
false
package com.company; import java.util.Scanner; public class Greeting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String firstName = scanner.nextLine(); String lastName = scanner.nextLine(); int age = Integer.parseInt(scanner.nextLine()); System.out.printf("Hello, %s %s. You are %d years old.", firstName, lastName, age); } }
ivelin1936/Studing-SoftUni-
Programming Fundamentals/DataTypesAndVariables-Lab/src/com/company/Greeting.java
Java
mit
419
26.933333
91
0.646778
false
package sbahjsic.runtime; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import sbahjsic.core.Warnings; import sbahjsic.core.Warnings.Level; import sbahjsic.runtime.Operator.BiOperator; import sbahjsic.runtime.Operator.UnOperator; import sbahjsic.runtime.Operator.VarargOperator; import sbahjsic.runtime.type.AnyType; import sbahjsic.runtime.type.SVoid; /** Describes a Sbahjsic type. * * <p>For all subclasses, there must only exist one instance. To enforce * this, this class implements final {@code equals()} and {@code hashCode()} * methods as they are defined in {@code Object}.*/ public abstract class Type { private final Map<String, Operator> operators = new HashMap<>(); private final Set<Type> supertypes = new HashSet<>(); private final Set<String> fields = new HashSet<>(); private final Map<String, Method> methods = new HashMap<>(); private int priority = 0; protected Type() { // Fixes a bug where AnyType tried to add AnyType.INSTANCE, which // was null at that point, to its own supertypes if(!getClass().equals(AnyType.class)) { addSupertype(AnyType.INSTANCE); } } /** Registers a new supertype for this type. * @param supertype the new supertype*/ public final void addSupertype(Type supertype) { if(getSupertypes().contains(supertype) || supertype.getSupertypes().contains(this)) { throw new RecursiveTypedefException(this.toString()); } if(this != supertype) { supertypes.add(supertype); } } /** Removes a supertype from this type if it exists. * @param supertype the supertype to remove*/ public final void removeSupertype(Type supertype) { supertypes.remove(supertype); } /** Registers an unary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addUnOperator(String op, UnOperator func) { operators.put(op, Operator.unaryOperator(func)); } /** Registers a binary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addBiOperator(String op, BiOperator func) { operators.put(op, Operator.binaryOperator(func)); } /** Adds an operator that can accept one or two arguments. * @param op the operator * @param unary the unary operator * @param binary the binary operator*/ protected final void addDoubleOperator(String op, UnOperator unary, BiOperator binary) { operators.put(op, (con, args) -> { if(args.length == 1) return unary.apply(con, args[0]); else if(args.length == 2) return binary.apply(con, args[0], args[1]); throw new OperatorCallException("Called with " + args.length + " arguments, expected 1 or 2"); }); } /** Registers a vararg operator for this type.*/ public void addVarargOperator(String op, VarargOperator func) { operators.put(op, Operator.varargOperator(func)); } /** Adds a field to this type. * @param field the field to add*/ protected final void addField(String field) { fields.add(field); } /** Returns a specific operator of this type. * @param op the operator to search * @return the operator matching {@code op} * @throws OperatorCallException if {@code op} isn't defined*/ public final Operator getOperator(String op) { if(operators.containsKey(op)) { return operators.get(op); } Operator operator = operatorLookup(op); if(operator == null) { throw new OperatorCallException("Operator " + op + " not defined on type " + getName()); } return operator; } private final Operator operatorLookup(String op) { for(Type supertype : supertypes) { if(supertype.operators.containsKey(op)) { return supertype.operators.get(op); } } for(Type supertype : supertypes) { Operator operator = supertype.operatorLookup(op); if(operator != null) { return operator; } } return null; } /** Returns a set of all defined operators of this type. * @return a set of the defined operators of this type*/ public final Set<String> getDefinedOperators() { Set<String> ops = new HashSet<>(); ops.addAll(operators.keySet()); for(Type supertype : getSupertypes()) { ops.addAll(supertype.getDefinedOperators()); } return ops; } /** Returns a set of the supertypes of this type. * @return a set of the supertypes of this type*/ public final Set<Type> getSupertypes() { Set<Type> types = new HashSet<>(); types.addAll(supertypes); for(Type supertype : supertypes) { types.addAll(supertype.getSupertypes()); } return types; } /** Returns the fields declared for this type. * @return a set of fields declared for this type*/ public final Set<String> getFields() { Set<String> allFields = new HashSet<>(); allFields.addAll(fields); for(Type supertype : getSupertypes()) { allFields.addAll(supertype.getFields()); } return allFields; } /** Adds a method to this type. * @param name the name of the method * @param method the method*/ public final void addMethod(String name, Method method) { methods.put(name, method); } /** Returns all methods defined for this type. * @return all methods defined for this type*/ public final Set<String> getMethods() { Map<String, Method> allMethods = new HashMap<>(); allMethods.putAll(methods); for(Type supertype : getSupertypes()) { allMethods.putAll(supertype.methods); } return allMethods.keySet(); } /** Returns a method of this type. * @param name the name of the method * @return the method * @throws MethodCallException if the method isn't defined for this type*/ public final Method getMethod(String name) { if(methods.containsKey(name)) { return methods.get(name); } Method method = methodLookup(name); if(method == null) { throw new MethodCallException("Method " + name + " not defined for type " + getName()); } return method; } private final Method methodLookup(String name) { for(Type supertype : supertypes) { if(supertype.methods.containsKey(name)) { return supertype.methods.get(name); } } for(Type supertype : supertypes) { Method method = supertype.methodLookup(name); if(method != null) { return method; } } return null; } /** Returns the name of this type. * @return the name of this type*/ public abstract String getName(); /** Casts a value to this type. * @param object the value to cast * @return the casted value*/ public SValue cast(SValue object) { Warnings.warn(Level.ADVICE, "Undefined cast from " + object.getType() + " to " + this); return object; } /** Returns whether this type is the subtype of some other type. That is * true if this type or any if its supertypes is the other type. * @param other the other type * @return whether this type is the subtype of the other type */ public boolean isSubtype(Type other) { return this.equals(other) || getSupertypes().contains(other); } /** Constructs an instance of this type * @param context the RuntimeContext * @param args the arguments passed to the constructor*/ public SValue construct(RuntimeContext context, SValue...args) { Warnings.warn(Level.NOTIFICATION, "Cannot instantiate " + getName()); return SVoid.VOID; } /** Returns the priority of this type, used to determine which operand * should choose the implementation of a binary operator. Defaults to zero.*/ public int priority() { return priority; } /** Sets the priority for this type.*/ public void setPriority(int p) { priority = p; } @Override public final boolean equals(Object o) { return super.equals(o); } @Override public final int hashCode() { return super.hashCode(); } @Override public final String toString() { return getName(); } }
expositionrabbit/Sbahjsic-runtime
src/sbahjsic/runtime/Type.java
Java
mit
7,839
27.717949
91
0.698941
false
{ "date": "2018-02-19", "type": "post", "title": "Report for Monday 19th of February 2018", "slug": "2018\/02\/19", "categories": [ "Daily report" ], "images": [], "health": { "weight": 79.6, "height": 173, "age": 13578 }, "nutrition": { "calories": 1939.89, "fat": 142.55, "carbohydrates": 101.78, "protein": 65.78 }, "exercise": { "pushups": 0, "crunches": 0, "steps": 12906 }, "media": { "books": [], "podcast": [], "youtube": [], "movies": [], "photos": [] } } Today I am <strong>13578 days</strong> old and my weight is <strong>79.6 kg</strong>. During the day, I consumed <strong>1939.89 kcal</strong> coming from <strong>142.55 g</strong> fat, <strong>101.78 g</strong> carbohydrates and <strong>65.78 g</strong> protein. Managed to do <strong>0 push-ups</strong>, <strong>0 crunches</strong> and walked <strong>12906 steps</strong> during the day which is approximately <strong>9.83 km</strong>.
aquilax/quantified.avtobiografia.com
content/post/2018-02-19.md
Markdown
mit
1,092
30.228571
438
0.53663
false
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for USN-2166-1 # # Security announcement date: 2014-04-14 00:00:00 UTC # Script generation date: 2017-01-01 21:03:46 UTC # # Operating System: Ubuntu 12.04 LTS # Architecture: x86_64 # # Vulnerable packages fix on version: # - libsnmp15:5.4.3~dfsg-2.4ubuntu1.2 # # Last versions recommanded by security team: # - libsnmp15:5.4.3~dfsg-2.4ubuntu1.3 # # CVE List: # - CVE-2012-6151 # - CVE-2014-2284 # - CVE-2014-2285 # - CVE-2014-2310 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo apt-get install --only-upgrade libsnmp15=5.4.3~dfsg-2.4ubuntu1.3 -y
Cyberwatch/cbw-security-fixes
Ubuntu_12.04_LTS/x86_64/2014/USN-2166-1.sh
Shell
mit
706
24.214286
72
0.689802
false
class Person < ActiveRecord::Base has_many :addresses, dependent: :destroy accepts_nested_attributes_for :addresses end
scotthelm/fencepost
spec/dummy/app/models/person.rb
Ruby
mit
125
24
42
0.776
false
import React from 'react'; import {connect} from 'cerebral-view-react'; import styles from './styles.css'; import { isObject, isArray, isString, isBoolean, isNumber, isNull } from 'common/utils'; import JSONInput from './JSONInput'; import connector from 'connector'; function isInPath(source, target) { if (!source || !target) { return false; } return target.reduce((isInPath, key, index) => { if (!isInPath) { return false; } return String(source[index]) === String(key); }, true); } function renderType(value, hasNext, path, propertyKey, highlightPath) { if (value === undefined) { return null; } if (isArray(value)) { return ( <ArrayValue value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } if (isObject(value)) { return ( <ObjectValue value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } return ( <Value value={value} hasNext={hasNext} path={path} propertyKey={propertyKey} highlightPath={highlightPath}/> ); } class ObjectValue extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props, context) { super(props); const numberOfKeys = Object.keys(props.value).length; const isHighlightPath = !!(this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path)); const preventCollapse = this.props.path.length === 0 && context.options.expanded; this.state = { isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true) }; this.onCollapseClick = this.onCollapseClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextState.isCollapsed !== this.state.isCollapsed || this.context.options.canEdit || nextProps.path !== this.props.path || nextProps.highlightPath !== this.props.highlightPath ); } componentWillReceiveProps(nextProps) { const context = this.context; const props = nextProps; const numberOfKeys = Object.keys(props.value).length; const isHighlightPath = !!(props.highlightPath && isInPath(props.highlightPath, props.path)); const preventCollapse = props.path.length === 0 && context.options.expanded; if (this.state.isCollapsed) { this.setState({ isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true) }); } } onExpandClick() { this.setState({isCollapsed: false}) } onCollapseClick() { this.setState({isCollapsed: true}); } renderProperty(key, value, index, hasNext, path) { this.props.path.push(key); const property = ( <div className={styles.objectProperty} key={index}> <div className={styles.objectPropertyValue}>{renderType(value, hasNext, path.slice(), key, this.props.highlightPath)}</div> </div> ); this.props.path.pop(); return property; } renderKeys(keys) { if (keys.length > 3) { return keys.slice(0, 3).join(', ') + '...' } return keys.join(', '); } render() { const {value, hasNext} = this.props; const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isCollapsed) { return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object} onClick={this.onExpandClick}> {this.props.propertyKey ? this.props.propertyKey + ': ' : null} <strong>{'{ '}</strong>{this.renderKeys(Object.keys(value))}<strong>{' }'}</strong> {hasNext ? ',' : null} </div> ); } else if (this.props.propertyKey) { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object}> <div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'{ '}</strong></div> {keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path))} <div><strong>{' }'}</strong>{hasNext ? ',' : null}</div> </div> ); } else { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightObject : styles.object}> <div onClick={this.onCollapseClick}><strong>{'{ '}</strong></div> {keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path, this.props.highlightPath))} <div><strong>{' }'}</strong>{hasNext ? ',' : null}</div> </div> ); } } } class ArrayValue extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props, context) { super(props); const numberOfItems = props.value.length; const isHighlightPath = this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path); this.state = { isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true }; this.onCollapseClick = this.onCollapseClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextState.isCollapsed !== this.state.isCollapsed || this.context.options.canEdit || nextProps.path !== this.props.path || nextProps.highlightPath !== this.props.highlightPath ); } componentWillReceiveProps(nextProps) { const context = this.context; const props = nextProps; const numberOfItems = props.value.length; const isHighlightPath = props.highlightPath && isInPath(props.highlightPath, props.path); if (this.state.isCollapsed) { this.setState({ isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true }); } } onExpandClick() { this.setState({isCollapsed: false}) } onCollapseClick() { this.setState({isCollapsed: true}); } renderItem(item, index, hasNext, path) { this.props.path.push(index); const arrayItem = ( <div className={styles.arrayItem} key={index}> {renderType(item, hasNext, path.slice())} </div> ); this.props.path.pop(); return arrayItem; } render() { const {value, hasNext} = this.props; const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isCollapsed) { return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array} onClick={this.onExpandClick}> {this.props.propertyKey ? this.props.propertyKey + ': ' : null} <strong>{'[ '}</strong>{value.length}<strong>{' ]'}</strong> {hasNext ? ',' : null} </div> ); } else if (this.props.propertyKey) { const keys = Object.keys(value); return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array}> <div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'[ '}</strong></div> {value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))} <div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div> </div> ); } else { return ( <div className={isExactHighlightPath ? styles.highlightArray : styles.array}> <div onClick={this.onCollapseClick}><strong>{'[ '}</strong></div> {value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))} <div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div> </div> ); } } } @connect() class Value extends React.Component { static contextTypes = { options: React.PropTypes.object.isRequired } constructor(props) { super(props); this.state = { isEditing: false, path: props.path.slice() }; this.onSubmit = this.onSubmit.bind(this); this.onBlur = this.onBlur.bind(this); this.onClick = this.onClick.bind(this); } shouldComponentUpdate(nextProps, nextState) { return ( nextProps.value !== this.props.value || nextState.isEditing !== this.state.isEditing || nextProps.path !== this.props.path ); } onClick() { this.setState({ isEditing: this.context.options.canEdit ? true : false }); } onSubmit(value) { this.props.signals.debugger.modelChanged({ path: this.state.path, value }) this.setState({isEditing: false}); connector.sendEvent('changeModel', { path: this.state.path, value: value }); } onBlur() { this.setState({isEditing: false}); } renderValue(value, hasNext) { const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path); if (this.state.isEditing) { return ( <div className={isExactHighlightPath ? styles.highlightValue : null}> {this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>} <span> <JSONInput value={value} onBlur={this.onBlur} onSubmit={this.onSubmit}/> </span> {hasNext ? ',' : null} </div> ); } else { return ( <div className={isExactHighlightPath ? styles.highlightValue : null}> {this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>} <span onClick={this.onClick}>{isString(value) ? '"' + value + '"' : String(value)}</span> {hasNext ? ',' : null} </div> ); } } render() { let className = styles.string; if (isNumber(this.props.value)) className = styles.number; if (isBoolean(this.props.value)) className = styles.boolean; if (isNull(this.props.value)) className = styles.null; return ( <div className={className}> {this.renderValue(this.props.value, this.props.hasNext)} </div> ); } } class Inspector extends React.Component { static childContextTypes = { options: React.PropTypes.object.isRequired } getChildContext() { return { options: { expanded: this.props.expanded || false, canEdit: this.props.canEdit || false } } } render() { return renderType(this.props.value, false, [], null, this.props.path); } } export default Inspector;
cerebral/cerebral-debugger-prototype
versions/v1/components/Debugger/Inspector/index.js
JavaScript
mit
10,888
31.020588
150
0.6212
false
// Package storagedatalake implements the Azure ARM Storagedatalake service API version 2019-10-31. // // Azure Data Lake Storage provides storage for Hadoop and other big data workloads. package storagedatalake // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" ) const ( // DefaultDNSSuffix is the default value for dns suffix DefaultDNSSuffix = "dfs.core.windows.net" ) // BaseClient is the base client for Storagedatalake. type BaseClient struct { autorest.Client XMsVersion string AccountName string DNSSuffix string } // New creates an instance of the BaseClient client. func New(xMsVersion string, accountName string) BaseClient { return NewWithoutDefaults(xMsVersion, accountName, DefaultDNSSuffix) } // NewWithoutDefaults creates an instance of the BaseClient client. func NewWithoutDefaults(xMsVersion string, accountName string, dNSSuffix string) BaseClient { return BaseClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), XMsVersion: xMsVersion, AccountName: accountName, DNSSuffix: dNSSuffix, } }
Azure/azure-sdk-for-go
services/storage/datalake/2019-10-31/storagedatalake/client.go
GO
mit
1,358
31.333333
99
0.783505
false
'use strict'; function valuefy(value) { if (typeof value !== 'object') { return (typeof value === 'string') ? `"${value}"` : value; } let values = []; if (Array.isArray(value)) { for (const v of value) { values.push(valuefy(v)); } values = `[${values.join(',')}]`; } else { for (let v in value) { if ({}.hasOwnProperty.call(value, v)) { values.push(`"${v}":${valuefy(value[v])}`); } } values = `{${values.join(',')}}`; } return values; } function serialize(target) { if (!target || typeof target !== 'object') { throw new TypeError('Invalid type of target'); } let values = []; for (let t in target) { if ({}.hasOwnProperty.call(target, t)) { values.push(`${t}=${valuefy(target[t])}`); } } return values; } function extract(t, outter, onlyContent) { const start = onlyContent ? 1 : 0; const pad = onlyContent ? 0 : 1; return t.slice(start, t.lastIndexOf(outter) + pad); } function objectify(v) { if (v[0] === '{') { return JSON.parse(extract(v, '}')); } else if (v[0] === '[') { const set = []; const es = extract(v, ']', true); if (es[0] === '[' || es[0] === '{') { set.push(objectify(es)); } else { for (const e of es.split(',')) { set.push(objectify(e)); } } return set; } else if (v[0] === '"') { v = extract(v, '"', true); } return v; } function deserialize(values) { if (!values) { throw new TypeError('Invalid type of values'); } else if (!Array.isArray(values)) { values = [values]; } const target = {}; for (const v of values) { const fieldValue = v.split('=', 2); target[fieldValue[0]] = objectify(fieldValue[1]); } return target; } module.exports = { pairify: serialize, parse: deserialize };
ragingwind/field-value
index.js
JavaScript
mit
1,725
17.75
60
0.564638
false
<?php namespace App\Notifications\Mship; use App\Notifications\Notification; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class ForgottenPasswordLink extends Notification implements ShouldQueue { use Queueable; private $token; /** * Create a new notification instance. * * @return void */ public function __construct($token) { parent::__construct(); $this->token = $token; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail', 'database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $subject = 'SSO Password Reset'; return (new MailMessage) ->from(config('mail.from.address'), 'VATSIM UK Web Services') ->subject($subject) ->view('emails.mship.security.reset_confirmation', ['subject' => $subject, 'recipient' => $notifiable, 'account' => $notifiable, 'token' => route('password.reset', $this->token)]); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return ['token' => $this->token]; } }
atoff/core
app/Notifications/Mship/ForgottenPasswordLink.php
PHP
mit
1,567
23.107692
192
0.610083
false
export default class TasksService { static async fetchTasks() { const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(1000); return [ { id: 0, description: "task1", status: "Active" }, { id: 1, description: "task2", status: "Active" }, ]; } }
guptag/js-frameworks
React/examples/hello-world/src/data/TasksService.js
JavaScript
mit
308
24.666667
76
0.587662
false
// // GUISlider.h // GUIPlayerView // // Created by Guilherme Araújo on 08/12/14. // Copyright (c) 2014 Guilherme Araújo. All rights reserved. // #import <UIKit/UIKit.h> @interface GUISlider : UISlider - (void)setSecondaryValue:(float)value; - (void)setSecondaryTintColor:(UIColor *)tintColor; @property (nonatomic, retain) NSNumber * thick; @end @interface GUISlider (extra) @property(nonatomic, assign) NSNumber* thickNess; @end
tthufo/THPod
THPod/Classes/GUISlider.h
C
mit
446
16.76
61
0.722973
false
#ifndef RUBY_EXT_UTILS_HPP_ #define RUBY_EXT_UTILS_HPP_ 1 #include <functional> #include <ruby.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <typeinfo> #ifdef __GNUC__ #include <cxxabi.h> #endif template <typename T> static const char * type_name() { #ifdef __GNUC__ const int buf_size = 32; static char tname[buf_size]; if (tname[0] != 0) { return tname; } const std::type_info& id = typeid(T); int status; char *name = abi::__cxa_demangle(id.name(), NULL, 0, &status); if (name != NULL) { if (status == 0) { strncpy(tname, name, buf_size - 1); } else { strncpy(tname, id.name(), buf_size - 1); } free(name); } return tname; #else return typeid(T).name(); #endif } /* * undefined reference to ... [g++ (tdm-1) 4.5.2] */ // template<typename T> // static void // tmp_obj_free(T ptr) // { // if (ptr) { // delete ptr; // } // } // template<typename T> // static void // tmp_ary_free(T ptr) // { // if (ptr) { // delete[] ptr; // } // } template<typename T> static void tmp_obj_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete obj; } } template<typename T> static void tmp_ary_free(void *ptr) { if (ptr) { T obj = static_cast<T>(ptr); delete[] obj; } } template<typename T> static inline VALUE wrap_tmp_obj(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_obj_free<T>, ptr); } template<typename T> static inline VALUE wrap_tmp_ary(T ptr) { return Data_Wrap_Struct(rb_cObject, 0, tmp_ary_free<T>, ptr); } void delete_tmp_obj(volatile VALUE *store); #define delete_tmp_ary(x) delete_tmp_obj(x) /* * http://masamitsu-murase.blogspot.jp/2013/12/sevenzipruby-2-c-ruby.html */ extern "C" VALUE rxu_run_functor(VALUE p); #define RXU_PROTECT_FUNC(func) ((VALUE (*)(VALUE))(func)) template<typename T> static inline VALUE _rb_protect(T func, int *state) { typedef std::function<VALUE ()> func_type; func_type f = func; return rb_protect(rxu_run_functor, reinterpret_cast<VALUE>(&f), state); } template<typename T1, typename T2> static inline VALUE _rb_rescue(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } #if defined(_MSC_VER) && _MSC_VER <= 1800 template<VALUE& e1, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<VALUE& e1, VALUE& e2, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<VALUE& e1, VALUE& e2, VALUE& e3, VALUE& e4, VALUE& e5, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } #else template<VALUE&... exceptions, typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), exceptions..., NULL); } #endif template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, NULL); } template<typename T1, typename T2> static inline VALUE _rb_rescue2(T1 func1, T2 func2, VALUE e1, VALUE e2, VALUE e3, VALUE e4, VALUE e5) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_rescue2( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2), e1, e2, e3, e4, e5, NULL); } template<typename T1, typename T2> static inline VALUE _rb_ensure(T1 func1, T2 func2) { typedef std::function<VALUE ()> func_type; func_type f1 = func1; func_type f2 = func2; return rb_ensure( RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f1), RUBY_METHOD_FUNC(rxu_run_functor), reinterpret_cast<VALUE>(&f2)); } extern "C" int rxu_run_functor_foreach(VALUE key, VALUE val, VALUE p); #define RXU_FOREACH_FUNC(func) ((int (*)(ANYARGS))(func)) template<typename T> static inline void _rb_hash_foreach(VALUE obj, T func) { typedef std::function<int (VALUE, VALUE)> func_type; func_type f = func; rb_hash_foreach(obj, RXU_FOREACH_FUNC(rxu_run_functor_foreach), reinterpret_cast<VALUE>(&f)); } #endif /* RUBY_EXT_UTILS_HPP_ */
yagisumi/ruby-gdiplus
ext/gdiplus/ruby_ext_utils.hpp
C++
mit
8,156
26.647458
103
0.623222
false
/** * Vasya Hobot * * Copyright (c) 2013-2014 Vyacheslav Slinko * Licensed under the MIT License */ function Message(chat, body) { this._chat = chat; this._body = body; } Message.prototype.getChat = function() { return this._chat; }; Message.prototype.getBody = function() { return this._body; }; module.exports = Message;
vslinko-archive/vasya-hobot
src/client/api/Message.js
JavaScript
mit
351
13.625
44
0.646724
false
<?php namespace PLL\SocialBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Translation\TranslatorInterface; class PostType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('content', TextareaType::class, array( 'required' => true, 'label' => false, )) ->add('save', SubmitType::class, array( 'label' => 'timelinepost.label.post', 'translation_domain' => 'forms', 'attr' => array( 'class' => 'post-btn w3-btn w3-theme', ) )) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'PLL\SocialBundle\Entity\Post' )); } } ?>
Kishlin/Ehub
src/PLL/SocialBundle/Form/Type/PostType.php
PHP
mit
1,072
26.512821
73
0.640858
false
package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Random; /** * Created by Vlady on 22.10.2015. */ /** * Данный класс реализует отрисовку астероидов */ public class Asteroid { Bitmap bitmap; /** * Координаты первого астероида */ private int line1x; private int line1y; /** * Координаты второго астероида */ private int line2x; private int line2y; /** * Координаты третьего астероида */ private int line3x; private int line3y; private Random random; /** * Конструктор получающий объект картинки будущего астероида и * задающий астероидам рандомные координаты * @param bmp - объект картинки астероида */ public Asteroid(Bitmap bmp){ this.bitmap = bmp; random = new Random(); line1x = random.nextInt(880); line2x = random.nextInt(880); line3x = random.nextInt(880); line1y = -random.nextInt(300); line2y = -random.nextInt(300) - 400; // За пределом экрана минус 400 line3y = -random.nextInt(300) - 800; // За пределом экрана минус 800 } /** * Метод отрисовки астероидов * @param canvas - прямоугольная область экрана для рисования */ public void draw(Canvas canvas){ canvas.drawBitmap(bitmap, line1x, line1y, null); // Первая линия canvas.drawBitmap(bitmap, line2x, line2y, null); // Вторая линия canvas.drawBitmap(bitmap, line3x, line3y, null); // Третья линия } /** * Метод обновляющий координаты астероидов и задающий новые координаты при уплытии за границы фона */ public void update(){ if(line1y > 1400) { line1y = -80; line1x = random.nextInt(880); } else if(line2y > 1400) { line2y = -80; line2x = random.nextInt(880); } else if(line3y > 1400) { line3y = -80; line3x = random.nextInt(880); } line1y += GamePanel.speed; line2y += GamePanel.speed; line3y += GamePanel.speed; } /* * Методы возвращают прямоугольную область астероида по его координатам, для проверки столкновения с кораблем * Реализацию можно было уместить в один метод с четырьмя параметрами, но его вызов был бы нечитаемым * Поскольку присутствуют всего три астероида, мы имеем возможность сделать для каждого свой метод */ public Rect getAsteroid1(){ return new Rect(line1x, line1y, line1x + 100, line1y + 120); } public Rect getAsteroid2(){ return new Rect(line2x, line2y, line2x + 100, line2y + 120); } public Rect getAsteroid3(){ return new Rect(line3x, line3y, line3x + 100, line3y + 120); } }
vladb55/SeptemberRepository
app/src/main/java/septemberpack/september/Asteroid.java
Java
mit
3,547
25.783019
112
0.621698
false
import React from 'react'; import { shallow } from 'enzyme'; import UserProfile from '../UserProfile'; import Wrapper from '../Wrapper'; describe('<UserProfile />', () => { it('should render <Wrapper />', () => { const wrapper = shallow(<UserProfile />); expect(wrapper.find(Wrapper).length).toEqual(1); }); });
on3iro/Gloomhaven-scenario-creator
src/containers/Auth/tests/UserProfile.test.js
JavaScript
mit
327
24.153846
52
0.633028
false
class CreateWriMetadataSources < ActiveRecord::Migration[5.1] def change create_table :wri_metadata_sources do |t| t.text :name t.timestamps end end end
Vizzuality/climate-watch
db/migrate/20171016113108_create_wri_metadata_sources.rb
Ruby
mit
177
21.125
61
0.689266
false
## Examples: **As filters:** ```twig {{ subject | preg_filter(pattern, replacement, limit) }} {{ subject | preg_grep(pattern) }} {{ subject | preg_match(pattern) }} {{ subject | preg_quote(delimiter) }} {{ subject | preg_replace(pattern, replacement, limit) }} {{ subject | preg_split(pattern) }} ``` **As functions:** ```twig {{ preg_filter(subject, pattern, replacement, limit) }} {{ preg_grep(subject, pattern) }} {{ preg_match(subject, pattern) }} {{ preg_quote(subject, delimiter) }} {{ preg_replace(subject, pattern, replacement, limit) }} {{ preg_split(subject, pattern) }} ``` Please read the PHP docs for a more detailed explanation of all functions. **Usage Examples:** *Simple Word Replacement* ```twig {{ "This is a simple example." | preg_replace('/simple/', 'beautiful') }} ``` will output: ```twig This is a beautiful example. ``` *Whitespace cleaning up (Specifically from the results of a Twig macro)* ```twig {% macro generateItemUrl(item, falseLink) %} {% if (falseLink) or item.url is empty %} # {% else %} {{ item.url }} {% endif %} {% endmacro %} <a href="{{ _self.generateItemUrl(item, false) | preg_replace('/\\s+/', ' ') | trim | raw }}">{{ item.name }}</a> ```
LukeTowers/oc-queencityhack2k17-site
plugins/luketowers/twigpcre/DOCUMENTATION.md
Markdown
mit
1,210
20.245614
113
0.638843
false
<ul class="menu-item"> <li class="home"><a href="/">{{ site.title }}</a></li> {% for link in site.data.navigation %} {% if link.url_en contains 'http' %} {% assign domain = '' %} {% else %} {% assign domain = site.url_en %} {% endif %} <li><a href="{{ domain }}{{ link.url_en }}" {% if link.url contains 'http' %}target="_blank"{% endif %}>{{ link.title_en }}</a></li> {% endfor %} </ul>
TsinStudio/tsinstudio.github.com
_includes/navigation_en.html
HTML
mit
427
37.909091
136
0.505855
false
<?php namespace Davidsneal\MaxCDN\OAuth; class OAuthDataStore { function lookup_consumer($consumer_key) { // implement me } function lookup_token($consumer, $token_type, $token) { // implement me } function lookup_nonce($consumer, $token, $nonce, $timestamp) { // implement me } function new_request_token($consumer, $callback = null) { // return a new token attached to this consumer } function new_access_token($token, $consumer, $verifier = null) { // return a new access token attached to this consumer // for the user associated with this token if the request token // is authorized // should also invalidate the request token } }
davidsneal/laravel-maxcdn
src/MaxCDN/OAuth/OAuthDataStore.php
PHP
mit
747
24.758621
71
0.631861
false
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookCell.js'; import User from './User.js'; import DoneFooter from './DoneFooter.js'; import Icon from 'react-native-vector-icons/Ionicons'; const LookDetail = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}), comments: [], next:true, pageNo:1, animating:true }; }, getDefaultProps() { return { look:{}, navigator:"", }; }, componentWillMount() { this.queryRromServer(1); }, getDataSource(comments) { // return false; return this.state.dataSource.cloneWithRows(comments); }, renderFooter() { if (!this.state.next) { return ( <DoneFooter/> ); } return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>; }, renderHeader() { return ( <LookCell look={this.props.look} navigator={this.props.navigator} onSelect={function(){}} userCell={true} /> ); }, onEndReached() { if(this.props.look.comments_count==0){ this.setState({ next:false, }); return; } if (this.state.next && !this.state.animating) { this.setState({ animating: true }); this.queryRromServer(this.state.pageNo); } }, onSelectUser(user) { this.props.navigator.push({ component: User, title: user.name, backButtonTitle:' ', passProps: { user:user, navigator:this.props.navigator, }, }); }, // shouldComponentUpdate: function(nextProps, nextState) { // console.log('LookDetail.js.js-shouldComponentUpdate'); // return JSON.stringify(nextState)!=JSON.stringify(this.state); // }, renderRow(comments) { if(!comments.comment||!comments.comment.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> <View style={styles.commentBody}> <View style={styles.commentHeader}> <View style={{flex:1}}> <Text style={styles.userName}>{comments.comment.user.name}</Text> </View> <View style={styles.timeView}> <Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/> <Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text> </View> </View> <Text style={styles.commentText}>{comments.comment.body}</Text> </View> </TouchableOpacity> ); }, render() { console.log(new Date()-0); console.log('LookDetail.js.js-render'); return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} onEndReached={this.onEndReached} renderHeader={this.renderHeader} renderFooter={this.renderFooter} onEndReachedThreshold={10} automaticallyAdjustContentInsets={false} keyboardDismissMode='on-drag' keyboardShouldPersistTaps={false} showsVerticalScrollIndicator={true} style={styles.container} /> ); }, queryRromServer(page) { globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults); }, processsResults(data) { if (!data||!data.comments||!data.comments.length) { this.setState({ animating: false, next:false, }); return; } var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ comments: newComments, animating: false, dataSource: this.getDataSource(newComments), pageNo: this.state.pageNo+1, next:next, }); } }); const styles = StyleSheet.create({ container: { paddingTop: 64, backgroundColor: globalVariables.background, }, flexContainer: { opacity:0.97, padding: 10, flexDirection: 'row', justifyContent: 'flex-start', }, commentBody: { flex: 1, flexDirection: "column", justifyContent: "center", }, commentHeader: { flexDirection: "row", alignItems: "flex-start" }, userName: { color:globalVariables.base, // fontSize:12, }, timeView:{ // width:50, flexDirection: "row", alignItems:'center', marginRight:5, }, time:{ color:globalVariables.textBase, fontSize:12, // , }, commentText: { // fontSize:12, marginTop:8, flexDirection: "row", color:globalVariables.textBase, }, avatar: { borderRadius: 18, width: 36, height: 36, marginRight: 10, marginLeft: 5, backgroundColor:globalVariables.textBase2, }, scrollSpinner: { marginVertical: 20, }, }); export default LookDetail;
rollo-zhou/look
src/components/LookDetail.js
JavaScript
mit
5,317
23.730233
130
0.618394
false
#!/usr/bin/env python import sys import os from treestore import Treestore try: taxonomy = sys.argv[1] except: taxonomy = None t = Treestore() treebase_uri = 'http://purl.org/phylo/treebase/phylows/tree/%s' tree_files = [x for x in os.listdir('trees') if x.endswith('.nex')] base_uri = 'http://www.phylocommons.org/trees/%s' tree_list = set(t.list_trees()) for tree_uri in tree_list: if not 'TB2_' in tree_uri: continue tree_id = t.id_from_uri(tree_uri) tb_uri = treebase_uri % (tree_id.replace('_', ':')) print tree_id, tb_uri t.annotate(tree_uri, annotations='?tree bibo:cites <%s> .' % tb_uri)
NESCent/phylocommons
tools/treebase_scraper/annotate_trees.py
Python
mit
622
27.272727
72
0.663987
false
<?php /** * This file belongs to the AnoynmFramework * * @author vahitserifsaglam <vahit.serif119@gmail.com> * @see http://gemframework.com * * Thanks for using */ namespace Anonym\Facades; use Anonym\Patterns\Facade; /** * Class Validation * @package Anonym\Facades */ class Validation extends Facade { /** * return the validation facade * * @return string */ protected static function getFacadeClass(){ return 'validation'; } }
AnonymPHP/Anonym-Library
src/Anonym/Facades/Validation.php
PHP
mit
487
13.757576
54
0.646817
false
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Java Service Provider. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <jre@trifork.com> * Rolf Njor Jensen <rolf@trifork.com> * Aage Nielsen <ani@openminds.dk> * */ package dk.itst.oiosaml.sp.service; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dk.itst.oiosaml.logging.Logger; import dk.itst.oiosaml.logging.LoggerFactory; import org.apache.commons.configuration.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.xml.ConfigurationException; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.configuration.FileConfiguration; import dk.itst.oiosaml.configuration.SAMLConfiguration; import dk.itst.oiosaml.configuration.SAMLConfigurationFactory; import dk.itst.oiosaml.error.Layer; import dk.itst.oiosaml.error.WrappedException; import dk.itst.oiosaml.logging.Audit; import dk.itst.oiosaml.logging.Operation; import dk.itst.oiosaml.sp.UserAssertion; import dk.itst.oiosaml.sp.UserAssertionHolder; import dk.itst.oiosaml.sp.bindings.BindingHandler; import dk.itst.oiosaml.sp.develmode.DevelMode; import dk.itst.oiosaml.sp.develmode.DevelModeImpl; import dk.itst.oiosaml.sp.metadata.CRLChecker; import dk.itst.oiosaml.sp.metadata.IdpMetadata; import dk.itst.oiosaml.sp.metadata.SPMetadata; import dk.itst.oiosaml.sp.service.session.Request; import dk.itst.oiosaml.sp.service.session.SessionCleaner; import dk.itst.oiosaml.sp.service.session.SessionHandler; import dk.itst.oiosaml.sp.service.session.SessionHandlerFactory; import dk.itst.oiosaml.sp.service.util.Constants; /** * Servlet filter for checking if the user is authenticated. * * <p> * If the user is authenticated, a session attribute, * {@link Constants#SESSION_USER_ASSERTION} is set to contain a * {@link UserAssertion} representing the user. The application layer can access * this object to retrieve SAML attributes for the user. * </p> * * <p> * If the user is not authenticated, a &lt;AuthnRequest&gt; is created and sent * to the IdP. The protocol used for this is selected automatically based on th * available bindings in the SP and IdP metadata. * </p> * * <p> * The atual redirects are done by {@link BindingHandler} objects. * </p> * * <p> * Discovery profile is supported by looking at a request parameter named * _saml_idp. If the parameter does not exist, the browser is redirected to * {@link Constants#DISCOVERY_LOCATION}, which reads the domain cookie. If the * returned value contains ids, one of the ids is selected. If none of the ids * in the list is registered, an exception is thrown. If no value has been set, * the first configured IdP is selected automatically. * </p> * * @author Joakim Recht <jre@trifork.com> * @author Rolf Njor Jensen <rolf@trifork.com> * @author Aage Nielsen <ani@openminds.dk> */ public class SPFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(SPFilter.class); private CRLChecker crlChecker = new CRLChecker(); private boolean filterInitialized; private SAMLConfiguration conf; private String hostname; private SessionHandlerFactory sessionHandlerFactory; private AtomicBoolean cleanerRunning = new AtomicBoolean(false); private DevelMode develMode; /** * Static initializer for bootstrapping OpenSAML. */ static { try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { throw new WrappedException(Layer.DATAACCESS, e); } } public void destroy() { SessionCleaner.stopCleaner(); crlChecker.stopChecker(); if (sessionHandlerFactory != null) { sessionHandlerFactory.close(); } SessionHandlerFactory.Factory.close(); } /** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is * sent to the Login Site. * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("OIOSAML-J SP Filter invoked"); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); return; } } if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warn("Running in debug mode, skipping regular filter"); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration()); return; } if (cleanerRunning.compareAndSet(false, true)) { SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath().equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) { log.debug("Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebugEnabled()) log.debug("sessionId....:" + session.getId()); Boolean forceAuthn = false; if(request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN)) { String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN); forceAuthn = forceAuthnAsString.toLowerCase().equals("true"); } // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL); if ((actualAssuranceLevel > 0) && (actualAssuranceLevel < assuranceLevel)) { sessionHandler.logOut(session); log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebugEnabled()) log.debug("Everything is ok... Assertion: " + ua); Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest); } } protected void saveRequestAndGotoLogin(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException { SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(request)); String protocol = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL, "saml20"); String loginUrl = conf.getSystemConfiguration().getString(Constants.PROP_SAML_SERVLET, "/saml"); String protocolUrl = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL + "." + protocol); if (protocolUrl == null) { throw new RuntimeException("No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol); } loginUrl += protocolUrl; if (log.isDebugEnabled()) log.debug("Redirecting to " + protocol + " login handler at " + loginUrl); RequestDispatcher dispatch = request.getRequestDispatcher(loginUrl); dispatch.forward(new SAMLHttpServletRequest(request, hostname, relayState), response); } public void init(FilterConfig filterConfig) throws ServletException { conf = SAMLConfigurationFactory.getConfiguration(); if (conf.isConfigured()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) { develMode = new DevelModeImpl(); setConfiguration(conf); setFilterInitialized(true); return; } setRuntimeConfiguration(conf); setFilterInitialized(true); return; } catch (IllegalStateException e) { log.error("Unable to configure", e); } } setFilterInitialized(false); } private void setRuntimeConfiguration(Configuration conf) { restartCRLChecker(conf); setFilterInitialized(true); setConfiguration(conf); if (!IdpMetadata.getInstance().enableDiscovery()) { log.info("Discovery profile disabled, only one metadata file found"); } else { if (conf.getString(Constants.DISCOVERY_LOCATION) == null) { throw new IllegalStateException("Discovery location cannot be null when discovery profile is active"); } } setHostname(); sessionHandlerFactory = SessionHandlerFactory.Factory.newInstance(conf); sessionHandlerFactory.getHandler().resetReplayProtection(conf.getInt(Constants.PROP_NUM_TRACKED_ASSERTIONIDS)); log.info("Home url: " + conf.getString(Constants.PROP_HOME)); log.info("Assurance level: " + conf.getInt(Constants.PROP_ASSURANCE_LEVEL)); log.info("SP entity ID: " + SPMetadata.getInstance().getEntityID()); log.info("Base hostname: " + hostname); } private void setHostname() { String url = SPMetadata.getInstance().getDefaultAssertionConsumerService().getLocation(); setHostname(url.substring(0, url.indexOf('/', 8))); } private void restartCRLChecker(Configuration conf) { crlChecker.stopChecker(); int period = conf.getInt(Constants.PROP_CRL_CHECK_PERIOD, 600); if (period > 0) { crlChecker.startChecker(period, IdpMetadata.getInstance(), conf); } } public void setHostname(String hostname) { this.hostname = hostname; } public void setFilterInitialized(boolean b) { filterInitialized = b; } public boolean isFilterInitialized() { return filterInitialized; } public void setConfiguration(Configuration configuration) { SAMLConfigurationFactory.getConfiguration().setConfiguration(configuration); conf = SAMLConfigurationFactory.getConfiguration(); } public void setSessionHandlerFactory(SessionHandlerFactory sessionHandlerFactory) { this.sessionHandlerFactory = sessionHandlerFactory; } public void setDevelMode(DevelMode develMode) { this.develMode = develMode; } }
Safewhere/kombit-web-java
Kombit.Samples.CH.WebsiteDemo/src/java/dk/itst/oiosaml/sp/service/SPFilter.java
Java
mit
12,213
38.524272
141
0.756489
false
{% extends 'swp/base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="page-header"> <h1>{{ event.title }}</h1> </div> {% if user.is_authenticated %} <form action="{% url 'new_event' event.slug.hex %}" method="POST" enctype="multipart/form-data" class="form-inline" > {% csrf_token %} <div class="form-group"> <input type="text" name="caption" value="" placeholder="Caption" required="required" class="form-control" autocomplete="off" /> </div> <div class="form-group"> <label for="new-photo-original">Original</label> <input id="new-photo-original" type="file" name="original" required="required" class="form-control" /> </div> <div class="form-group"> <label for="new-photo-enhanced">Enhanced (optional)</label> <input id="new-photo-enhanced" type="file" name="enhanced" class="form-control" /> </div> <button type="submit" class="btn btn-primary">Upload</button> </form> {% endif %} <div class="row"> {% for photo in photos %} <div class="col-xs-12 col-md-4"> <a href="#" data-toggle="modal" data-target="#swp-all-images-dialog" ><img src="{% static photo.image.thumbnail_path %}" alt="{{ photo.caption }}" class="swp-thumbnail" /></a> <br/> {% if user.is_authenticated %} {% if photo.enhanced %} <div class="btn-group" role="group"> <a href="{% url 'original_file' photo.original.slug.hex %}" role="button" class="btn btn-default btn-sm" >Original</a> <a href="{% url 'original_file' photo.enhanced.slug.hex %}" role="button" class="btn btn-default btn-sm" >Full resolution</a> </div> {% else %} <a href="{% url 'original_file' photo.original.slug.hex %}" role="button" class="btn btn-default btn-sm" >Full resolution</a> {% endif %} {% endif %} </div> {% endfor %} </div> </div> <div class="modal fade" id="swp-all-images-dialog" tabindex="-1" role="dialog" > <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" ><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Image Slideshow</h4> </div> <div class="modal-body"> <div id="swp-all-images-carousel" class="carousel slide" data-ride="carousel" data-interval="false" > <!-- Indicators --> <ol class="carousel-indicators"> {% for photo in photos %} <li data-target="SWPCarousel" data-slide-to="{{ forloop.counter0 }}" {% if forloop.counter0 == 0 %} class="active" {% endif %} ></li> {% endfor %} </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for photo in photos %} <div class="item {% if forloop.counter0 == 0 %}active{% endif %}" > <img src="{% static photo.image.image_path %}" class="swp-carousel-image" alt="{{ photo.caption }}" /> <div class="carousel-caption"> <h3>{{ photo.caption }}</h3> </div> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#swp-all-images-carousel" role="button" data-slide="prev" > <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" ></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#swp-all-images-carousel" role="button" data-slide="next" > <span class="glyphicon glyphicon-chevron-right" aria-hidden="true" ></span> <span class="sr-only">Next</span> </a> </div> </div> </div> </div> </div> {% endblock %}
merry-bits/SWP
swp/templates/swp/event.html
HTML
mit
4,577
30.349315
76
0.486126
false
package queier import ( "github.com/julienschmidt/httprouter" "net/http" "encoding/json" "fmt" "strconv" "broker-gateway/entities" "github.com/satori/go.uuid" ) type Router interface { Start(port int) } type router struct { q Querier http *httprouter.Router } func NewRouter(q Querier) Router { r := httprouter.New() rte:= &router{ q: q, http: r, } rte.register() return rte } func (rte *router)futures(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { futures := rte.q.Futures() echo(w, futures) } // //func (rte *router)ordersByFirmId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // orders := rte.q.Orders(firmId) // res, err := json.Marshal(orders) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router)ordersByFirmIdAndId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // order := rte.q.OrderById(firmId,ps.ByName("id")) // res, err := json.Marshal(order) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router) consignations(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // rtn := rte.q.Consignations(firmId) // res, err := json.Marshal(rtn) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router)consignationsByFirmIdAndId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // firmId,_ := strconv.Atoi(ps.ByName("firmId")) // order := rte.q.ConsignationById(firmId,ps.ByName("id")) // res, err := json.Marshal(order) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} // //func (rte *router)quotationsByFutureId(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { // futureId,_ := strconv.Atoi(ps.ByName("id")) // rtn := rte.q.Quotations(futureId) // res, err := json.Marshal(rtn) // if err != nil { // fmt.Println(err) // } // w.Write(res) //} func echo(w http.ResponseWriter, entity interface{}) { if entity == nil { w.Write([]byte("{}")) return } res, err := json.Marshal(entity) if err != nil { fmt.Println(err) } w.Header().Set("Access-Control-Allow-Origin","*") w.Write(res) } func (rte *router) register() { // For firm rte.http.GET("/futures",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { futures := rte.q.Futures() echo(w, futures) }) rte.http.GET("/futures/:id", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("id")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.Quotations(id,limit,offset)) }) rte.http.GET("/firms/:firmId/orders", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("firmId")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) res := rte.q.Orders(id,limit,offset) for i:=0;i<len(res) ;i++ { res[i] = entities.TransformForFirm(res[i],id) } echo(w,res) }) rte.http.GET("/firms/:firmId/orders/:id",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmid,_ := strconv.Atoi(p.ByName("firmId")) res := rte.q.OrderById(firmid, p.ByName("id")) if uuid.Equal(res.ID,uuid.FromBytesOrNil(nil)) { echo(w, nil) } else { echo(w,res) } }) rte.http.GET("/firms/:firmId/consignations",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { id,_ := strconv.Atoi(p.ByName("firmId")) limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) res := rte.q.Consignations(id,limit,offset) echo(w,res) }) rte.http.GET("/firms/:firmId/consignations/:id",func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmid,_ := strconv.Atoi(p.ByName("firmId")) res := rte.q.ConsignationById(firmid, p.ByName("id")) if uuid.Equal(res.ID,uuid.FromBytesOrNil(nil)) { echo(w, nil) } else { echo(w,res) } }) // For admin rte.http.GET("/admin/orders", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.AllOrders(limit,offset)) }) rte.http.GET("/admin/consignations", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { limit,_ := strconv.Atoi(h.URL.Query().Get("limit")) offset,_ := strconv.Atoi(h.URL.Query().Get("offset")) echo(w,rte.q.AllConsignations(limit,offset)) }) rte.http.PUT("/admin/commissions/:id", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmId,_ :=strconv.Atoi(h.URL.Query().Get("firmId")) futureId,_ := strconv.Atoi(h.URL.Query().Get("futureId")) orderType,_ := strconv.Atoi(h.URL.Query().Get("orderType")) percent,_ := strconv.Atoi(h.URL.Query().Get("percent")) id,_ := strconv.Atoi(p.ByName("id")) comm := entities.Commission{ ID: id, FirmId: firmId, FutureId: futureId, OrderType: orderType, CommissionPercent: percent, } rte.q.Save(&comm) echo(w, comm) }) rte.http.GET("/admin/commissions", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { var res []entities.Commission rte.q.Query().Find(&res) echo(w, res) }) rte.http.POST("/admin/commissions", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { firmId,_ :=strconv.Atoi(h.URL.Query().Get("firmId")) futureId,_ := strconv.Atoi(h.URL.Query().Get("futureId")) orderType,_ := strconv.Atoi(h.URL.Query().Get("orderType")) id,_ := strconv.Atoi(p.ByName("id")) percent,_ := strconv.Atoi(h.URL.Query().Get("percent")) comm := entities.Commission{ ID: id, FirmId: firmId, FutureId: futureId, OrderType: orderType, CommissionPercent: percent, } rte.q.Save(&comm) echo(w, comm) }) rte.http.GET("/admin/firmFutures", func(w http.ResponseWriter, h *http.Request, p httprouter.Params) { var res []entities.FirmFuture rte.q.Query().Find(res) echo(w, res) }) } func (r *router) Start(port int) { http.ListenAndServe(":"+strconv.Itoa(port),r.http) }
commodity-trading-system/broker-gateway
queier/router.go
GO
mit
6,277
27.402715
116
0.65509
false
:: Sample batch script for Post-Job Bot Event :: If you enable 'For all commands, use job details as arguments' :: some details about the just-finished job will be appended to the :: command as arguments. :: :: Argument order is as follows for render operations after each job completes :: %1 => The row index in the spreadsheet. This is always `null` when Bot is enabled. :: %2 => The value of the job's ID column if it has one, `null` if no ID value. :: %3 => The value of the job's devised output name. :: %4 => Absolute path to the final rendered file if it was rendered. :: %5 => Absolute path to the folder containing the rendered file. :: %6 => Absolute path to the processed AE project file. :: %7 => Absolute path to the folder containing the processed AE project file. :: %8 => Absolute path to a .json file containing all job's column values :: :: Provided for your personal or commercial use by Dataclay, LLC @ECHO OFF SET log=%7\post-job.log For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo -------- [TEMPLATER JOB] -------- >> %log% echo Job completed on %mydate% @ %mytime% >> %log% echo Rendered job with ID %2 to %4 >> %log% echo Job details as JSON are found in file %8 >> %log% echo( >> %log%
dataclay/event-scripts
Windows/post-job.bat
Batchfile
mit
1,388
48.571429
92
0.644813
false
<?php /** * Controlador de acesso do backend * * @package MagicPHP Backend * @author André Ferreira <andrehrf@gmail.com> */ class maPrivileges{ /** * Função para verificar autorização de acesso * * @static * @access public * @param string $sUsercase * @param string $sType * @return boolean */ public static function AuthorizedAccess($sUsercase, $sType){ if(Session::CheckAuthentication()){ return (Storage::Get("user.root", false)) ? true : Storage::Get("privilege.{$sType}.{$sUsercase}", false); } else{ Output::Redirect(Storage::Join("route.root", "login")); return false; } } /** * Função para salvar os privilégios * * @static * @access public * @param integer $iID * @return void */ public static function SavePrivileges($iID){ $oDb = Db::backend(); $iID = intval($iID); $aStorage = Storage::GetList(); $aData = array(); foreach($aStorage as $sKey => $mValue){ if(substr($sKey, 0, 4) == "put.") $aData[str_replace("put.", "", $sKey)] = $mValue; } if(count($aData) > 0 && $iID > 0) $oDb->administrators->Update(array("privilegios" => json_encode($aData)), array("id" => $iID), 1); ioBackendController::ReturnAjax(true); } /** * Função para retornar lista de privilgégios de um usuário * * @static * @access public * @param integer $iID * @return void */ public static function GetPrivileges($iID){ $iID = intval($iID); if($iID){ $oDb = Db::backend(); $oDb->administrators->Select("privilegios") ->Filter("id", $iID) ->Execute(function($aData, $mError){ $aPrivileges = json_decode($aData[0]["privilegios"], true); if(count($aPrivileges) > 0) foreach($aPrivileges as $iKey => $mItem) $aPrivileges[$iKey] = ($mItem == "true"); $aPrivileges = (empty($aPrivileges)) ? json_encode(array()) : json_encode($aPrivileges); die($aPrivileges); }); } else{ die(json_encode(array())); } } /** * Função para converter privilegios em JSON para Storage * * @static * @access public * @return void */ public static function LoadPrivileges(){ //if(!empty(Session::Get("user.privileges", ""))){ $aPrivileges = json_decode(Session::Get("user.privileges", array()), true); if($aPrivileges != null) foreach($aPrivileges as $sKey => $sValue) Storage::Set("privilege.".str_replace("_", ".", $sKey), ($sValue == "true")); //} } }
magicphp/backend
modules/backend/core/maprivileges.class.php
PHP
mit
3,522
33.732673
128
0.424458
false
var cv = require('../lib/opencv'); var COLOR = [0, 255, 0]; // default red var thickness = 2; // default 1 cv.readImage('./files/mona.png', function(err, im) { if (err) throw err; if (im.width() < 1 || im.height() < 1) throw new Error('Image has no size'); im.detectObject('../data/haarcascade_frontalface_alt2.xml', {}, function(err, faces) { if (err) throw err; for (var i = 0; i < faces.length; i++) { var face = faces[i]; im.rectangle([face.x, face.y], [face.width, face.height], COLOR, 2); } im.save('./tmp/face-detection-rectangle.png'); console.log('Image saved to ./tmp/face-detection-rectangle.png'); }); });
peterbraden/node-opencv
examples/face-detection-rectangle.js
JavaScript
mit
664
29.181818
88
0.60241
false
// ======================================================================== // SproutCore -- JavaScript Application Framework // Copyright ©2006-2011, Strobe Inc. and contributors. // Portions copyright ©2008 Apple Inc. All rights reserved. // ======================================================================== sc_require('controllers/object'); sc_require('mixins/selection_support'); sc_require('private/tree_item_observer'); /** @class A TreeController manages a tree of model objects that you might want to display in the UI using a collection view. For the most part, you should work with a TreeController much like you would an ObjectController, except that the TreeController will also provide an arrangedObjects property that can be used as the content of a CollectionView. TODO: Document More @extends SC.ObjectController @extends SC.SelectionSupport @since SproutCore 1.0 */ SC.TreeController = SC.ObjectController.extend(SC.SelectionSupport, /** @scope SC.TreeController.prototype */ { // .......................................................... // PROPERTIES // /** Set to YES if you want the top-level items in the tree to be displayed as group items in the collection view. @property {Boolean} */ treeItemIsGrouped: NO, /** If your content support expanding and collapsing of content, then set this property to the name of the key on your model that should be used to determine the expansion state of the item. The default is "treeItemIsExpanded" @property {String} */ treeItemIsExpandedKey: "treeItemIsExpanded", /** Set to the name of the property on your content object that holds the children array for each tree node. The default is "treeItemChildren". @property {String} */ treeItemChildrenKey: "treeItemChildren", /** Returns an SC.Array object that actually will represent the tree as a flat array suitable for use by a CollectionView. Other than binding this property as the content of a CollectionView, you generally should not use this property directly. Instead, work on the tree content using the TreeController like you would any other ObjectController. @property {SC.Array} */ arrangedObjects: function() { var ret, content = this.get('content'); if (content) { ret = SC.TreeItemObserver.create({ item: content, delegate: this }); } else ret = null; // empty! this._sctc_arrangedObjects = ret ; return ret ; }.property().cacheable(), // .......................................................... // PRIVATE // /** @private Manually invalidate the arrangedObjects cache so that we can teardown any existing value. We do it via an observer so that this will fire immediately instead of waiting on some other component to get arrangedObjects again. */ _sctc_invalidateArrangedObjects: function() { this.propertyWillChange('arrangedObjects'); var ret = this._sctc_arrangedObjects; if (ret) ret.destroy(); this._sctc_arrangedObjects = null; this.propertyDidChange('arrangedObjects'); }.observes('content', 'treeItemIsExpandedKey', 'treeItemChildrenKey', 'treeItemIsGrouped'), _sctc_arrangedObjectsContentDidChange: function() { this.updateSelectionAfterContentChange(); }.observes('*arrangedObjects.[]'), /** @private Returns the first item in arrangeObjects that is not a group. This uses a brute force approach right now; we assume you probably don't have a lot of groups up front. */ firstSelectableObject: function() { var objects = this.get('arrangedObjects'), indexes, len, idx = 0; if (!objects) return null; // fast track indexes = objects.contentGroupIndexes(null, objects); len = objects.get('length'); while(indexes.contains(idx) && (idx<len)) idx++; return idx>=len ? null : objects.objectAt(idx); }.property() });
Eloqua/sproutcore
frameworks/foundation/controllers/tree.js
JavaScript
mit
4,038
31.548387
93
0.645937
false
--- title: Custom Login description: This tutorial will show you how to use the Auth0 Ionic SDK to add authentication and authorization to your mobile app. --- <%= include('../../_includes/_package', { githubUrl: 'https://github.com/auth0-samples/auth0-ionic-samples', pkgOrg: 'auth0-samples', pkgRepo: 'auth0-ionic-samples', pkgBranch: 'master', pkgPath: '02-Custom-Login', pkgFilePath: '02-Custom-Login/www/app/auth0.variables.js', pkgType: 'replace' }) %> ::: panel-info Running the Sample At any point in time you can run this sample by going to the `02-Custom-Login` folder of the sample project and running `ionic serve` ::: The previous step explained how you can log users into your application using the Lock Widget. You do not have to use Lock, and can instead create a custom login page and log the user in using a username and password they supply through a customer user interface. If you are using social logins, you can also launch the login screen for a particular social login provider directly from your Ionic application. ### 1. Update references The custom login uses the Auth0.js library to sign a user in, so you should therefor reference this library instead of the Lock widget in your `index.html`. Replace the existing reference to `lib/auth0-lock/build/auth0-lock.js` with `lib/auth0.js/build/auth0.js`: ${snippet(meta.snippets.referencescustom)} ### 2. Implement the login For the login view you must display a Username and Password field to allow the user to sign in with their email address and password, and also display a button which will allow the user to sign in with their Google account. Go ahead and update your `login.html` you did in Step 1: ${snippet(meta.snippets.loginviewcustom)} Also change the `LoginController` to sign the user in with the supplied `username` and `password` fields, or alternatively launch the Google login dialog when the user clicks on the **Login with Google** button: ${snippet(meta.snippets.logincustom)} Notice that in the `onLoginSuccess` method, which is called when a user successfully authenticates, the `profile`, `token`, `accessToken` and `refreshToken` values are saved to Local storage. These values can be retrieve from Local storage at a later stage, for example when you want to display the user's profile information which will be done in Step 3.
Catografix/docs
articles/native-platforms/ionic/02-custom-login.md
Markdown
mit
2,357
55.142857
356
0.767501
false
# hack-homelessness Hack Homelessness Weekend!
OpenDataSTL/placestl.com
README.md
Markdown
mit
47
22.5
26
0.829787
false
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Pfz.AnimationManagement; using Pfz.AnimationManagement.Abstract; using Pfz.AnimationManagement.Animations; using Pfz.AnimationManagement.Wpf; namespace WpfSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private IAnimation[] _basicAnimations; private IAnimation[] _intermediaryAnimations; internal IAnimation _animation; private ReadOnlyCollection<BitmapFrame> _waitingCharacter; private ReadOnlyCollection<BitmapFrame> _movingForwardCharacter; public MainWindow() { InitializeComponent(); Pfz.AnimationManagement.Wpf.Initializer.Initialize(); tabItemBasic.RequestBringIntoView += (a, b) => _SetBasicAnimation(); tabItemIntermediary.RequestBringIntoView += (a, b) => _SetIntermediaryAnimation(); _basicAnimations = new IAnimation[] { // Range AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)), // Accelerating Start AnimationBuilder. BeginAcceleratingStart(1). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndAcceleratingStart(), // Deaccelerating End AnimationBuilder. BeginDeacceleratingEnd(1, 3). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndDeacceleratingEnd(), // Multiple time multipliers AnimationBuilder. BeginProgressiveTimeMultipliers(0.1). Add(AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value))). MultiplySpeed(1, 1). KeepSpeed(1). MultiplySpeed(0.1, 1). EndProgressiveTimeMultipliers(), // Color Range AnimationBuilder.Range(Colors.Black, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)), // Many Color Ranges AnimationBuilder. BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(), // Parallel Animation AnimationBuilder. BeginParallel(). BeginLoop(). BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(). EndLoop(). BeginLoop(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndLoop(). EndParallel(), // Sequential Animation AnimationBuilder. BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(), // Sequential Animation + Multiple Speeds AnimationBuilder. BeginProgressiveTimeMultipliers(). KeepSpeed(1). MultiplySpeed(2, 3). KeepSpeed(1). MultiplySpeed(0.5, 2). KeepSpeedUntilEnd(). BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(). EndProgressiveTimeMultipliers(), // Imperative Animation new ImperativeAnimation(_ImperativeAnimation()), // Frame-by-Frame Animation new ImperativeAnimation(_FrameBasedAnimation()) }; AnimationManager.Add(new _ShowSelectedAnimation(this)); listboxBasicAnimation.SelectionChanged += listboxBasicAnimation_SelectionChanged; _SetBasicAnimation(); bool isGoing = true; _waitingCharacter = _LoadCharacter("Images\\Waiting.gif"); _movingForwardCharacter = _LoadCharacter("Images\\MoveForward.gif"); _intermediaryAnimations = new IAnimation[] { // Animate Character AnimationBuilder.RangeBySpeed(0, _waitingCharacter.Count-1, 10, (index) => imageCharacter.Source = _waitingCharacter[index]), // Move Character AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). BeginLoop(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). EndLoop(). EndParallel(), // Move (Frame-by-Frame) new ImperativeAnimation(_MoveFrameByFrame(_movingForwardCharacter)), // Go and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). BeginPrematureEndCondition(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). BeginParallel(). BeginPrematureEndCondition(() => isGoing). BeginLoop(). RangeBySpeed(_movingForwardCharacter.Count-1, 0, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). EndSequence(), // Go, Turn and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). BeginPrematureEndCondition(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). BeginParallel(). BeginPrematureEndCondition(() => isGoing). BeginLoop(). // Different from the last full-animation, we continue "going forward". RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(), // Go, Turn and Return (* walking while turning). // This animation is similar to the previous 2, but in this case the character is always walking, even // when the animation is "turning" to the opposite side. AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). BeginLoop(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(). EndLoop(). EndParallel() }; listboxIntermediaryAnimation.SelectionChanged += listboxIntermediaryAnimation_SelectionChanged; } private IEnumerable<IAnimation> _ImperativeAnimation() { Random random = new Random(); while(true) { Point origin = new Point(Canvas.GetLeft(circle), Canvas.GetTop(circle)); Point destination = new Point(random.Next(450), random.Next(450)); yield return AnimationBuilder.RangeBySpeed(origin, destination, 150, _SetLeftAndTop); } } private void _SetLeftAndTop(Point point) { Canvas.SetLeft(circle, point.X); Canvas.SetTop(circle, point.Y); } private IEnumerable<IAnimation> _FrameBasedAnimation() { var helper = FrameBasedAnimationHelper.CreateByFps(100); while(true) { double yPosition = 0; double xPosition = 0; double ySpeed = 0.5; while(yPosition < 500) { xPosition++; yPosition += ySpeed; ySpeed += 0.1; Canvas.SetLeft(circle, xPosition); Canvas.SetTop(circle, yPosition); yield return helper.WaitNextFrame(); } } } private void listboxBasicAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) { _SetBasicAnimation(); } private void _SetBasicAnimation() { Canvas.SetLeft(circle, 0); Canvas.SetTop(circle, 0); circle.Fill = Brushes.Black; if (_animation != null) _animation.Reset(); _animation = _basicAnimations[listboxBasicAnimation.SelectedIndex]; } private void listboxIntermediaryAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) { _SetIntermediaryAnimation(); } private void _SetIntermediaryAnimation() { imageCharacter.Left = 0; imageCharacter.Top = 0; imageCharacter.ScaleX = 1; if (_animation != null) _animation.Reset(); _animation = _intermediaryAnimations[listboxIntermediaryAnimation.SelectedIndex]; } private ReadOnlyCollection<BitmapFrame> _LoadCharacter(string path) { using(var stream = File.OpenRead(path)) { var decoder = GifBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var frames = decoder.Frames; return frames; } } private IEnumerable<IAnimation> _MoveFrameByFrame(ReadOnlyCollection<BitmapFrame> character) { var helper = FrameBasedAnimationHelper.CreateByFps(80); int frameCount = character.Count*7; int frameIndex = 0; imageCharacter.Top = canvasIntermediary.ActualHeight - character[0].Height; while(true) { for(int left=0; left<400; left++) { frameIndex++; if (frameIndex >= frameCount) frameIndex = 0; imageCharacter.Source = character[frameIndex/7]; imageCharacter.Left = left; yield return helper.WaitNextFrame(); } } } private void tabItemAdvanced_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { if (_animation != null) _animation.Reset(); _animation = new ImperativeAnimation(_AdvancedAnimation()); } private int _direction = 0; private bool _isUpPressed; private IEnumerable<IAnimation> _AdvancedAnimation() { var helper = FrameBasedAnimationHelper.CreateByFps(80); canvasAdvanced.Focus(); var canvasChildren = canvasAdvanced.Children; double playerLeft = 0; double playerScale = 1; var playerCharacter = new ImageWithShadow(); playerCharacter.Left = playerLeft; playerCharacter.Top = 300; var otherCharacter = new ImageWithShadow(); otherCharacter.ScaleX = -1; otherCharacter.Left = 350; otherCharacter.Top = 300; var presentationAnimation = AnimationBuilder. BeginSequence(). Add(_ShowText("This is an interactive animation.\r\nPress the Left, Up and Right arrows to Move.")). Add(_ShowText("Yet this is not a game, the other character will only flee from you.")). EndSequence(); bool ending = false; bool jumping = false; try { // This animation will run in parallel to the actual imperative animaion. // It is "subordinated" and so, if this animation is ended prematurely, such // parallel animation will also end prematurely. // This is different than adding the animation to the WpfAnimationManager directly. // Also, there is an additional difference, as time modifiers that are affecting // this animation will also affect its subordinated parallel (even if this is not // happening in this sample application). ImperativeAnimation.AddSubordinatedParallel(presentationAnimation); canvasChildren.Add(playerCharacter); canvasChildren.Add(otherCharacter); canvasAdvanced.PreviewKeyDown += canvasAdvanced_PreviewKeyDown; canvasAdvanced.PreviewKeyUp += canvasAdvanced_PreviewKeyUp; int actualMovingFrame = 0; int totalMovingFrames = _movingForwardCharacter.Count * 8; int totalWaitingFrames = _waitingCharacter.Count * 8; int actualWaitingFrame = totalWaitingFrames; bool running = true; while(running) { actualWaitingFrame++; if (actualWaitingFrame >= totalWaitingFrames) actualWaitingFrame = 0; int actualRealFrame = actualWaitingFrame / 8; otherCharacter.Source = _waitingCharacter[actualRealFrame]; if (_isUpPressed && !jumping) { jumping = true; Action<double> setTop = (value) => playerCharacter.JumpingHeight = value; var animation = AnimationBuilder.BeginSequence(). Range(0, 100, 0.3, setTop). Range(100, 0, 0.3, setTop). Add(() => jumping = false). EndSequence(); ImperativeAnimation.AddSubordinatedParallel(animation); } if (_direction == 0) playerCharacter.Source = _waitingCharacter[actualRealFrame]; else { bool canMove = false; if (_direction < 0) { if (playerScale > -1) { playerScale -= 0.1; if (playerScale < -1) playerScale = -1; } else canMove = true; playerCharacter.ScaleX = playerScale; } else { if (playerScale < 1) { playerScale += 0.1; if (playerScale > 1) playerScale = 1; } else canMove = true; playerCharacter.ScaleX = playerScale; } if (canMove) { actualMovingFrame++; if (actualMovingFrame >= totalMovingFrames) actualMovingFrame = 0; playerCharacter.Source = _movingForwardCharacter[actualMovingFrame/8]; playerLeft += _direction * 1; if (playerLeft < 0) playerLeft = 0; // The typical invisible barrier in which the character // continues walking without moving. playerCharacter.Left = playerLeft; if (playerLeft > 250 && !ending) { // this is to avoid playing the ending animation more // than once. ending = true; // and this is just in case the presentation is still running, // as we don't want messages to overlap. presentationAnimation.Dispose(); Action<double> setLeft = (value) => otherCharacter.Left = value; Action<double> setTop = (value) => otherCharacter.Top = value; var finalAnimation = AnimationBuilder. BeginSequence(). BeginParallel(). Range(350, 370, 0.10, setLeft). Range(300, 280, 0.10, setTop). EndParallel(). BeginParallel(). Range(370, 390, 0.10, setLeft). Range(280, 300, 0.10, setTop). EndParallel(). Range(-1.0, 1.0, 0.5, (value) => otherCharacter.ScaleX = value). Range(390, 510, 0.5, setLeft). Add(_ShowText("The other character fled from you...")). Add(_ShowText("... he is a COWARD!!!")). Add(() => running=false). EndSequence(); ImperativeAnimation.AddSubordinatedParallel(finalAnimation); } } } yield return helper.WaitNextFrame(); } } finally { canvasAdvanced.PreviewKeyDown -= canvasAdvanced_PreviewKeyDown; canvasChildren.Remove(playerCharacter); canvasChildren.Remove(otherCharacter); } } void canvasAdvanced_PreviewKeyDown(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: _direction = -1; e.Handled = true; break; case Key.Right: _direction = 1; e.Handled = true; break; case Key.Up: _isUpPressed = true; e.Handled = true; break; } } void canvasAdvanced_PreviewKeyUp(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: case Key.Right: e.Handled = true; _direction = 0; break; case Key.Up: e.Handled = true; _isUpPressed = false; break; } } private IEnumerable<IAnimation> _ShowText(string message) { var textBlock = new TextBlock(); try { textBlock.Text = message; canvasAdvanced.Children.Add(textBlock); Action<double> setOpacity = (value) => textBlock.Opacity = value; yield return AnimationBuilder. BeginSequence(). Range(0.0, 1.0, 1, setOpacity). Wait(2). Range(1.0, 0.0, 1, setOpacity). EndSequence(); } finally { canvasAdvanced.Children.Remove(textBlock); } } } }
flysnoopy1984/DDZ_Live
ReferenceCode/Pfz.AnimationManagement.2013_08_25/Pfz.AnimationManagement/WpfSample/MainWindow.xaml.cs
C#
mit
26,050
42.631491
160
0.466984
false
package fables.kotlin.jee.rest; import fables.kotlin.jee.business.KittenBusinessService; import fables.kotlin.jee.business.KittenEntity; import javax.inject.Inject; import javax.ws.rs.*; /** * JSON REST CRud service. * JEE will first create one noarg instance, and then injected instances. * * @author Zeljko Trogrlic */ @Path("kitten") public class KittenRestService { @Inject protected KittenBusinessService kittenBusinessService; @GET @Path("{id}") @Produces({"application/json"}) public KittenRest find( @PathParam("id") final int id ) { return kittenBusinessService .find(id) .map(kittenEntity -> new KittenRest(kittenEntity.getName(), kittenEntity.getCuteness())) .orElseThrow(() -> new NotFoundException("ID " + id + " not found")); } @POST @Produces({"application/json"}) public Integer add(KittenRest kittenRest) { KittenEntity kittenEntity = new KittenEntity(kittenRest.getName(), kittenRest.getCuteness()); return kittenBusinessService.add(kittenEntity); } }
zeljkot/fables-kotlin
jee/java/src/main/java/fables/kotlin/jee/rest/KittenRestService.java
Java
mit
1,047
25.846154
97
0.714422
false
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => true, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost/web.api', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'GZxF3oujFlAL4GVeC1n57tAzXLWK0wsv', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Remote\RemoteServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', 'Way\Generators\GeneratorsServiceProvider', 'Aws\Laravel\AwsServiceProvider', 'Intervention\Image\ImageServiceProvider', 'Twilio\Laratwilio\LaratwilioServiceProvider' ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'SSH' => 'Illuminate\Support\Facades\SSH', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'AWS' => 'Aws\Laravel\AwsFacade', 'Image' => 'Intervention\Image\Facades\Image', 'Sms' => 'Twilio\Laratwilio\Facades\Laratwilio' ), );
TeenahApp/web.api
app/config/app.php
PHP
mit
7,278
38.554348
76
0.571448
false
import React, {Component} from 'react'; import PdfJS from './pdfJS'; import Contract from "../../contract"; import Event from '../../event'; import AnnotationLoader from '../../annotator/loader'; class Viewer extends Component { constructor(props) { super(props); this.state = ({ page_no: 0, pdf_url: "", scale: 0, loading: true }); } componentDidMount() { this.subscribe_zoom = Event.subscribe('zoom:change', (scale) => { this.setState({scale: scale}); }); this.updateState(this.props); } updateState(props) { var {page_no, pdf_url} = props.page; var scale = Contract.getPdfScale(); this.setState({ page_no, pdf_url, scale, loading: false }); } componentWillUnmount() { this.subscribe_zoom.remove(); } getPageID() { return 'pdf-' + this.state.page_no; } getAnnotations() { let page = []; let annotations = Contract.getAnnotations(); annotations.result.forEach(annotation=> { if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) { page.push(annotation); } }); return page; } onPageRendered() { if (!this.annotator) { this.annotator = new AnnotationLoader('.pdf-annotator'); this.annotator.init(); Contract.setAnnotatorInstance(this.annotator); } const annotations = this.getAnnotations(); if (annotations.length > 0) { this.annotator.content.annotator("loadAnnotations", annotations); } Event.publish('annotation:loaded', 'pdf'); } componentWillReceiveProps(props) { this.updateState(props); } shouldComponentUpdate(nextProps, nextState) { return (nextProps.page.page_no !== this.state.page_no || this.state.scale !== nextState.scale); } render() { if (this.state.loading) { return ( <div className="pdf-viewer pdf-annotator"> <div className="pdf-wrapper"> Loading... </div> </div>); } return ( <div className="pdf-viewer pdf-annotator"> <div id={this.getPageID()} className="pdf-wrapper"> <PdfJS onPageRendered={this.onPageRendered.bind(this)} file={this.state.pdf_url} page={this.state.page_no} scale={this.state.scale}/> </div> <a href="#" className="change-view-icon exit-fullscreen"></a> </div> ); } } export default Viewer;
younginnovations/resourcecontracts-rc-subsite
resources/assets/scripts/contract/components/pdf/viewer.js
JavaScript
mit
2,838
26.553398
103
0.519027
false
use std::collections::{HashMap}; use std::path::{Path}; use std::sync::{Arc}; use crossbeam::sync::{MsQueue}; use glium::backend::{Facade}; use debug::{gnomon, indicator}; use inverse_kinematics::{Chain}; use model::{Model}; use unlit_model::{UnlitModel}; use render::render_frame::{RenderFrame}; pub const DEPTH_DIMENSION: u32 = 2048; #[derive(Eq, PartialEq, Hash, Copy, Clone)] pub enum ModelId { Player, Scene, IKModel, // TODO: we are going to need more of these / a dynamic way to generate ids and load at a later time Tree, // DEBUG Gnomon, Indicator, } pub struct RenderContext { pub q: Arc<MsQueue<RenderFrame>>, // TODO: make private and provide minimal decent api window_size: (u32, u32), // TODO: maybe this should be a per RenderFrame parameter pub models: HashMap<ModelId, Arc<Model>>, // DEBUG pub unlit_models: HashMap<ModelId, Arc<UnlitModel>>, } impl RenderContext { pub fn new<F: Facade>(facade: &F, q: Arc<MsQueue<RenderFrame>>, window_size: (u32, u32), ik_chains: &[Chain]) -> RenderContext { let model_map = load_initial_models(facade, ik_chains); // DEBUG let mut unlit_models = HashMap::new(); unlit_models.insert(ModelId::Gnomon, Arc::new(gnomon::model(facade))); unlit_models.insert(ModelId::Indicator, Arc::new(indicator::model(facade))); RenderContext { q: q, window_size: window_size, models: model_map, // DEBUG unlit_models: unlit_models, } } pub fn aspect_ratio(&self) -> f32 { (self.window_size.0 as f32) / (self.window_size.1 as f32) } } // TODO: don't pass in chains but make something like IntoModel // fn load_initial_models<F: Facade>(facade: &F, ik_chains: &[Chain]) -> HashMap<ModelId, Arc<Model>> { let mut map = HashMap::new(); const MODEL_PATH_STRINGS: [(ModelId, &'static str); 3] = [ (ModelId::Player, "./data/player.obj"), (ModelId::Scene, "./data/level.obj"), (ModelId::Tree, "./data/tree.obj") ]; for &(model_id, path) in &MODEL_PATH_STRINGS { let model = Arc::new(Model::new(facade, &Path::new(path))); map.insert(model_id, model); } for chain in ik_chains { map.insert(ModelId::IKModel, Arc::new(chain.model(facade))); } map } unsafe impl Send for RenderContext {} unsafe impl Sync for RenderContext {}
AnthonyMl/sg-rs
src/render/render_context.rs
Rust
mit
2,238
25.963855
129
0.677837
false
var ratio = require('ratio') function error(actual, expected) { return Math.abs(actual - expected) / expected } function approx(target, max) { max = (max || 10) // find a good approximation var best = 1, j, e, result for (var i = 1; i < max; i++) { j = Math.round(i * target) e = error(j / i, target) if (e >= best) continue best = e result = ratio(j, i) } return result } module.exports = approx
agnoster/approx
index.js
JavaScript
mit
474
16.555556
49
0.546414
false
// ------------------------------------------------------------------------------------- // Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved. // For email, run on linux (perl v5.8.5): // perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"' // ------------------------------------------------------------------------------------- // Author - Sourabh S Joshi #ifndef POKER_HAND_H_ #define POKER_HAND_H_ #include <iostream> #include <array> #include <vector> #include <string> #include <sstream> using std::vector; using std::ostream; using std::pair; class Card { public: enum CardSuit { Clubs, Diamonds, Hearts, Spades, NUM_SUITS }; enum CardVal { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace, NUM_VALS }; Card(CardSuit suit, CardVal val) : suit_(suit), val_(val) {} ~Card() {} //comparison operators only compare on value of card bool operator==(const Card& rhs) const { return (val_ == rhs.val_);} bool operator<(const Card& rhs) const { return (val_ < rhs.val_);} bool operator>(const Card& rhs) const { return (val_ > rhs.val_);} CardVal GetVal() const {return val_;} CardSuit GetSuit() const {return suit_;} friend ostream& operator<<(ostream& os, const Card& cd); private: CardSuit suit_; CardVal val_; }; class Pokerhand { public: enum HandType { PHHighCard, PHPair, PHTwoPair, PHThreeOfAKind, PHStraight, PHFlush, PHFullHouse, PHFourOfAKind, PHStraightFlush, PH_NUM_TYPES }; Pokerhand(std::string istr); virtual ~Pokerhand() {} vector<Card> AllCards() const {return hand_;} vector<Card> TieBreakCards() const {return tiebreak_cards_;} HandType GetType() const {return type_;} std::string GetTypeStr() const; //comparison to compare 2 poker hands bool operator>(const Pokerhand& rhs) const {return (Compare_(rhs) == PH_GT);} bool operator<(const Pokerhand& rhs) const {return (Compare_(rhs) == PH_LT);} bool operator==(const Pokerhand& rhs) const {return (Compare_(rhs) == PH_EQ);} friend ostream& operator<<(ostream& os, const Pokerhand& ph); void ProcessPokerHand(); private: //each of these methods returns a bool, saying whether the poker hand is of that type //also returns a vector of cards in order, so that tie-breakers can be resolved Card* XOfAKind__(unsigned int num); bool XOfAKind_(unsigned int num); bool MNOfAKind_(unsigned int m, unsigned int n); bool HighCard_(); bool Pair_(); bool TwoPair_(); bool ThreeOfAKind_(); bool Straight_(); bool Flush_(); bool FullHouse_(); bool FourOfAKind_(); bool StraightFlush_(); //since C++ STL lacks an ordering type, I am forced to create one enum Ordering { PH_LT, PH_EQ, PH_GT }; Ordering Compare_(const Pokerhand& rhs) const; private: vector<Card> hand_; HandType type_; vector<Card> tiebreak_cards_; }; int PlayPokerHands(vector<std::pair<int, Pokerhand> >& hands); bool DetectCheating(vector<std::pair<int, Pokerhand> >& hands); #endif /* POKER_HAND_H_ */
cbrghostrider/Hacking
cpp-katas/Poker-Hand/poker-hand.h
C
mit
3,193
30.303922
133
0.615722
false
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ 'use strict'; /* Controllers */ moduloUsuariocursoxusuario.controller('UsuariocursoxusuarioPListController', ['$scope', '$routeParams', 'serverService', '$location', 'redirectService', 'sharedSpaceService', 'checkSessionStorageService', function ($scope, $routeParams, serverService, $location, redirectService, sharedSpaceService, checkSessionStorageService) { checkSessionStorageService.isSessionSessionStoraged(); $scope.visibles = {}; $scope.visibles.id = true; $scope.visibles.titulo = true; $scope.visibles.descripcion = true; $scope.visibles.nota = true; $scope.ob = "usuariocursoxusuario"; $scope.op = "plist"; $scope.title = "Listado de usuariocursoxusuario"; $scope.icon = "fa-file-text-o"; $scope.neighbourhood = 2; if (!$routeParams.page) { $routeParams.page = 1; } if (!$routeParams.rpp) { $routeParams.rpp = 999; } $scope.numpage = $routeParams.page; $scope.rpp = $routeParams.rpp; $scope.predicate = 'id'; $scope.reverse = false; $scope.orderCliente = function (predicate) { $scope.predicate = predicate; $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; }; $scope.getListaCursos = function () { serverService.getDataFromPromise(serverService.promise_getListaCursos()).then(function (data) { redirectService.checkAndRedirect(data); if (data.status != 200) { $scope.statusListaCursos = "Error en la recepción de datos del servidor"; } else { $scope.listaCursos = data.message; for (var i = 0; i < $scope.listaCursos.length; i++) { if (i > 0) { if ($scope.listaCursos[i].obj_curso.id == $scope.listaCursos[i - 1].obj_curso.id) { $scope.listaCursos[i - 1].alProfesores.push($scope.listaCursos[i].alProfesores[0]); $scope.listaCursos.splice(i, 1); i = i - 1; } } } } }); }; //$scope.rppPad = serverService.getNrppBar($scope.ob, $scope.op, $scope.numpage, $scope.rpp); // $scope.order = $routeParams.order; // $scope.ordervalue = $routeParams.value; // // $scope.filter = $routeParams.filter; // $scope.filteroperator = $routeParams.filteroperator; // $scope.filtervalue = $routeParams.filtervalue; // // $scope.systemfilter = $routeParams.systemfilter; // $scope.systemfilteroperator = $routeParams.systemfilteroperator; // $scope.systemfiltervalue = $routeParams.systemfiltervalue; $scope.order = ""; $scope.ordervalue = ""; $scope.filter = "id"; $scope.filteroperator = "like"; $scope.filtervalue = ""; $scope.systemfilter = ""; $scope.systemfilteroperator = ""; $scope.systemfiltervalue = ""; $scope.params = ""; $scope.paramsWithoutOrder = ""; $scope.paramsWithoutFilter = ""; $scope.paramsWithoutSystemFilter = ""; if ($routeParams.order && $routeParams.ordervalue) { $scope.order = $routeParams.order; $scope.ordervalue = $routeParams.ordervalue; $scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue; $scope.paramsWithoutFilter += $scope.orderParams; $scope.paramsWithoutSystemFilter += $scope.orderParams; } else { $scope.orderParams = ""; } if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) { $scope.filter = $routeParams.filter; $scope.filteroperator = $routeParams.filteroperator; $scope.filtervalue = $routeParams.filtervalue; $scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue; $scope.paramsWithoutOrder += $scope.filterParams; $scope.paramsWithoutSystemFilter += $scope.filterParams; } else { $scope.filterParams = ""; } if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) { $scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue; $scope.paramsWithoutOrder += $scope.systemFilterParams; $scope.paramsWithoutFilter += $scope.systemFilterParams; } else { $scope.systemFilterParams = ""; } $scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams); //$scope.paramsWithoutOrder = $scope.paramsWithoutOrder.replace('&', '?'); //$scope.paramsWithoutFilter = $scope.paramsWithoutFilter.replace('&', '?'); //$scope.paramsWithoutSystemFilter = $scope.paramsWithoutSystemFilter.replace('&', '?'); $scope.params = $scope.params.replace('&', '?'); $scope.getCursosPage = function () { serverService.getDataFromPromise(serverService.promise_getSomeUsuariocursoXUsuario($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) { redirectService.checkAndRedirect(data); if (data.status != 200) { $scope.status = "Error en la recepción de datos del servidor"; } else { $scope.pages = data.message.pages.message; if (parseInt($scope.numpage) > parseInt($scope.pages)) $scope.numpage = $scope.pages; $scope.page = data.message.page.message; $scope.registers = data.message.registers.message; $scope.status = ""; } }); } $scope.getCursosPage(); // $scope.pages = serverService.getPages($scope.ob, $scope.rpp, null, null, null, null, null, null).then(function (datos5) { // $scope.pages = data['data']; // if (parseInt($scope.page) > parseInt($scope.pages)) // $scope.page = $scope.pages; // //$location.path( "#/clientes/" +$scope.pages + "/" + $scope.pages); // }); // $scope.$watch('pages', function () { // $scope.$broadcast('myApp.construirBotoneraPaginas'); // }, true) // $scope.getRangeArray = function (lowEnd, highEnd) { var rangeArray = []; for (var i = lowEnd; i <= highEnd; i++) { rangeArray.push(i); } return rangeArray; }; $scope.evaluateMin = function (lowEnd, highEnd) { return Math.min(lowEnd, highEnd); }; $scope.evaluateMax = function (lowEnd, highEnd) { return Math.max(lowEnd, highEnd); }; $scope.dofilter = function () { if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") { //console.log('#/' + $scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp + '?filter=' + $scope.filter + '&filteroperator=' + $scope.filteroperator + '&filtervalue=' + $scope.filtervalue + $scope.paramsWithoutFilter); if ($routeParams.order && $routeParams.ordervalue) { if ($routeParams.systemfilter && $routeParams.systemfilteroperator) { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue); } else { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue); } } else { $location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue); } } return false; }; //$scope.$on('myApp.construirBotoneraPaginas', function () { // $scope.botoneraPaginas = serverService.getPaginationBar($scope.ob, $scope.op, $scope.page, $scope.pages, 2, $scope.rpp); //}) // // $scope.prettyFieldNames = serverService.getPrettyFieldNames($scope.ob).then(function (datos4) { // datos4['data'].push('acciones'); // $scope.prettyFieldNames = datos4['data']; // }); // // $scope.clientes = serverService.getPage($scope.ob, $scope.page, null, null, $scope.rpp, null, null, null, null, null, null).then(function (datos3) { // $scope.clientes = datos3['list']; // // }); // // $scope.fieldNames = serverService.getFieldNames($scope.ob).then(function (datos6) { // $scope.fieldNames = datos6['data']; // $scope.selectedFilterFieldName = null; // }); // // // $scope.$watch('numPagina', function () { // $scope.$broadcast('myApp.construirPagina'); // }, true) // // $scope.$on('myApp.construirPagina', function () { // // $scope.clientes = serverService.getPage($scope.ob, $scope.page, null, null, $scope.rpp, null, null, null, null, null, null).then(function (datos3) { // $scope.clientes = datos3['list']; // // }); // // }) // // $scope.filtrar = function () { // alert("f") // // // }; // $scope.$watch('filteroperator', function () { // console.log($scope.filter); // console.log($scope.filteroperator); // console.log($scope.filtervalue); // }, true) $scope.newObj = function (args) { $scope.objEdit = {}; $scope.position = undefined; switch (args.strClass) { case 'curso': $scope.objEdit.id = 0; break; case 'inscribirse': $scope.mostrarPass={}; if (sharedSpaceService.getFase() == 0) { serverService.getDataFromPromise(serverService.promise_getOne('curso', args.id)).then(function (data) { $scope.objEdit = data.message; $scope.objEdit.password; $scope.mostrarPass.mostrar=true; $scope.mostrarPass.idCurso=args.id; }); } else { $scope.objEdit = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } break; } ; }; $scope.edit = function (args) { $scope.objEdit = {}; switch (args.strClass) { case 'curso': $scope.position = $scope.page.alUsuariocursos.indexOf(args.levelOne); if (sharedSpaceService.getFase() == 0) { serverService.getDataFromPromise(serverService.promise_getOne(args.strClass, args.id)).then(function (data) { $scope.objEdit = data.message; //date conversion }); } else { $scope.objEdit = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } break; } ; }; $scope.save = function (type) { switch (type) { case 'curso': serverService.getDataFromPromise(serverService.promise_setCurso('curso', {json: JSON.stringify(serverService.array_identificarArray($scope.objEdit))})).then(function (data) { redirectService.checkAndRedirect(data); if (data.status = 200) { $scope.result = data; if ($scope.position !== undefined) { $scope.page.alUsuariocursos[$scope.position].obj_curso = $scope.objEdit; $scope.position = undefined; } else { $scope.objFinal = {}; $scope.objFinal.id = $scope.result.message.idUsuarioCurso; $scope.objFinal.obj_curso = {id: $scope.result.message.idCurso}; $scope.objFinal.obj_curso.titulo = $scope.objEdit.titulo; $scope.objFinal.obj_curso.descripcion = $scope.objEdit.descripcion; $scope.page.alUsuariocursos.push($scope.objFinal); } } }); break; case 'inscribirse': serverService.getDataFromPromise(serverService.promise_setUsuariocurso('usuariocurso', {json: JSON.stringify(serverService.array_identificarArray($scope.objEdit))})).then(function (data) { redirectService.checkAndRedirect(data); if (data.status = 200) { $scope.getCursosPage(); $scope.mostrarContraseña.mostrar=undefined; $scope.mostrarContraseña.idCurso=undefined; } }); break; } ; }; $scope.remove = function (type, id, idUsuarioCurso) { switch (type) { case 'curso': serverService.getDataFromPromise(serverService.promise_removeCurso(type, id, idUsuarioCurso)).then(function (data) { redirectService.checkAndRedirect(data); if (data.status = 200) { $scope.result = data; $scope.page.alUsuariocursos.splice($scope.position, 1); $scope.position = undefined; } }); break; } }; }]);
Ilthur/boletinweb
src/main/webapp/js/usuariocursoxusuario/plist.js
JavaScript
mit
16,663
44.895317
490
0.548052
false
.yan-github { position: fixed; bottom:0; right:0; min-width:350px; outline:1px solid rgba(0, 0, 0, 0.3); min-height:200px; background: #FFFFFF; border-radius:3px; box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); z-index: 10000 } .yan-github ul{ padding:0 } .yan-github li { list-style-type: none } .yan-header { margin: 10px; border-bottom: 1px solid #2299DD; padding-bottom: 5px; } .yan-header h2 { margin:0; } .yan-header .yan-close { float: right; font-size: 0.8em; cursor: pointer } .yan-github form { margin: 10px } .yan-github fieldset { border: 0; margin: 5px; margin-bottom: 20px } .yan-github fieldset::after { content: ""; display: block; clear: both } .yan-github legend { font-size: 1.2em; margin-bottom: 10px; border-bottom: 1px solid #e5e5e5; width: 100%; } .yan-label-block{ display: block; margin: 5px } .yan-btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; background-image: none; border: 1px solid transparent; border-radius: 4px; } .yan-btn:hover { color: #333; }
yanhaijing/githubFansTool
src/css/index.css
CSS
mit
1,340
16.402597
45
0.6
false
/** * Write the input to the paramsified file * * --- * INPUTS: * * - FILES * Write the list of files to the paramsified file (line feed after each filename). * * - STRINGS * Write the strings (concatenated) to the paramsified file. * * - STRING * Write the string to the paramsified file. * * - UNDEFINED * Touch the file. * * OUTPUT: * * - FILES * The filename that was written. * --- * * @module tasks * @submodule write */ var State = require('../state'), path = require('path'), mkdirp = require('mkdirp').mkdirp, fs = require('fs'); /** * Write out the input to the destination filename. * * This can only apply to single string inputs. * * @method writeTask * @param options {Object} Write task options * @param options.name {String} Filename to write to. * @param options.encoding {String} [default='utf8'] Encoding to use when writing the file * @param options.mkdir {Boolean} [default=true] Make destination directory if it does not exist * @param options.dirmode {String} [default='0755'] Create new directories with this mode (chmod) * @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses. * @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status) * @return {undefined} * @public */ function writeTask(options, status, logger) { var self = this, pathname = path.resolve(path.dirname(options.name)), name = options.name, encoding = options && options.encoding || 'utf8', mkdir = options && options.mkdir || true, dirmode = options && options.dirmode || '0755'; // Write the content to the specified file. function writeFile(filename, data) { fs.writeFile(filename, data, encoding, function(err) { if (err) { status.emit('failed', 'write', 'error writing destination file: ' + err); } else { self._state.set(State.TYPES.FILES, [ filename ]); status.emit('complete', 'write', 'wrote ' + filename); } }); } // Create the paramsified path if it does not exist. function mkdirIfNotExist(filename, callback) { path.exists(filename, function(exists) { if (!exists) { if (mkdir === true) { mkdirp(filename, dirmode, function(err) { if (err) { callback(err); } else { callback(null); } }); } else { callback('tried to write a file to a non-existing directory and mkdir is false'); } } else { callback(null); } }); } switch (this._state.get().type) { case State.TYPES.FILES: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("\n")); } }); break; case State.TYPES.STRING: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value); } }); break; case State.TYPES.STRINGS: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("")); } }); break; case State.TYPES.UNDEFINED: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, ""); } }); break; default: status.emit('failed', 'write', 'unrecognised input type: ' + this._type); break; } } exports.tasks = { 'write' : { callback: writeTask } };
mosen/buildy
lib/buildy/tasks/write.js
JavaScript
mit
4,521
30.84507
111
0.52223
false
# frozen_string_literal: true require 'grape/router' require 'grape/api/instance' module Grape # The API class is the primary entry point for creating Grape APIs. Users # should subclass this class in order to build an API. class API # Class methods that we want to call on the API rather than on the API object NON_OVERRIDABLE = (Class.new.methods + %i[call call! configuration compile! inherited]).freeze class << self attr_accessor :base_instance, :instances # Rather than initializing an object of type Grape::API, create an object of type Instance def new(*args, &block) base_instance.new(*args, &block) end # When inherited, will create a list of all instances (times the API was mounted) # It will listen to the setup required to mount that endpoint, and replicate it on any new instance def inherited(api, base_instance_parent = Grape::API::Instance) api.initial_setup(base_instance_parent) api.override_all_methods! make_inheritable(api) end # Initialize the instance variables on the remountable class, and the base_instance # an instance that will be used to create the set up but will not be mounted def initial_setup(base_instance_parent) @instances = [] @setup = Set.new @base_parent = base_instance_parent @base_instance = mount_instance end # Redefines all methods so that are forwarded to add_setup and be recorded def override_all_methods! (base_instance.methods - NON_OVERRIDABLE).each do |method_override| define_singleton_method(method_override) do |*args, &block| add_setup(method_override, *args, &block) end end end # Configure an API from the outside. If a block is given, it'll pass a # configuration hash to the block which you can use to configure your # API. If no block is given, returns the configuration hash. # The configuration set here is accessible from inside an API with # `configuration` as normal. def configure config = @base_instance.configuration if block_given? yield config self else config end end # This is the interface point between Rack and Grape; it accepts a request # from Rack and ultimately returns an array of three values: the status, # the headers, and the body. See [the rack specification] # (http://www.rubydoc.info/github/rack/rack/master/file/SPEC) for more. # NOTE: This will only be called on an API directly mounted on RACK def call(*args, &block) instance_for_rack.call(*args, &block) end # Allows an API to itself be inheritable: def make_inheritable(api) # When a child API inherits from a parent API. def api.inherited(child_api) # The instances of the child API inherit from the instances of the parent API Grape::API.inherited(child_api, base_instance) end end # Alleviates problems with autoloading by tring to search for the constant def const_missing(*args) if base_instance.const_defined?(*args) base_instance.const_get(*args) else super end end # The remountable class can have a configuration hash to provide some dynamic class-level variables. # For instance, a description could be done using: `desc configuration[:description]` if it may vary # depending on where the endpoint is mounted. Use with care, if you find yourself using configuration # too much, you may actually want to provide a new API rather than remount it. def mount_instance(**opts) instance = Class.new(@base_parent) instance.configuration = Grape::Util::EndpointConfiguration.new(opts[:configuration] || {}) instance.base = self replay_setup_on(instance) instance end # Replays the set up to produce an API as defined in this class, can be called # on classes that inherit from Grape::API def replay_setup_on(instance) @setup.each do |setup_step| replay_step_on(instance, setup_step) end end def respond_to?(method, include_private = false) super(method, include_private) || base_instance.respond_to?(method, include_private) end def respond_to_missing?(method, include_private = false) base_instance.respond_to?(method, include_private) end def method_missing(method, *args, &block) # If there's a missing method, it may be defined on the base_instance instead. if respond_to_missing?(method) base_instance.send(method, *args, &block) else super end end def compile! require 'grape/eager_load' instance_for_rack.compile! # See API::Instance.compile! end private def instance_for_rack if never_mounted? base_instance else mounted_instances.first end end # Adds a new stage to the set up require to get a Grape::API up and running def add_setup(method, *args, &block) setup_step = { method: method, args: args, block: block } @setup += [setup_step] last_response = nil @instances.each do |instance| last_response = replay_step_on(instance, setup_step) end last_response end def replay_step_on(instance, setup_step) return if skip_immediate_run?(instance, setup_step[:args]) args = evaluate_arguments(instance.configuration, *setup_step[:args]) response = instance.send(setup_step[:method], *args, &setup_step[:block]) if skip_immediate_run?(instance, [response]) response else evaluate_arguments(instance.configuration, response).first end end # Skips steps that contain arguments to be lazily executed (on re-mount time) def skip_immediate_run?(instance, args) instance.base_instance? && (any_lazy?(args) || args.any? { |arg| arg.is_a?(Hash) && any_lazy?(arg.values) }) end def any_lazy?(args) args.any? { |argument| argument.respond_to?(:lazy?) && argument.lazy? } end def evaluate_arguments(configuration, *args) args.map do |argument| if argument.respond_to?(:lazy?) && argument.lazy? argument.evaluate_from(configuration) elsif argument.is_a?(Hash) argument.transform_values { |value| evaluate_arguments(configuration, value).first } elsif argument.is_a?(Array) evaluate_arguments(configuration, *argument) else argument end end end def never_mounted? mounted_instances.empty? end def mounted_instances instances - [base_instance] end end end end
dblock/grape
lib/grape/api.rb
Ruby
mit
7,030
34.867347
107
0.635562
false
(function () { "use strict"; /** * This module have an ability to contain constants. * No one can reinitialize any of already initialized constants */ var module = (function () { var constants = {}, hasOwnProperty = Object.prototype.hasOwnProperty, prefix = (Math.random() + "_").slice(2), isAllowed; /** * This private method checks if value is acceptable * @param value {String|Number|Boolean} - the value of the constant * @returns {boolean} * @private */ isAllowed = function (value) { switch (typeof value) { case "number": return true; case "string": return true; case "boolean": return true; default: return false; } }; return { /** * Constant getter * @param name {String} - the name of the constant * @returns {String|Number|Boolean|null} */ getConstant: function (name) { if (this.isDefined(name) === true) { return constants[prefix + name]; } return undefined; }, /** * Setter * @param name {String} - the name of the constant * @param value {String|Number|Boolean} - the value of the constant * @returns {boolean} */ setConstant: function (name, value) { if (isAllowed(value) !== true) { return false; } if (this.isDefined(name) === true) { return false; } constants[prefix + name] = value; return true; }, /** * This method checks if constant is already defined * @param name {String} - the name of the constant * @returns {boolean} */ isDefined: function (name) { return hasOwnProperty.call(constants, prefix + name); } }; })(); /**Testing*/ module.setConstant("test", 123); print("test == " + module.getConstant("test")); print("idDefined(\"test\") == " + module.isDefined("test")); print("test2 == " + module.getConstant("test2")); print("idDefined(\"test2\") == " + module.isDefined("test2")); print(""); module.setConstant("test", 321); print("test == " + module.getConstant("test")); print(""); module.setConstant("test3", {a: 123}); print("test3 == " + module.getConstant("test3")); })();
AlexeyPopovUA/JavaScript-design-patterns
js/samples/object-constants/ObjectConstants.js
JavaScript
mit
2,762
28.709677
79
0.468139
false
# frozen_string_literal: true module RuboCop module Formatter # This formatter formats report data in clang style. # The precise location of the problem is shown together with the # relevant source code. class ClangStyleFormatter < SimpleTextFormatter ELLIPSES = '...' def report_file(file, offenses) offenses.each { |offense| report_offense(file, offense) } end private def report_offense(file, offense) output.printf( "%<path>s:%<line>d:%<column>d: %<severity>s: %<message>s\n", path: cyan(smart_path(file)), line: offense.line, column: offense.real_column, severity: colored_severity_code(offense), message: message(offense) ) begin return unless valid_line?(offense) report_line(offense.location) report_highlighted_area(offense.highlighted_area) rescue IndexError # rubocop:disable Lint/SuppressedException # range is not on a valid line; perhaps the source file is empty end end def valid_line?(offense) !offense.location.source_line.blank? end def report_line(location) source_line = location.source_line if location.first_line == location.last_line output.puts(source_line) else output.puts("#{source_line} #{yellow(ELLIPSES)}") end end def report_highlighted_area(highlighted_area) output.puts("#{' ' * highlighted_area.begin_pos}" \ "#{'^' * highlighted_area.size}") end end end end
smakagon/rubocop
lib/rubocop/formatter/clang_style_formatter.rb
Ruby
mit
1,635
27.684211
74
0.606728
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="An approach to developing modern web applications"> <meta name="author" content="Marc J. Greenberg"> <title>ElectricDiscoTech</title> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="css/style.min.css" type="text/css"> <script src="js/jquery.min.js"></script> <script src="js/uikit.min.js"></script> <script src="js/clipboard.min.js"></script> <script src="js/edt.min.js"></script> </head> <body class="edt-background"> <div class="inc:site/header.html"></div> <div class="uk-grid" data-uk-grid-margin> <div class="uk-width-medium-1-1"> <div class="edt-front2"></div> </div> </div> <div class="edt-middle"> <div class="uk-container uk-container-center"> <div class="uk-grid" data-uk-grid-margin> <div class="edt-sidebar uk-width-medium-1-4 uk-hidden-small"> <ul class="edt-nav uk-nav" data-uk-nav> <li class="uk-nav-header">Conceptual</li> <li><a href="readme.html">Dance Floor</a></li> <li><a href="source.html">First Steps</a></li> <li><a href="tools.html">Do the Hustle</a></li> <ul class="uk-nav uk-margin-left"> <li><a href="winivp.html"><i class="uk-icon-windows uk-margin-right"></i>Windows (ivp)</a></li> <li><a href="linuxivp.html"><i class="uk-icon-linux uk-margin-right"></i>Linux (ivp)</a></li> <li class="uk-active"><a href="osxivp.html"><i class="uk-icon-apple uk-margin-right"></i>Mac OS X (ivp)</a></li> </ul> <li><a href="bower.html">Disco Duck</a></li> <li><a href="tasks.html">Disco Pig</a></li> <li class="uk-nav-header"></li> <li><a href=""></a></li> </ul> </div> <div class="edt-main uk-width-medium-3-4"> <article class="uk-article"> <h2 id="osxivp"> <img src="img/osx.png" width="48"/> <a href="#osxivp" class="uk-link-reset">&nbsp;&nbsp;Mac OS X ivp for <i class="edt-tla2">EDT</i></a> </h2> <hr class="uk-article-divider"> <div class="uk-grid"> <div class="uk-width-medium-1-2"> <p> <a href="http://www.apple.com/osx/">Mac OS X</a> is currently my favorite dance partner. It is a common practice among dance instructors, to have the students switch partners frequently during the class in order to get them used to dancing with different partners. Using OS X as a base platform I can seamlessly run virtualized windows and/or linux on demand. </p> <p> While I mentioned this before, a good code editor is the hammer in a modern web application developers toolbox. For this project I am using one of Microsoft&apos;s latest concoctions, <a href=https://code.visualstudio.com/> Visual Studio Code</a>. It runs on windows, linux and os x. It&apos;s open source and <a href="https://github.com/Microsoft/vscode">forkable on github</a> and I really like. </p> </div> <div class="uk-width-medium-1-4"> <img src="img/discothink.png" width="80%"></a> </div> </div> </article> </div> <div class="uk-width-medium-1-4"> </div> </div> <!-- Git --> <div class="uk-grid"> <div class="uk-width-medium-1-4"> <a href="https://github.com/explore"> <img style="margin-top:2.5em;margin-left:-18px;" src="img/github-octocat.png"> </a> </div> <div class="uk-width-medium-2-4"> <hr class="uk-article-divider" style="margin-top:-48px;"> <h4><a href="http://git-scm.com/">Git</a></h4> <!--//http://git-scm.com/--> <p>Let&apos;s start a shell and validate the ability to run git from the command prompt:</p> <button class="edt-clip" data-clipboard-text="git --version"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border uk-margin-bottom">$ git --version git version 2.4.9 (Apple Git-60) </pre> <p> If for some reason you don&apos;t have git installed, you can download the <a href="http://git-scm.com/download/mac">git-osx-installer</a> from <a href="http://git-scm.com/">get-scm.com</a> If you can use use git then clone a copy of <span class="edt-tla2">EDT</span>: </p> <button class="edt-clip" data-clipboard-text="git clone https://github.com/codemarc/ElectricDiscoTech"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border">$ git clone https://github.com/codemarc/ElectricDiscoTech Cloning into 'ElectricDiscoTech'... remote: Counting objects: 254, done. remote: Compressing objects: 100% (30/30), done. remote: Total 254 (delta 10), reused 0 (delta 0), pack-reused 223 Receiving objects: 100% (254/254), 5.69 MiB | 3.31 MiB/s, done. Resolving deltas: 100% (101/101), done. Checking connectivity... done. </pre> </div> </div> <!-- NODE/NPM --> <div class="uk-grid"> <div class="uk-width-medium-1-4"> <a href="https://nodejs.org/"> <img style="margin-top:3.5em" src="img/nodejs-npm.png" width="70%"> </a> </div> <div class="uk-width-medium-2-4"> <hr class="uk-article-divider"> <h4><a href="https://www.npmjs.com/">Npm</a></h4> <p>Now let&apos;s see which version of npm is installed:</p> <button class="edt-clip" data-clipboard-text="npm -v"><i class="uk-icon-clipboard"></i></button> <pre>$ npm -v -bash: npm: command not found </pre> <p> Oops, forgot to install node. <a href="https://www.npmjs.com/">npm</a> is part of <a href="https://nodejs.org">Node.js</a>. On the Node.js website you can quickly find the download for installable package for OS X (x64). </p> <button class="edt-clip" data-clipboard-text="npm -v"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border">$ npm -v 2.14.7 </pre> <p> You can use npm to update npm. </p> <button class="edt-clip" data-clipboard-text="sudo npm install -g npm"><i class="uk-icon-clipboard"></i></button> <pre class="edt-border uk-margin-large-bottom">$ sudo npm install -g npm &vellip; $ npm -v 3.5.0 </pre> </div> </div> <!-- BOWER --> <div class="uk-grid"> <div class="uk-width-medium-1-4"> <a href="http://bower.io/"> <img class="uk-margin-left" src="img/bower.png" width="45%"> </a> </div> <div class="uk-width-medium-2-4"> <hr class="uk-article-divider" style="margin-top:-36px;"> <h4><a href="http://bower.io/">Bower</a></h4> <p><a href="http://bower.io/">bower</a> is billed as a package manager for the web. What it saves you from is endless hours of searching for source components. If you know the name of a component and its author has created a package for it (most popular components have the by now) then all you need to do to grab a copy using: <span class="uk-margin-left uk-text-primary">bower install &lt;package&gt;</span> </p> <p>To install or update bower run:</p> <button class="edt-clip" data-clipboard-text="npm install -g bower"><i class="uk-icon-clipboard"></i></button> <pre>$ npm install -g bower &vellip; $ bower -version 1.6.5 </pre> </div> </div> </div> <div class="inc:site/footer.html"></div> </body> <script>new Clipboard('.edt-clip');</script> </html>
codemarc/ElectricDiscoTech
dev/docs/osxivp.html
HTML
mit
10,042
52.137566
165
0.46196
false
package me.nereo.multi_image_selector; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.AbstractDraweeController; import com.facebook.drawee.drawable.ProgressBarDrawable; import com.facebook.drawee.drawable.ScalingUtils; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import java.io.File; import me.nereo.multi_image_selector.view.ClipImageBorderView; import me.nereo.multi_image_selector.view.zoomable.DefaultZoomableController; import me.nereo.multi_image_selector.view.zoomable.ZoomableDraweeView; /** * Created by sunny on 2015/12/22. * 图片裁剪 */ public class ClipPhotoActivity extends Activity implements OnClickListener, IBitmapShow { public static final String TAG = ClipPhotoActivity.class.getSimpleName(); private String imgUrl; private TextView mTitle; private Button mCommit; private ImageView mBack; private ZoomableDraweeView mGestureImageView; private ClipImageBorderView clip_image_borderview; //图片的平移与缩放 float mCurrentScale; float last_x = -1; float last_y = -1; boolean move = false; public static void startClipPhotoActivity(Context context, String uri) { Intent targetIntent = new Intent(context, ClipPhotoActivity.class); targetIntent.putExtra(TAG, uri); context.startActivity(targetIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clip_photo); setTitle("图片裁剪"); initIntentParams(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); /* new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { getBitmap(); } },100);*/ getBitmap(); } private void getBitmap() { int width = clip_image_borderview.getWidth(); int height = clip_image_borderview.getHeight(); Log.e("with", "with===" + width + "\nheight===" + height); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(screenWidth - 40, screenWidth - 40); layoutParams.gravity = Gravity.CENTER; mGestureImageView.setLayoutParams(layoutParams);*/ if (!TextUtils.isEmpty(imgUrl)) { // ImageLoaderUtils.load(imgUrl,mGestureImageView); //解决图片倒置 ImageRequest imageRequest = ImageRequestBuilder .newBuilderWithSource(Uri.parse("file://" + imgUrl)) .setAutoRotateEnabled(true).build(); //解决图片多指缩放 DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .setTapToRetryEnabled(true) .build(); /* DefaultZoomableController controller = DefaultZoomableController.newInstance(); controller.setEnabled(true);*/ GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources()) .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER) .setProgressBarImage(new ProgressBarDrawable()) .build(); mGestureImageView.setController(controller); mGestureImageView.setHierarchy(hierarchy); //图片等比例缩放 // getAvatarBitmap(imageRequest, controller, hierarchy, ClipPhotoActivity.this); } } @Override public void onContentChanged() { mTitle = (TextView) findViewById(R.id.photo_title); mGestureImageView = (ZoomableDraweeView) findViewById(R.id.gesture_iv); mBack = (ImageView) findViewById(R.id.btn_back); mBack.setOnClickListener(this); clip_image_borderview = (ClipImageBorderView) findViewById(R.id.clip_image_borderview); mCommit = (Button) findViewById(R.id.commit); mCommit.setOnClickListener(this); } @Override public void setTitle(CharSequence title) { mTitle.setText(title); } private void initIntentParams() { Intent mIntent = getIntent(); if (mIntent != null) { imgUrl = mIntent.getStringExtra(TAG); } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_back) { finish(); } else if (id == R.id.commit) { if (mGestureImageView != null) { Bitmap bm = mGestureImageView.clip(); Log.e("bm", "bm:" + bm.toString()); Intent resultIntent = new Intent(); Bundle mBundle = new Bundle(); mBundle.putParcelable(TAG, bm); resultIntent.putExtras(mBundle); setResult(101, resultIntent); finish(); } } } private void getAvatarBitmap(ImageRequest imageRequest, final DefaultZoomableController controller, final GenericDraweeHierarchy hierarchy, final IBitmapShow callback) { ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, ClipPhotoActivity.this); dataSource.subscribe(new BaseBitmapDataSubscriber() { @Override protected void onNewResultImpl(@Nullable Bitmap bitmap) { if (bitmap != null) { if (callback != null) { callback.onBitmapLoadedSuccess(bitmap, controller, hierarchy); } } } @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { } }, CallerThreadExecutor.getInstance()); } @Override public void onBitmapLoadedSuccess(Bitmap bm, DefaultZoomableController controller, GenericDraweeHierarchy hierarchy) { int bmWidth = bm.getWidth(); int bmHeight = bm.getHeight(); int newWidth = clip_image_borderview.getWidth() == 0 ? 200 : clip_image_borderview.getWidth(); int newHeight = clip_image_borderview.getHeight() == 0 ? 200 : clip_image_borderview.getHeight(); Log.e("bmWidth", "bmWidth:" + bmWidth + ",\nbmHeight:" + bmHeight + ",\nnewWidth:" + newWidth + ",\nnewHeight:" + newHeight); float scaleWidth = ((float) newWidth) / bmWidth; float scaleHeight = ((float) newHeight) / bmHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, bmWidth, bmHeight, matrix, true); mGestureImageView.setZoomableController(controller); mGestureImageView.setHierarchy(hierarchy); mGestureImageView.setImageBitmap(newBm); mGestureImageView.setOnTouchListener(new View.OnTouchListener() { float baseValue = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: float x = last_x = event.getRawX(); float y = last_y = event.getRawY(); move = false; break; case MotionEvent.ACTION_MOVE: if (event.getPointerCount() == 2) { //双指 float x1 = event.getX(0) - event.getX(1); float y1 = event.getY(0) - event.getY(1); //计算2点之间的距离 float value = (float) Math.sqrt(x1 * x1 + y1 * y1); if (baseValue == 0) { baseValue = value; } else { //由2点之间的距离来计算缩放比例 if ((value - baseValue) >= 10 || (baseValue - value) >= 10) { float scale = value / baseValue; img_scale(scale); } } } else if (event.getPointerCount() == 1) { //单指 float x2 = event.getRawX(); float y2 = event.getRawY(); x2 -= last_x; y2 -= last_y; if (x2 >= 10 || y2 >= 10 || x2 <= -10 || y2 <= -10) { img_translate(x2, y2); last_x = event.getRawX(); last_y = event.getRawY(); } } break; } return false; } }); } /** * 平移 * * @param x2 * @param y2 */ private void img_translate(float x2, float y2) { if (mGestureImageView != null) mGestureImageView.img_translate(x2, y2); } /** * 缩放 * * @param scale */ private void img_scale(float scale) { if (mGestureImageView != null) { mGestureImageView.img_scale(scale); } } }
SunnyLy/LocalImageChoose
multi-image-selector/src/main/java/me/nereo/multi_image_selector/ClipPhotoActivity.java
Java
mit
11,258
34.314286
146
0.595919
false
# NS Provides a Ruby wrapper for the Dutch NS API. ## Installation Add this line to your application's Gemfile: gem 'ns' And then execute: $ bundle Or install it yourself as: $ gem install ns ## Usage ns_client = Ns::Client.new(api_key, api_password) available_stations = ns_client.get_stations advice = ns_client.get_travel_advice(available_stations[0], available_stations[1]) Should return a travel advice based on the first and second available station. ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Added some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
jaimie-van-santen/ns
README.md
Markdown
mit
777
20.583333
78
0.675676
false
#include <onyxudp/udpclient.h> #include <stdio.h> #include <string.h> #include <assert.h> /* This test just makes sure the client library compiles and doens't crash on start. */ void on_error(udp_client_params_t *client, UDPERR code, char const *name) { fprintf(stderr, "on_error: code %d: %s\n", code, name); assert(!"should not happen"); } int main() { udp_client_params_t params; memset(&params, 0, sizeof(params)); params.app_id = 123; params.app_version = 321; params.on_error = on_error; params.on_idle = NULL; params.on_payload = NULL; params.on_disconnect = NULL; udp_client_t *client = udp_client_initialize(&params); assert(client != NULL); udp_client_terminate(client); return 0; }
jwatte/onyxnet
test/client/client.cpp
C++
mit
756
24.2
87
0.654762
false
<p>This is the test-route view.</p>
heynemann/tornado-angular
tests/sandbox/app/views/test-route.html
HTML
mit
36
35
35
0.666667
false
# alsa-switch Switching of Alsa audio devices the purpose of alsa-switch is to control the flow of multiple audio-streams going through a system while supporting priority streams You invoke audio-switch like this: auido-switch <input-device> <output-device> <control-file> for example audio-switch microphone speaker control1 This creates a named pipe named "control1", it is ready to connect "microphone" audio device to "speaker" audio device once the control pipe is telling it to do so. Writing a character to the control channel does this commands to send: '1'...'9' priority 1...9 announcement '0' end of announcement (channel muted) typical use case you have audio source1...9 you have virtual speakers 1...9 you mix virtual speaker 1...9 to physical speaker in alsa (/etc/asound.conf) you run alsa-switch and it will create control files 1...9 now all sound sources are muted if source 2 now has a level 8 priority annoucement it would write '8' into "control2" this would mute all audio streams which have no announcement or a priority announcement of level '9' 1 is the highest priority 9 is the lowest priority 0 is channel is muted At startup all channels are muted. Should a higher priority annoucement come in now on source 3, then source 2 would become muted too. Once source 3 is finished and source 2 is still in priority level 8, the audio from source 2 would be heard again.
andreasfink/alsa-switch
README.md
Markdown
mit
1,452
35.3
164
0.756198
false
package wanghaisheng.com.yakerweather; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
sheng-xiaoya/YakerWeather
app/src/test/java/wanghaisheng/com/yakerweather/ExampleUnitTest.java
Java
mit
322
20.533333
78
0.698758
false
// // 2016-01-21, jjuiddong // // »ç°¢ÇüÀ» ã´Â´Ù. // #pragma once namespace cvproc { class cDetectRect { public: cDetectRect(); virtual ~cDetectRect(); bool Init(); bool Detect(const cv::Mat &src); void UpdateParam(const cRecognitionEdgeConfig &recogConfig); public: bool m_show; cRectContour m_rect; int m_threshold1; int m_threshold2; int m_minArea; double m_minCos; double m_maxCos; vector<vector<cv::Point> > m_contours; cv::Mat m_gray; cv::Mat m_edges; cv::Mat m_binMat; }; }
jjuiddong/Common
CamCommon/detectrect.h
C
mit
529
12.225
62
0.646503
false
<?php /** * Copyright 2012 Klarna AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file demonstrates the use of the Klarna library to complete * the purchase and display the thank you page snippet. * * PHP version 5.3.4 * * @category Payment * @package Payment_Klarna * @subpackage Examples * @author Klarna <support@klarna.com> * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://developers.klarna.com/ */ require_once 'src/Klarna/Checkout.php'; session_start(); Klarna_Checkout_Order::$contentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"; $sharedSecret = 'sharedSecret'; @$checkoutId = $_GET['klarna_order']; $connector = Klarna_Checkout_Connector::create($sharedSecret); $order = new Klarna_Checkout_Order($connector, $checkoutId); $order->fetch(); if ($order['status'] == "checkout_complete") { // At this point make sure the order is created in your system and send a // confirmation email to the customer $update['status'] = 'created'; $update['merchant_reference'] = array( 'orderid1' => uniqid() ); $order->update($update); }
chrisVdd/Time2web
vendor/klarna/checkout/docs/examples/push.php
PHP
mit
1,718
30.814815
77
0.700815
false
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true }, // { fieldName: 'party', dataType: 'string' }, // ]; // const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const assasinatedPresidents = [16, 20, 25, 35]; function padStart(str: string, targetLength: number, padString: string) { // tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + str; } } const data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
coolkev/react-power-table
examples/src/filters.tsx
TypeScript
mit
4,479
39.333333
185
0.63078
false