text
stringlengths
2
99k
meta
dict
-- UPDATE `creature_template` SET `difficulty_entry_1`=57884, `difficulty_entry_2`=57885, `difficulty_entry_3`=57886 WHERE `entry`=56341; UPDATE `creature_template` SET `difficulty_entry_1`=57887, `difficulty_entry_2`=57888, `difficulty_entry_3`=57889 WHERE `entry`=56575; UPDATE `creature_template` SET `difficulty_entry_1`=57895, `difficulty_entry_2`=57896, `difficulty_entry_3`=57897 WHERE `entry`=53889; UPDATE `creature_template` SET `difficulty_entry_1`=57976, `difficulty_entry_2`=58137, `difficulty_entry_3`=58138 WHERE `entry`=56471; UPDATE `creature_template` SET `difficulty_entry_1`=57879, `difficulty_entry_2`=57880, `difficulty_entry_3`=57881 WHERE `entry`=53891; UPDATE `creature_template` SET `difficulty_entry_1`=57901, `difficulty_entry_2`=57902, `difficulty_entry_3`=57903 WHERE `entry`=56161; UPDATE `creature_template` SET `difficulty_entry_1`=57904, `difficulty_entry_2`=57905, `difficulty_entry_3`=57906 WHERE `entry`=56162; UPDATE `creature_template` SET `difficulty_entry_1`=49103 WHERE `entry`=40923; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags`=33554432, `unit_flags2`=134217728 WHERE `entry`=57884; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags`=33554432, `unit_flags2`=134217728 WHERE `entry`=57885; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags`=33554432, `unit_flags2`=134217728 WHERE `entry`=57886; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags`=33554432, `unit_flags2`=134217728 WHERE `entry`=57887; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags`=33554432, `unit_flags2`=134217728 WHERE `entry`=57888; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags`=33554432, `unit_flags2`=134217728 WHERE `entry`=57889; UPDATE `creature_template` SET `minlevel`=87, `maxlevel`=87, `exp`=3, `faction`=14 WHERE `entry`=57895; UPDATE `creature_template` SET `minlevel`=87, `maxlevel`=87, `exp`=3, `faction`=14 WHERE `entry`=57896; UPDATE `creature_template` SET `minlevel`=87, `maxlevel`=87, `exp`=3, `faction`=14 WHERE `entry`=57897; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14 WHERE `entry`=57976; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14 WHERE `entry`=58137; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14 WHERE `entry`=58138; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57879; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57880; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57881; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57901; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57902; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57903; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57904; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57905; UPDATE `creature_template` SET `minlevel`=88, `maxlevel`=88, `exp`=3, `faction`=14, `unit_flags2`=134250496 WHERE `entry`=57906; UPDATE `creature_template` SET `minlevel`=85, `maxlevel`=85, `exp`=3, `faction`=16 WHERE `entry`=49103; UPDATE `creature_template` SET `minlevel`=87, `maxlevel`=87, `exp`=3, `faction`=14 WHERE `entry`=58142; UPDATE `creature_template` SET `minlevel`=87, `maxlevel`=87, `exp`=3, `faction`=14 WHERE `entry`=58143;
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="HomeMessage" xml:space="preserve"> <value>Bonjour!</value> </data> </root>
{ "pile_set_name": "Github" }
include LICENSE.txt include README.rst recursive-include docs * recursive-include tests * global-exclude __pycache__ global-exclude *.py[cod]
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: MIT */ #ifndef __NVKM_BUS_PRIV_H__ #define __NVKM_BUS_PRIV_H__ #define nvkm_bus(p) container_of((p), struct nvkm_bus, subdev) #include <subdev/bus.h> struct nvkm_bus_func { void (*init)(struct nvkm_bus *); void (*intr)(struct nvkm_bus *); int (*hwsq_exec)(struct nvkm_bus *, u32 *, u32); u32 hwsq_size; }; int nvkm_bus_new_(const struct nvkm_bus_func *, struct nvkm_device *, int, struct nvkm_bus **); void nv50_bus_init(struct nvkm_bus *); void nv50_bus_intr(struct nvkm_bus *); #endif
{ "pile_set_name": "Github" }
/* operand types: + Z: no operand (Z,Z,Z,Z) + B: 8bit (B,S,B,B) + BB: 8+8bit (BB,SB,BS,SS) + BBB: 8+8+8bit (BBB,SBB,BSB,SSB) + BS: 8+16bit (BS,SS,BS,BS) + S: 16bit (S,S,S,S) + W: 24bit (W,W,W,W) */ /*----------------------------------------------------------------------- operation code operands semantics ------------------------------------------------------------------------*/ OPCODE(NOP, Z) /* no operation */ OPCODE(MOVE, BB) /* R(a) = R(b) */ OPCODE(LOADL, BB) /* R(a) = Pool(b) */ OPCODE(LOADI, BB) /* R(a) = mrb_int(b) */ OPCODE(LOADINEG, BB) /* R(a) = mrb_int(-b) */ OPCODE(LOADI__1, B) /* R(a) = mrb_int(-1) */ OPCODE(LOADI_0, B) /* R(a) = mrb_int(0) */ OPCODE(LOADI_1, B) /* R(a) = mrb_int(1) */ OPCODE(LOADI_2, B) /* R(a) = mrb_int(2) */ OPCODE(LOADI_3, B) /* R(a) = mrb_int(3) */ OPCODE(LOADI_4, B) /* R(a) = mrb_int(4) */ OPCODE(LOADI_5, B) /* R(a) = mrb_int(5) */ OPCODE(LOADI_6, B) /* R(a) = mrb_int(6) */ OPCODE(LOADI_7, B) /* R(a) = mrb_int(7) */ OPCODE(LOADSYM, BB) /* R(a) = Syms(b) */ OPCODE(LOADNIL, B) /* R(a) = nil */ OPCODE(LOADSELF, B) /* R(a) = self */ OPCODE(LOADT, B) /* R(a) = true */ OPCODE(LOADF, B) /* R(a) = false */ OPCODE(GETGV, BB) /* R(a) = getglobal(Syms(b)) */ OPCODE(SETGV, BB) /* setglobal(Syms(b), R(a)) */ OPCODE(GETSV, BB) /* R(a) = Special[Syms(b)] */ OPCODE(SETSV, BB) /* Special[Syms(b)] = R(a) */ OPCODE(GETIV, BB) /* R(a) = ivget(Syms(b)) */ OPCODE(SETIV, BB) /* ivset(Syms(b),R(a)) */ OPCODE(GETCV, BB) /* R(a) = cvget(Syms(b)) */ OPCODE(SETCV, BB) /* cvset(Syms(b),R(a)) */ OPCODE(GETCONST, BB) /* R(a) = constget(Syms(b)) */ OPCODE(SETCONST, BB) /* constset(Syms(b),R(a)) */ OPCODE(GETMCNST, BB) /* R(a) = R(a)::Syms(b) */ OPCODE(SETMCNST, BB) /* R(a+1)::Syms(b) = R(a) */ OPCODE(GETUPVAR, BBB) /* R(a) = uvget(b,c) */ OPCODE(SETUPVAR, BBB) /* uvset(b,c,R(a)) */ OPCODE(JMP, S) /* pc=a */ OPCODE(JMPIF, BS) /* if R(a) pc=b */ OPCODE(JMPNOT, BS) /* if !R(a) pc=b */ OPCODE(JMPNIL, BS) /* if R(a)==nil pc=b */ OPCODE(ONERR, S) /* rescue_push(a) */ OPCODE(EXCEPT, B) /* R(a) = exc */ OPCODE(RESCUE, BB) /* R(b) = R(a).isa?(R(b)) */ OPCODE(POPERR, B) /* a.times{rescue_pop()} */ OPCODE(RAISE, B) /* raise(R(a)) */ OPCODE(EPUSH, B) /* ensure_push(SEQ[a]) */ OPCODE(EPOP, B) /* A.times{ensure_pop().call} */ OPCODE(SENDV, BB) /* R(a) = call(R(a),Syms(b),*R(a+1)) */ OPCODE(SENDVB, BB) /* R(a) = call(R(a),Syms(b),*R(a+1),&R(a+2)) */ OPCODE(SEND, BBB) /* R(a) = call(R(a),Syms(b),R(a+1),...,R(a+c)) */ OPCODE(SENDB, BBB) /* R(a) = call(R(a),Syms(b),R(a+1),...,R(a+c),&R(a+c+1)) */ OPCODE(CALL, Z) /* R(0) = self.call(frame.argc, frame.argv) */ OPCODE(SUPER, BB) /* R(a) = super(R(a+1),... ,R(a+b+1)) */ OPCODE(ARGARY, BS) /* R(a) = argument array (16=m5:r1:m5:d1:lv4) */ OPCODE(ENTER, W) /* arg setup according to flags (23=m5:o5:r1:m5:k5:d1:b1) */ OPCODE(KEY_P, BB) /* R(a) = kdict.key?(Syms(b)) # todo */ OPCODE(KEYEND, Z) /* raise unless kdict.empty? # todo */ OPCODE(KARG, BB) /* R(a) = kdict[Syms(b)]; kdict.delete(Syms(b)) # todo */ OPCODE(RETURN, B) /* return R(a) (normal) */ OPCODE(RETURN_BLK, B) /* return R(a) (in-block return) */ OPCODE(BREAK, B) /* break R(a) */ OPCODE(BLKPUSH, BS) /* R(a) = block (16=m5:r1:m5:d1:lv4) */ OPCODE(ADD, B) /* R(a) = R(a)+R(a+1) */ OPCODE(ADDI, BB) /* R(a) = R(a)+mrb_int(b) */ OPCODE(SUB, B) /* R(a) = R(a)-R(a+1) */ OPCODE(SUBI, BB) /* R(a) = R(a)-mrb_int(b) */ OPCODE(MUL, B) /* R(a) = R(a)*R(a+1) */ OPCODE(DIV, B) /* R(a) = R(a)/R(a+1) */ OPCODE(EQ, B) /* R(a) = R(a)==R(a+1) */ OPCODE(LT, B) /* R(a) = R(a)<R(a+1) */ OPCODE(LE, B) /* R(a) = R(a)<=R(a+1) */ OPCODE(GT, B) /* R(a) = R(a)>R(a+1) */ OPCODE(GE, B) /* R(a) = R(a)>=R(a+1) */ OPCODE(ARRAY, BB) /* R(a) = ary_new(R(a),R(a+1)..R(a+b)) */ OPCODE(ARRAY2, BBB) /* R(a) = ary_new(R(b),R(b+1)..R(b+c)) */ OPCODE(ARYCAT, B) /* ary_cat(R(a),R(a+1)) */ OPCODE(ARYPUSH, B) /* ary_push(R(a),R(a+1)) */ OPCODE(ARYDUP, B) /* R(a) = ary_dup(R(a)) */ OPCODE(AREF, BBB) /* R(a) = R(b)[c] */ OPCODE(ASET, BBB) /* R(a)[c] = R(b) */ OPCODE(APOST, BBB) /* *R(a),R(a+1)..R(a+c) = R(a)[b..] */ OPCODE(INTERN, B) /* R(a) = intern(R(a)) */ OPCODE(STRING, BB) /* R(a) = str_dup(Lit(b)) */ OPCODE(STRCAT, B) /* str_cat(R(a),R(a+1)) */ OPCODE(HASH, BB) /* R(a) = hash_new(R(a),R(a+1)..R(a+b*2-1)) */ OPCODE(HASHADD, BB) /* R(a) = hash_push(R(a),R(a+1)..R(a+b*2)) */ OPCODE(HASHCAT, B) /* R(a) = hash_cat(R(a),R(a+1)) */ OPCODE(LAMBDA, BB) /* R(a) = lambda(SEQ[b],L_LAMBDA) */ OPCODE(BLOCK, BB) /* R(a) = lambda(SEQ[b],L_BLOCK) */ OPCODE(METHOD, BB) /* R(a) = lambda(SEQ[b],L_METHOD) */ OPCODE(RANGE_INC, B) /* R(a) = range_new(R(a),R(a+1),FALSE) */ OPCODE(RANGE_EXC, B) /* R(a) = range_new(R(a),R(a+1),TRUE) */ OPCODE(OCLASS, B) /* R(a) = ::Object */ OPCODE(CLASS, BB) /* R(a) = newclass(R(a),Syms(b),R(a+1)) */ OPCODE(MODULE, BB) /* R(a) = newmodule(R(a),Syms(b)) */ OPCODE(EXEC, BB) /* R(a) = blockexec(R(a),SEQ[b]) */ OPCODE(DEF, BB) /* R(a).newmethod(Syms(b),R(a+1)) */ OPCODE(ALIAS, BB) /* alias_method(target_class,Syms(a),Syms(b)) */ OPCODE(UNDEF, B) /* undef_method(target_class,Syms(a)) */ OPCODE(SCLASS, B) /* R(a) = R(a).singleton_class */ OPCODE(TCLASS, B) /* R(a) = target_class */ OPCODE(DEBUG, BBB) /* print a,b,c */ OPCODE(ERR, B) /* raise(LocalJumpError, Lit(a)) */ OPCODE(EXT1, Z) /* make 1st operand 16bit */ OPCODE(EXT2, Z) /* make 2nd operand 16bit */ OPCODE(EXT3, Z) /* make 1st and 2nd operands 16bit */ OPCODE(STOP, Z) /* stop VM */ OPCODE(LOADI16, BS) /* R(a) = mrb_int(b) */
{ "pile_set_name": "Github" }
/* The industrial I/O core * *Copyright (c) 2008 Jonathan Cameron * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * General attributes */ #ifndef _INDUSTRIAL_IO_SYSFS_H_ #define _INDUSTRIAL_IO_SYSFS_H_ struct iio_chan_spec; /** * struct iio_dev_attr - iio specific device attribute * @dev_attr: underlying device attribute * @address: associated register address * @l: list head for maintaining list of dynamically created attrs. */ struct iio_dev_attr { struct device_attribute dev_attr; u64 address; struct list_head l; struct iio_chan_spec const *c; }; #define to_iio_dev_attr(_dev_attr) \ container_of(_dev_attr, struct iio_dev_attr, dev_attr) ssize_t iio_read_const_attr(struct device *dev, struct device_attribute *attr, char *len); /** * struct iio_const_attr - constant device specific attribute * often used for things like available modes * @string: attribute string * @dev_attr: underlying device attribute */ struct iio_const_attr { const char *string; struct device_attribute dev_attr; }; #define to_iio_const_attr(_dev_attr) \ container_of(_dev_attr, struct iio_const_attr, dev_attr) /* Some attributes will be hard coded (device dependent) and not require an address, in these cases pass a negative */ #define IIO_ATTR(_name, _mode, _show, _store, _addr) \ { .dev_attr = __ATTR(_name, _mode, _show, _store), \ .address = _addr } #define IIO_DEVICE_ATTR(_name, _mode, _show, _store, _addr) \ struct iio_dev_attr iio_dev_attr_##_name \ = IIO_ATTR(_name, _mode, _show, _store, _addr) #define IIO_DEVICE_ATTR_NAMED(_vname, _name, _mode, _show, _store, _addr) \ struct iio_dev_attr iio_dev_attr_##_vname \ = IIO_ATTR(_name, _mode, _show, _store, _addr) #define IIO_CONST_ATTR(_name, _string) \ struct iio_const_attr iio_const_attr_##_name \ = { .string = _string, \ .dev_attr = __ATTR(_name, S_IRUGO, iio_read_const_attr, NULL)} #define IIO_CONST_ATTR_NAMED(_vname, _name, _string) \ struct iio_const_attr iio_const_attr_##_vname \ = { .string = _string, \ .dev_attr = __ATTR(_name, S_IRUGO, iio_read_const_attr, NULL)} /* Generic attributes of onetype or another */ /** * IIO_DEV_ATTR_RESET: resets the device **/ #define IIO_DEV_ATTR_RESET(_store) \ IIO_DEVICE_ATTR(reset, S_IWUSR, NULL, _store, 0) /** * IIO_DEV_ATTR_SAMP_FREQ - sets any internal clock frequency * @_mode: sysfs file mode/permissions * @_show: output method for the attribute * @_store: input method for the attribute **/ #define IIO_DEV_ATTR_SAMP_FREQ(_mode, _show, _store) \ IIO_DEVICE_ATTR(sampling_frequency, _mode, _show, _store, 0) /** * IIO_DEV_ATTR_SAMP_FREQ_AVAIL - list available sampling frequencies * @_show: output method for the attribute * * May be mode dependent on some devices **/ #define IIO_DEV_ATTR_SAMP_FREQ_AVAIL(_show) \ IIO_DEVICE_ATTR(sampling_frequency_available, S_IRUGO, _show, NULL, 0) /** * IIO_CONST_ATTR_AVAIL_SAMP_FREQ - list available sampling frequencies * @_string: frequency string for the attribute * * Constant version **/ #define IIO_CONST_ATTR_SAMP_FREQ_AVAIL(_string) \ IIO_CONST_ATTR(sampling_frequency_available, _string) #define IIO_DEV_ATTR_TEMP_RAW(_show) \ IIO_DEVICE_ATTR(in_temp_raw, S_IRUGO, _show, NULL, 0) #define IIO_CONST_ATTR_TEMP_OFFSET(_string) \ IIO_CONST_ATTR(in_temp_offset, _string) #define IIO_CONST_ATTR_TEMP_SCALE(_string) \ IIO_CONST_ATTR(in_temp_scale, _string) #endif /* _INDUSTRIAL_IO_SYSFS_H_ */
{ "pile_set_name": "Github" }
'use strict'; const forEach = require('lodash.foreach'), statsHelpers = require('../../support/statsHelpers'); module.exports = { statsPerCategory: {}, groups: {}, addToAggregate(coachData, group) { if (this.groups[group] === undefined) { this.groups[group] = {}; } // push the total score statsHelpers.pushGroupStats( this.statsPerCategory, this.groups[group], 'score', coachData.advice.score ); forEach(coachData.advice, (category, categoryName) => { if (category.score === undefined) { return; } // Push the score per category statsHelpers.pushGroupStats( this.statsPerCategory, this.groups[group], [categoryName, 'score'], category.score ); forEach(category.adviceList, (advice, adviceName) => { statsHelpers.pushGroupStats( this.statsPerCategory, this.groups[group], [categoryName, adviceName], advice.score ); }); }); }, summarize() { if (Object.keys(this.statsPerCategory).length === 0) { return undefined; } const summary = { groups: { total: this.summarizePerObject(this.statsPerCategory) } }; for (let group of Object.keys(this.groups)) { summary.groups[group] = this.summarizePerObject(this.groups[group]); } return summary; }, summarizePerObject(type) { return Object.keys(type).reduce((summary, categoryName) => { if (categoryName === 'score') { statsHelpers.setStatsSummary(summary, 'score', type[categoryName]); } else { const categoryData = {}; forEach(type[categoryName], (stats, name) => { statsHelpers.setStatsSummary(categoryData, name, stats); }); summary[categoryName] = categoryData; } return summary; }, {}); } };
{ "pile_set_name": "Github" }
# Copyright (c) 2019 Antmicro <www.antmicro.com> # SPDX-License-Identifier: Apache-2.0 config I2C_LITEX bool "LiteX I2C driver" depends on SOC_RISCV32_LITEX_VEXRISCV select I2C_BITBANG help Enable support for Litex I2C driver
{ "pile_set_name": "Github" }
import Comp from './index.vue' import { mount } from 'vue-test-utils' import { expect } from 'chai' describe('Selector', () => { it('basic', () => { const wrapper = mount(Comp, { propsData: { options: [] } }) expect(wrapper.name()).to.equal('selector') }) })
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd "> <camelContext id="camel" trace="true" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="file://src/test/resources?noop=true&amp;fileName=order.csv"/> <unmarshal><csv/></unmarshal> <split> <!-- use simple language to refer to the body --> <simple>body</simple> <to uri="mock:queue.csv"/> </split> </route> </camelContext> </beans>
{ "pile_set_name": "Github" }
typedef struct ebml_master { int pos; int sizebytes; } ebml_master; static int start_ebml_master() { return 42; }
{ "pile_set_name": "Github" }
// // AssemblyInfo.cs // // Author: // Alexander Köplinger (alexander.koeplinger@xamarin.com) // // (C) 2016 Xamarin, Inc. // // // 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. // using System; using System.Reflection; using System.Resources; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about the assembly [assembly: AssemblyTitle ("System.Reflection.Context.dll")] [assembly: AssemblyDescription ("System.Reflection.Context.dll")] [assembly: AssemblyDefaultAlias ("System.Reflection.Context.dll")] [assembly: AssemblyCompany (Consts.MonoCompany)] [assembly: AssemblyProduct (Consts.MonoProduct)] [assembly: AssemblyCopyright (Consts.MonoCopyright)] [assembly: AssemblyVersion (Consts.FxVersion)] [assembly: SatelliteContractVersion (Consts.FxVersion)] [assembly: AssemblyInformationalVersion (Consts.FxFileVersion)] [assembly: AssemblyFileVersion (Consts.FxFileVersion)] [assembly: NeutralResourcesLanguage ("en-US")] [assembly: CLSCompliant (true)] [assembly: AssemblyDelaySign (true)] [assembly: SecurityCritical] [assembly: ComVisible (false)]
{ "pile_set_name": "Github" }
perf-y += clone.o perf-y += fcntl.o perf-y += flock.o perf-y += fsmount.o perf-y += fspick.o ifeq ($(SRCARCH),$(filter $(SRCARCH),x86)) perf-y += ioctl.o endif perf-y += kcmp.o perf-y += mount_flags.o perf-y += move_mount.o perf-y += pkey_alloc.o perf-y += arch_prctl.o perf-y += prctl.o perf-y += renameat.o perf-y += sockaddr.o perf-y += socket.o perf-y += statx.o perf-y += sync_file_range.o perf-y += tracepoints/
{ "pile_set_name": "Github" }
import tensorflow as tf import numpy as np #%% def conv(layer_name, x, out_channels, kernel_size=[3,3], stride=[1,1,1,1], is_pretrain=True): '''Convolution op wrapper, use RELU activation after convolution Args: layer_name: e.g. conv1, pool1... x: input tensor, [batch_size, height, width, channels] out_channels: number of output channels (or comvolutional kernels) kernel_size: the size of convolutional kernel, VGG paper used: [3,3] stride: A list of ints. 1-D of length 4. VGG paper used: [1, 1, 1, 1] is_pretrain: if load pretrained parameters, freeze all conv layers. Depending on different situations, you can just set part of conv layers to be freezed. the parameters of freezed layers will not change when training. Returns: 4D tensor ''' in_channels = x.get_shape()[-1] with tf.variable_scope(layer_name): w = tf.get_variable(name='weights', trainable=is_pretrain, shape=[kernel_size[0], kernel_size[1], in_channels, out_channels], initializer=tf.contrib.layers.xavier_initializer()) # default is uniform distribution initialization b = tf.get_variable(name='biases', trainable=is_pretrain, shape=[out_channels], initializer=tf.constant_initializer(0.0)) x = tf.nn.conv2d(x, w, stride, padding='SAME', name='conv') x = tf.nn.bias_add(x, b, name='bias_add') x = tf.nn.relu(x, name='relu') return x #%% def pool(layer_name, x, kernel=[1,2,2,1], stride=[1,2,2,1], is_max_pool=True): '''Pooling op Args: x: input tensor kernel: pooling kernel, VGG paper used [1,2,2,1], the size of kernel is 2X2 stride: stride size, VGG paper used [1,2,2,1] padding: is_max_pool: boolen if True: use max pooling else: use avg pooling ''' if is_max_pool: x = tf.nn.max_pool(x, kernel, strides=stride, padding='SAME', name=layer_name) else: x = tf.nn.avg_pool(x, kernel, strides=stride, padding='SAME', name=layer_name) return x #%% def batch_norm(x): '''Batch normlization(I didn't include the offset and scale) ''' epsilon = 1e-3 batch_mean, batch_var = tf.nn.moments(x, [0]) x = tf.nn.batch_normalization(x, mean=batch_mean, variance=batch_var, offset=None, scale=None, variance_epsilon=epsilon) return x #%% def FC_layer(layer_name, x, out_nodes): '''Wrapper for fully connected layers with RELU activation as default Args: layer_name: e.g. 'FC1', 'FC2' x: input feature map out_nodes: number of neurons for current FC layer ''' shape = x.get_shape() if len(shape) == 4: size = shape[1].value * shape[2].value * shape[3].value else: size = shape[-1].value with tf.variable_scope(layer_name): w = tf.get_variable('weights', shape=[size, out_nodes], initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable('biases', shape=[out_nodes], initializer=tf.constant_initializer(0.0)) flat_x = tf.reshape(x, [-1, size]) # flatten into 1D x = tf.nn.bias_add(tf.matmul(flat_x, w), b) x = tf.nn.relu(x) return x #%% def loss(logits, labels): '''Compute loss Args: logits: logits tensor, [batch_size, n_classes] labels: one-hot labels ''' with tf.name_scope('loss') as scope: cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels,name='cross-entropy') loss = tf.reduce_mean(cross_entropy, name='loss') tf.summary.scalar(scope+'/loss', loss) return loss #%% def accuracy(logits, labels): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, """ with tf.name_scope('accuracy') as scope: correct = tf.equal(tf.arg_max(logits, 1), tf.arg_max(labels, 1)) correct = tf.cast(correct, tf.float32) accuracy = tf.reduce_mean(correct)*100.0 tf.summary.scalar(scope+'/accuracy', accuracy) return accuracy #%% def num_correct_prediction(logits, labels): """Evaluate the quality of the logits at predicting the label. Return: the number of correct predictions """ correct = tf.equal(tf.arg_max(logits, 1), tf.arg_max(labels, 1)) correct = tf.cast(correct, tf.int32) n_correct = tf.reduce_sum(correct) return n_correct #%% def optimize(loss, learning_rate, global_step): '''optimization, use Gradient Descent as default ''' with tf.name_scope('optimizer'): optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) #optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss, global_step=global_step) return train_op #%% def load(data_path, session): data_dict = np.load(data_path, encoding='latin1').item() keys = sorted(data_dict.keys()) for key in keys: with tf.variable_scope(key, reuse=True): for subkey, data in zip(('weights', 'biases'), data_dict[key]): session.run(tf.get_variable(subkey).assign(data)) #%% def test_load(): data_path = './/vgg16_pretrain//vgg16.npy' data_dict = np.load(data_path, encoding='latin1').item() keys = sorted(data_dict.keys()) for key in keys: weights = data_dict[key][0] biases = data_dict[key][1] print('\n') print(key) print('weights shape: ', weights.shape) print('biases shape: ', biases.shape) #%% def load_with_skip(data_path, session, skip_layer): data_dict = np.load(data_path, encoding='latin1').item() for key in data_dict: if key not in skip_layer: with tf.variable_scope(key, reuse=True): for subkey, data in zip(('weights', 'biases'), data_dict[key]): session.run(tf.get_variable(subkey).assign(data)) #%% def print_all_variables(train_only=True): """Print all trainable and non-trainable variables without tl.layers.initialize_global_variables(sess) Parameters ---------- train_only : boolean If True, only print the trainable variables, otherwise, print all variables. """ # tvar = tf.trainable_variables() if train_only else tf.all_variables() if train_only: t_vars = tf.trainable_variables() print(" [*] printing trainable variables") else: try: # TF1.0 t_vars = tf.global_variables() except: # TF0.12 t_vars = tf.all_variables() print(" [*] printing global variables") for idx, v in enumerate(t_vars): print(" var {:3}: {:15} {}".format(idx, str(v.get_shape()), v.name)) #%% ##***** the followings are just for test the tensor size at diferent layers *********## #%% def weight(kernel_shape, is_uniform = True): ''' weight initializer Args: shape: the shape of weight is_uniform: boolen type. if True: use uniform distribution initializer if False: use normal distribution initizalizer Returns: weight tensor ''' w = tf.get_variable(name='weights', shape=kernel_shape, initializer=tf.contrib.layers.xavier_initializer()) return w #%% def bias(bias_shape): '''bias initializer ''' b = tf.get_variable(name='biases', shape=bias_shape, initializer=tf.constant_initializer(0.0)) return b #%%
{ "pile_set_name": "Github" }
apiVersion: volumesnapshot.external-storage.k8s.io/v1 kind: VolumeSnapshot metadata: name: snapshot-demo-cstor namespace: default spec: persistentVolumeClaimName: cstor-vol1-1r-claim
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("apl", function() { var builtInOps = { ".": "innerProduct", "\\": "scan", "/": "reduce", "⌿": "reduce1Axis", "⍀": "scan1Axis", "¨": "each", "⍣": "power" }; var builtInFuncs = { "+": ["conjugate", "add"], "−": ["negate", "subtract"], "×": ["signOf", "multiply"], "÷": ["reciprocal", "divide"], "⌈": ["ceiling", "greaterOf"], "⌊": ["floor", "lesserOf"], "∣": ["absolute", "residue"], "⍳": ["indexGenerate", "indexOf"], "?": ["roll", "deal"], "⋆": ["exponentiate", "toThePowerOf"], "⍟": ["naturalLog", "logToTheBase"], "○": ["piTimes", "circularFuncs"], "!": ["factorial", "binomial"], "⌹": ["matrixInverse", "matrixDivide"], "<": [null, "lessThan"], "≤": [null, "lessThanOrEqual"], "=": [null, "equals"], ">": [null, "greaterThan"], "≥": [null, "greaterThanOrEqual"], "≠": [null, "notEqual"], "≡": ["depth", "match"], "≢": [null, "notMatch"], "∈": ["enlist", "membership"], "⍷": [null, "find"], "∪": ["unique", "union"], "∩": [null, "intersection"], "∼": ["not", "without"], "∨": [null, "or"], "∧": [null, "and"], "⍱": [null, "nor"], "⍲": [null, "nand"], "⍴": ["shapeOf", "reshape"], ",": ["ravel", "catenate"], "⍪": [null, "firstAxisCatenate"], "⌽": ["reverse", "rotate"], "⊖": ["axis1Reverse", "axis1Rotate"], "⍉": ["transpose", null], "↑": ["first", "take"], "↓": [null, "drop"], "⊂": ["enclose", "partitionWithAxis"], "⊃": ["diclose", "pick"], "⌷": [null, "index"], "⍋": ["gradeUp", null], "⍒": ["gradeDown", null], "⊤": ["encode", null], "⊥": ["decode", null], "⍕": ["format", "formatByExample"], "⍎": ["execute", null], "⊣": ["stop", "left"], "⊢": ["pass", "right"] }; var isOperator = /[\.\/⌿⍀¨⍣]/; var isNiladic = /⍬/; var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/; var isArrow = /←/; var isComment = /[⍝#].*$/; var stringEater = function(type) { var prev; prev = false; return function(c) { prev = c; if (c === type) { return prev === "\\"; } return true; }; }; return { startState: function() { return { prev: false, func: false, op: false, string: false, escape: false }; }, token: function(stream, state) { var ch, funcName; if (stream.eatSpace()) { return null; } ch = stream.next(); if (ch === '"' || ch === "'") { stream.eatWhile(stringEater(ch)); stream.next(); state.prev = true; return "string"; } if (/[\[{\(]/.test(ch)) { state.prev = false; return null; } if (/[\]}\)]/.test(ch)) { state.prev = true; return null; } if (isNiladic.test(ch)) { state.prev = false; return "niladic"; } if (/[¯\d]/.test(ch)) { if (state.func) { state.func = false; state.prev = false; } else { state.prev = true; } stream.eatWhile(/[\w\.]/); return "number"; } if (isOperator.test(ch)) { return "operator apl-" + builtInOps[ch]; } if (isArrow.test(ch)) { return "apl-arrow"; } if (isFunction.test(ch)) { funcName = "apl-"; if (builtInFuncs[ch] != null) { if (state.prev) { funcName += builtInFuncs[ch][1]; } else { funcName += builtInFuncs[ch][0]; } } state.func = true; state.prev = false; return "function " + funcName; } if (isComment.test(ch)) { stream.skipToEnd(); return "comment"; } if (ch === "∘" && stream.peek() === ".") { stream.next(); return "function jot-dot"; } stream.eatWhile(/[\w\$_]/); state.prev = true; return "keyword"; } }; }); CodeMirror.defineMIME("text/apl", "apl"); });
{ "pile_set_name": "Github" }
import { moduleForProperty } from '../../../helpers/properties'; import { create, triggerable } from 'ember-cli-page-object'; moduleForProperty('triggerable', function(test) { test("calls Ember's triggerEvent helper with proper args", async function(assert) { assert.expect(1); let expectedSelector = 'input'; let page = create({ foo: triggerable('focus', expectedSelector) }); await this.adapter.createTemplate(this, page, '<input />'); this.adapter.$(expectedSelector).on('focus', () => { assert.ok(1); }); await this.adapter.await(page.foo()); }); test("calls Ember's triggerEvent helper with static event options", async function(assert) { assert.expect(1); let page = create({ foo: triggerable('keypress', 'input', { eventProperties: { keyCode: 13 } }) }); await this.adapter.createTemplate(this, page, '<input />'); this.adapter.$('input').on('keypress', (e: KeyboardEvent) => assert.equal(e.keyCode, 13)); await this.adapter.await(page.foo()); }); test("calls Ember's triggerEvent helper with dynamic event options", async function(assert) { assert.expect(1); let page = create({ foo: triggerable('keypress', 'input') }); await this.adapter.createTemplate(this, page, '<input />'); this.adapter.$('input').on('keypress', (e: KeyboardEvent) => assert.equal(e.keyCode, 13)); await this.adapter.await(page.foo({ keyCode: 13 })); }); test("overrides static event options with dynamic event options", async function(assert) { assert.expect(1); let page = create({ foo: triggerable('keypress', 'input', { eventProperties: { keyCode: 0 } }) }); await this.adapter.createTemplate(this, page, '<input />'); this.adapter.$('input').on('keypress', (e: KeyboardEvent) => assert.equal(e.keyCode, 13)); await this.adapter.await(page.foo({ keyCode: 13 })); }); test('looks for elements inside the scope', async function(assert) { assert.expect(1); let page = create({ foo: triggerable('focus', 'input', { scope: '.scope' }) }); await this.adapter.createTemplate(this, page, '<div class="scope"><input/></div>'); this.adapter.$('.scope input').on('focus', () => assert.ok(1)); await this.adapter.await(page.foo()); }); test("looks for elements inside page's scope", async function(assert) { assert.expect(1); let page = create({ scope: '.scope', foo: triggerable('focus', 'input') }); await this.adapter.createTemplate(this, page, '<div class="scope"><input /></div>'); this.adapter.$('.scope input').on('focus', () => assert.ok(1)); await this.adapter.await(page.foo()); }); test('resets scope', async function(assert) { assert.expect(1); let page = create({ scope: '.scope', foo: triggerable('focus', 'input', { resetScope: true }) }); await this.adapter.createTemplate(this, page, '<input></input>'); this.adapter.$('input').on('focus', () => assert.ok(1)); await this.adapter.await(page.foo()); }); test('returns chainable object', async function(assert) { assert.expect(1); let page = create({ foo: triggerable('focus', 'input') }); await this.adapter.createTemplate(this, page, '<input/>'); let ret = page.foo(); assert.ok(ret.foo); await this.adapter.await(ret); }); test('finds element by index', async function(assert) { assert.expect(1); let expectedSelector = 'input:eq(3)'; let page = create({ foo: triggerable('focus', 'input', { at: 3 }) }); await this.adapter.createTemplate(this, page, '<input /><input /><input /><input />'); this.adapter.$(expectedSelector).on('focus', () => assert.ok(1)); await this.adapter.await(page.foo()); }); test('looks for elements outside the testing container', async function(assert) { assert.expect(1); let expectedContext = '#alternate-ember-testing'; let page = create({ foo: triggerable('focus', 'input', { testContainer: expectedContext }) }); await this.adapter.createTemplate(this, page, '<input />', { useAlternateContainer: true }); this.adapter.$('input', expectedContext).on('focus', () => assert.ok(1)); await this.adapter.await(page.foo()); }); test('looks for elements within test container specified at node level', async function(assert) { assert.expect(1); let expectedContext = '#alternate-ember-testing'; let page = create({ testContainer: expectedContext, foo: triggerable('focus', 'input') }); await this.adapter.createTemplate(this, page, '<input />', { useAlternateContainer: true }); this.adapter.$('input', expectedContext).on('focus', () => assert.ok(1)); await this.adapter.await(page.foo()); }); test("raises an error when the element doesn't exist", async function(assert) { assert.expect(1); let page = create({ foo: { bar: { baz: { qux: triggerable('focus', 'button') } } } }); await this.adapter.createTemplate(this, page); await this.adapter.throws(assert, function() { return page.foo.bar.baz.qux(); }, /page\.foo\.bar\.baz\.qux/, 'Element not found'); }); });
{ "pile_set_name": "Github" }
:103E000001C0A0C011248FEF94E09EBF8DBF84B786 :103E100090E89093610010926100882361F0982FE0 :103E20009A70923041F081FF02C097EF94BF282E24 :103E300080E0A3D0E5C082E082B988E181B985E065 :103E400080B986E88CBF8EE098D090D0813479F428 :103E50008DD0182F96D0123811F480E004C088E07D :103E6000113809F083E07ED080E17CD0EECF82343F :103E700019F484E18ED0F8CF853411F485E0FACFBF :103E8000853541F473D0C82F71D0D82FCC0FDD1FEA :103E900078D0EACF863519F484E07BD0DECF843643 :103EA00091F564D063D0F82E61D0D82E00E011E0F7 :103EB00058018FEFA81AB80A59D0F80180838501FC :103EC000FA10F6CF5ED0F5E4DF1201C0FFCF50E06C :103ED00040E063E0CE0136D08E01E0E0F1E06F011A :103EE00082E0C80ED11C4081518161E0C8012AD016 :103EF0000E5F1F4FF601FC10F2CF50E040E065E08E :103F0000CE0120D0B1CF843771F430D02FD0F82E2D :103F10002DD037D08E01F80185918F0123D0FA94EE :103F2000F110F9CFA1CF853739F42BD08EE11AD01B :103F300084E918D084E097CF813509F0A9CF88E0D3 :103F40001CD0A6CFFC010A0167BFE895112407B673 :103F500000FCFDCF667029F0452B19F481E187BF85 :103F6000E8950895159BFECF83B90895179BFECF62 :103F7000149901C0A89583B1089598E191BD81BDC0 :103F80000895F4DF803219F088E0F7DFFFCF84E195 :103F9000E9CFCF93C82FEADFC150E9F7CF91F1CF36 :023FFE000008B9 :0400000300003E00BB :00000001FF
{ "pile_set_name": "Github" }
#!/usr/bin/env bash set -eo pipefail this=`basename $0` show_help() { cat << EOF Usage: $this [-a APPLICATION_NAME] Clean-up pods with and without discovery enabled for the specified application. -a APPLICATION_NAME clean-up the pods with APPLICATION_NAME application. APPLICATION_NAME can be one of parsec or cloverleaf. EOF } if [ $# -eq 0 ] then show_help exit 1 fi app="parsec" OPTIND=1 options="ha:" while getopts $options option do case $option in a) if [ "$OPTARG" == "parsec" ] || [ "$OPTARG" == "cloverleaf" ] then app=$OPTARG else echo "Invalid application name." show_help exit 0 fi ;; h) show_help exit 0 ;; '?') show_help exit 1 ;; esac done echo "Using application name = $app." for i in {1..10} do kubectl delete po demo-$app-$i-wo-discovery done for i in {1..10} do kubectl delete po demo-$app-$i-with-discovery done
{ "pile_set_name": "Github" }
var VPAIDAdUnitWrapper = require('ads/vpaid/VPAIDAdUnitWrapper'); var VASTError = require('ads/vast/VASTError'); var utilities = require('utils/utilityFunctions'); var testUtils = require('../../test-utils'); describe("VPAIDAdUnitWrapper", function(){ var vpaidAdUnit; beforeEach(function(){ vpaidAdUnit = { 'handshakeVersion': utilities.noop, 'initAd': utilities.noop, 'startAd': utilities.noop, 'stopAd': utilities.noop, 'skipAd': utilities.noop, 'resizeAd': utilities.noop, 'pauseAd': utilities.noop, 'expandAd': utilities.noop, 'collapseAd': utilities.noop, 'subscribe': utilities.noop, 'unsubscribe': utilities.noop, 'unloadAdUnit': utilities.noop }; }); describe("checkVPAIDInterface", function(){ it("must return false if you pass an obj that does not fully implements the VPAID interface", function(){ assert.isFalse(VPAIDAdUnitWrapper.checkVPAIDInterface()); assert.isFalse(VPAIDAdUnitWrapper.checkVPAIDInterface(null)); assert.isFalse(VPAIDAdUnitWrapper.checkVPAIDInterface(utilities.noop)); assert.isFalse(VPAIDAdUnitWrapper.checkVPAIDInterface('foo')); }); it("must return true if you pass an object that fully implements the VPAID interface", function(){ assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); }); it("must return false if there is no method to subscribe to events", function(){ vpaidAdUnit.subscribe = undefined; assert.isFalse(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); }); it("must return true if there is a method to subscribe to events", function(){ assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); vpaidAdUnit.subscribe = undefined; vpaidAdUnit.on = utilities.noop; assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); vpaidAdUnit.on = undefined; vpaidAdUnit.addEventListener = utilities.noop; assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); }); it("must return false if there is no method to unsubscribe to events", function(){ vpaidAdUnit.unsubscribe = undefined; assert.isFalse(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); }); it("must return true if there is a method to unsubscribe from events", function(){ assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); vpaidAdUnit.unsubscribe = undefined; vpaidAdUnit.off = utilities.noop; assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); vpaidAdUnit.off = undefined; vpaidAdUnit.removeEventListener = utilities.noop; assert.isTrue(VPAIDAdUnitWrapper.checkVPAIDInterface(vpaidAdUnit)); }); }); describe("constructor", function(){ it("must return an instance of itself", function(){ assert.instanceOf(new VPAIDAdUnitWrapper(vpaidAdUnit, {responseTimeout: 5000}), VPAIDAdUnitWrapper); }); it("must throw a VASTError if the passed VPAIDAdUnit does not fully implement the VPAID api", function(){ [null, undefined, utilities.noop, 'foo', {}, []].forEach(function(invalidAdUnit) { assert.throws(function () { /*jshint unused:false*/ var adUnitWrapper = new VPAIDAdUnitWrapper(invalidAdUnit, {responseTimeout: 5000}); }, VASTError, 'on VPAIDAdUnitWrapper, the passed VPAID adUnit does not fully implement the VPAID interface'); }); }); it("must complain if you pass an options that is not a hash", function(){ assert.throws(function() { /*jshint unused:false*/ var adUnitWrapper = new VPAIDAdUnitWrapper(vpaidAdUnit, 'foo'); }, VASTError, "on VPAIDAdUnitWrapper, expected options hash but got 'foo'"); }); it("must publish the VPAIDAdUnit in '_adUnit'", function(){ var wrapper = new VPAIDAdUnitWrapper(vpaidAdUnit, {responseTimeout: 5000}); assert.equal(wrapper._adUnit, vpaidAdUnit); }); }); describe("instance", function(){ var wrapper; beforeEach(function(){ wrapper = new VPAIDAdUnitWrapper(vpaidAdUnit, {responseTimeout: 5000}); }); describe("adUnitAsyncCall", function(){ beforeEach(function(){ this.clock = sinon.useFakeTimers(); }); afterEach(function(){ this.clock.restore(); }); it("must complain if the method is not part of the adUnit", function(){ assert.throws(function () { wrapper.adUnitAsyncCall('foo', utilities.noop); }, VASTError, "on VPAIDAdUnitWrapper.adUnitAsyncCall, invalid method name"); }); it("must complain if there is no callback", function(){ assert.throws(function () { wrapper.adUnitAsyncCall('initAd'); }, VASTError, "on VPAIDAdUnitWrapper.adUnitAsyncCall, missing callback"); }); it("must call the adUnit method", function(){ sinon.spy(vpaidAdUnit, 'initAd'); wrapper.adUnitAsyncCall('initAd', utilities.noop); sinon.assert.calledOnce(vpaidAdUnit.initAd); }); it("must call the callback whenever the adUnit response comes back", function(){ var cb = sinon.spy(); sinon.spy(vpaidAdUnit, 'initAd'); wrapper.adUnitAsyncCall('initAd', cb); var wrapperCb = testUtils.firstArg(vpaidAdUnit.initAd); sinon.assert.notCalled(cb); wrapperCb(null); sinon.assert.calledOnce(cb); sinon.assert.calledWith(cb, null); //it must only call the callback once. this.clock.tick(wrapper.options.responseTimeout); sinon.assert.calledOnce(cb); }); describe("on response timeout", function(){ it("must call the callback with a VASTError", function(){ var cb = sinon.spy(); sinon.spy(vpaidAdUnit, 'initAd'); wrapper.adUnitAsyncCall('initAd', cb); var wrapperCb = testUtils.firstArg(vpaidAdUnit.initAd); sinon.assert.notCalled(cb); this.clock.tick(wrapper.options.responseTimeout); sinon.assert.calledOnce(cb); var error = testUtils.firstArg(cb); assert.instanceOf(error, VASTError); assert.equal(error.message, "VAST Error: on VPAIDAdUnitWrapper, timeout while waiting for a response on call 'initAd'"); //it must not call the callback again wrapperCb(null); sinon.assert.calledOnce(cb); }); }); }); describe("on", function(){ it("must call the subscribe method of the inner adunit", function(){ vpaidAdUnit.on = undefined; vpaidAdUnit.addEventListener = undefined; sinon.spy(vpaidAdUnit, 'subscribe'); wrapper.on('evtName', utilities.noop); sinon.assert.calledWith(vpaidAdUnit.subscribe, 'evtName', utilities.noop); }); it("must call the addEventListener method of the inner adunit", function(){ vpaidAdUnit.subscribe = undefined; vpaidAdUnit.on = undefined; vpaidAdUnit.addEventListener = sinon.spy(); wrapper.on('evtName', utilities.noop); sinon.assert.calledWith(vpaidAdUnit.addEventListener, 'evtName', utilities.noop); }); it("must call the on method of the inner adunit", function(){ vpaidAdUnit.subscribe = undefined; vpaidAdUnit.addEventListener = undefined; vpaidAdUnit.on = sinon.spy(); wrapper.on('evtName', utilities.noop); sinon.assert.calledWith(vpaidAdUnit.on, 'evtName', utilities.noop); }); }); describe("off", function(){ it("must call the unsubscribe method of the inner adunit", function(){ vpaidAdUnit.off = undefined; vpaidAdUnit.removeEventListener = undefined; sinon.spy(vpaidAdUnit, 'unsubscribe'); wrapper.off('evtName', utilities.noop); sinon.assert.calledWith(vpaidAdUnit.unsubscribe, 'evtName', utilities.noop); }); it("must call the removeEventListener method of the inner adunit", function(){ vpaidAdUnit.unsubscribe = undefined; vpaidAdUnit.on = undefined; vpaidAdUnit.removeEventListener = sinon.spy(); wrapper.off('evtName', utilities.noop); sinon.assert.calledWith(vpaidAdUnit.removeEventListener, 'evtName', utilities.noop); }); it("must call the off method of the inner adunit", function(){ vpaidAdUnit.unsubscribe = undefined; vpaidAdUnit.removeEventListener = undefined; vpaidAdUnit.off = sinon.spy(); wrapper.off('evtName', utilities.noop); sinon.assert.calledWith(vpaidAdUnit.off, 'evtName', utilities.noop); }); }); describe("waitForEvent", function(){ it("must complain if you don't pass an evtName", function(){ assert.throws(function () { wrapper.waitForEvent(); }, VASTError, "on VPAIDAdUnitWrapper.waitForEvent, missing evt name"); }); it("must complain if you don't pass a callback", function(){ assert.throws(function () { wrapper.waitForEvent('adInit'); }, VASTError, "on VPAIDAdUnitWrapper.waitForEvent, missing callback"); }); it("must subscribe to the passed event", function(){ var listener = sinon.spy(); sinon.spy(wrapper, 'on'); wrapper.waitForEvent('adInit', listener); sinon.assert.calledWith(wrapper.on, 'adInit', sinon.match.func); }); describe("on response", function(){ it("must call the callback with the null as the first arg and the listener args afterwards", function(){ var callback = sinon.spy(); var listener; sinon.spy(wrapper, 'on'); wrapper.waitForEvent('adInit', callback); listener = testUtils.secondArg(wrapper.on); //We simulate the response var evt = {type: 'adInit'}; listener(evt, 'foo', 'bar'); sinon.assert.calledWith(callback, null, evt, 'foo', 'bar'); }); }); describe("on response timeout", function(){ beforeEach(function(){ this.clock = sinon.useFakeTimers(); }); afterEach(function(){ this.clock.restore(); }); it("must call the callback with a vastError", function(){ var callback = sinon.spy(); var error; sinon.spy(wrapper, 'on'); wrapper.waitForEvent('adInit', callback); this.clock.tick(wrapper.options.responseTimeout); sinon.assert.calledOnce(callback); error = testUtils.firstArg(callback); assert.instanceOf(error, VASTError); assert.equal(error.message, "VAST Error: on VPAIDAdUnitWrapper.waitForEvent, timeout while waiting for event 'adInit'"); }); it("must not call the callback once the event response comes", function(){ var callback = sinon.spy(); var listener; sinon.spy(wrapper, 'on'); wrapper.waitForEvent('adInit', callback); listener = testUtils.secondArg(wrapper.on); this.clock.tick(wrapper.options.responseTimeout); sinon.assert.calledOnce(callback); listener('adInint'); sinon.assert.calledOnce(callback); }); }); }); }); });
{ "pile_set_name": "Github" }
module github.com/ardanlabs/garagesale go 1.12 require ( github.com/GuiaBolso/darwin v0.0.0-20170210191649-86919dfcf808 github.com/cznic/ql v1.2.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/go-chi/chi v4.0.2+incompatible github.com/go-playground/locales v0.12.1 github.com/go-playground/universal-translator v0.16.0 github.com/google/go-cmp v0.3.0 github.com/google/uuid v1.1.1 github.com/jmoiron/sqlx v1.2.0 github.com/leodido/go-urn v1.1.0 // indirect github.com/lib/pq v1.1.1 github.com/pkg/errors v0.8.1 github.com/pmezard/go-difflib v1.0.0 // indirect github.com/stretchr/testify v1.2.2 // indirect golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576 google.golang.org/appengine v1.4.0 // indirect gopkg.in/go-playground/assert.v1 v1.2.1 // indirect gopkg.in/go-playground/validator.v9 v9.27.0 )
{ "pile_set_name": "Github" }
#ifndef BOOST_SCOPED_ARRAY_HPP_INCLUDED #define BOOST_SCOPED_ARRAY_HPP_INCLUDED // (C) Copyright Greg Colvin and Beman Dawes 1998, 1999. // Copyright (c) 2001, 2002 Peter Dimov // // 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) // // http://www.boost.org/libs/smart_ptr/scoped_array.htm // #include <boost/smart_ptr/scoped_array.hpp> #endif // #ifndef BOOST_SCOPED_ARRAY_HPP_INCLUDED
{ "pile_set_name": "Github" }
page 20016 "APIV1 - Journals" { APIVersion = 'v1.0'; Caption = 'journals', Locked = true; ChangeTrackingAllowed = true; DelayedInsert = true; EntityName = 'journal'; EntitySetName = 'journals'; ODataKeyFields = SystemId; PageType = API; SourceTable = "Gen. Journal Batch"; Extensible = false; layout { area(content) { repeater(Group) { field(id; SystemId) { Caption = 'id', Locked = true; Editable = false; } field("code"; Name) { Caption = 'code', Locked = true; ShowMandatory = true; } field(displayName; Description) { Caption = 'displayName', Locked = true; } field(lastModifiedDateTime; "Last Modified DateTime") { Caption = 'lastModifiedDateTime', Locked = true; } field(balancingAccountId; BalAccountId) { Caption = 'balancingAccountId', Locked = true; } field(balancingAccountNumber; "Bal. Account No.") { Caption = 'balancingAccountNumber', Locked = true; Editable = false; } } part(journalLines; 20049) { ApplicationArea = All; Caption = 'JournalLines', Locked = true; EntityName = 'journalLine'; EntitySetName = 'journalLines'; SubPageLink = "Journal Batch Id" = FIELD(SystemId); } } } actions { } trigger OnNewRecord(BelowxRec: Boolean) begin "Journal Template Name" := GraphMgtJournal.GetDefaultJournalLinesTemplateName(); end; trigger OnOpenPage() begin SETRANGE("Journal Template Name", GraphMgtJournal.GetDefaultJournalLinesTemplateName()); end; var GraphMgtJournal: Codeunit "Graph Mgt - Journal"; ThereIsNothingToPostErr: Label 'There is nothing to post.'; CannotFindBatchErr: Label 'The General Journal Batch with ID %1 cannot be found.', Comment = '%1 - the System ID of the general journal batch'; [ServiceEnabled] [Scope('Cloud')] procedure post(var ActionContext: WebServiceActionContext) var GenJournalBatch: Record "Gen. Journal Batch"; begin GetBatch(GenJournalBatch); PostBatch(GenJournalBatch); SetActionResponse(ActionContext, SystemId); end; local procedure PostBatch(var GenJournalBatch: Record "Gen. Journal Batch") var GenJournalLine: Record "Gen. Journal Line"; begin GenJournalLine.SETRANGE("Journal Template Name", GenJournalBatch."Journal Template Name"); GenJournalLine.SETRANGE("Journal Batch Name", GenJournalBatch.Name); IF NOT GenJournalLine.FINDFIRST() THEN ERROR(ThereIsNothingToPostErr); CODEUNIT.RUN(CODEUNIT::"Gen. Jnl.-Post", GenJournalLine); end; local procedure GetBatch(var GenJournalBatch: Record "Gen. Journal Batch") begin if not GenJournalBatch.GetBySystemId(SystemId) then Error(CannotFindBatchErr, SystemId); end; local procedure SetActionResponse(var ActionContext: WebServiceActionContext; GenJournalBatchId: Guid) var begin ActionContext.SetObjectType(ObjectType::Page); ActionContext.SetObjectId(Page::"APIV1 - Journals"); ActionContext.AddEntityKey(FieldNo(SystemId), GenJournalBatchId); ActionContext.SetResultCode(WebServiceActionResultCode::Deleted); end; }
{ "pile_set_name": "Github" }
// // UIButton+MRButton.m // test // // Created by 刘入徵 on 2017/4/15. // Copyright © 2017年 Mix_Reality. All rights reserved. // #import "UIButton+MRButton.h" #import <objc/runtime.h> static const void *blockKey = &blockKey; @implementation UIButton (MRButton) @dynamic block; // 用 Runtime 强制给类目添加属性 - (void)setBlock:(Touch)block{ objc_setAssociatedObject(self, blockKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (Touch)block{ return objc_getAssociatedObject(self, blockKey); } - (void)buttonActionWith:(Touch)block{ self.block = block; // 调用此方法以触发block if(!self.block){ return; } [self addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside]; } - (void)clickAction:(UIButton *)button{ if(self.block){ self.block(button); } } /** 设置圆角 */ - (void)setCornerRadius:(NSInteger)cornerRadius{ self.layer.cornerRadius = cornerRadius; self.layer.masksToBounds = YES; // 开启离屏渲染 self.layer.rasterizationScale = [[UIScreen mainScreen] scale]; self.layer.shouldRasterize = YES; } @end
{ "pile_set_name": "Github" }
#pragma once #include "Quaternion.h" namespace Echo { class Transform { public: Vector3 m_pos; Vector3 m_scale; Quaternion m_quat; public: Transform() { reset(); } Transform(const Vector3& pos, const Vector3& scale = Vector3::ONE, const Quaternion& rot=Quaternion::IDENTITY); // transector3 Vector3 transformVec3(const Vector3& orig) const; // build matrix void buildMatrix(Matrix4& mat) const; // build inverse matrix void buildInvMatrix(Matrix4& invMat) const; // operate "*" Transform operator* (const Transform& b) const; // reset void reset(); }; }
{ "pile_set_name": "Github" }
# Intro to Python ### Overview: Today we'll introduce the basics of Python, a powerful programming language for data analysis, visualization, and simple application development. It's a great starter language because its syntax is simple and straightforward. We will use Anaconda to install Python onto our computers, and we will work with Python via the Jupyter notebook. Jupyter notebooks let you use Python in an interactive coding environment that's easily packaged up and shared with others. ### Readings: - Overview of the [Jupyter/IPython Notebook](https://ipython.org/ipython-doc/stable/notebook/notebook.html) - Chapters 2 and 3 of [Think Python](http://www.greenteapress.com/thinkpython/) (don't worry, the chapters are only like 8 pages long) - *Optional*, if you're not familiar with the command prompt/terminal - read the ['basics' and 'folders' sections](http://dosprompt.info/), or [this guide](http://guides.macrumors.com/Terminal) if you're a Mac user - *Optional*, short [overview of Anaconda](https://store.continuum.io/static/img/Anaconda-Quickstart.pdf) if you're not already familiar with it ### Getting Started: 1. Install [Anaconda](https://www.continuum.io/downloads) onto your computer. 2. Open a command prompt and change directory to this directory. 3. Run the command: jupyter notebook 4. A server window will open. Click the IPython notebook to launch it.
{ "pile_set_name": "Github" }
.PHONY: all all: test # This rule tells make how to build hello from test1.cpp test: test1.cpp g++ -O2 -I../../include test1.cpp -o test1.o # This rule tells make to delete the program .PHONY: clean clean: rm -f test1.o
{ "pile_set_name": "Github" }
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; public name = "Vishwas"; public message = ""; }
{ "pile_set_name": "Github" }
BEGIN {use File::Basename; push @INC, dirname($0); } require "valve_perl_helpers.pl"; use Cwd; use String::CRC32; my $txtfilename = shift; my $arg = shift; my $is360 = 0; my $platformextension = ""; if( $arg =~ m/-x360/i ) { $is360 = 1; $platformextension = ".360"; } open TXTFILE, "<$txtfilename"; my $src; my $dst; while( $src = <TXTFILE> ) { # get rid of comments $src =~ s,//.*,,g; # skip blank lines if( $src =~ m/^\s*$/ ) { next; } # Get rid of newlines. $src =~ s/\n//g; # Save off the shader source filename. my $dst = $src; $dst =~ s/_tmp//gi; # Does the dst exist? my $dstexists = -e $dst; my $srcexists = -e $src; # What are the time stamps for the src and dst? my $srcmodtime = ( stat $src )[9]; my $dstmodtime = ( stat $dst )[9]; # Open for edit or add if different than what is in perforce already. if( !$dstexists || ( $srcmodtime != $dstmodtime ) ) { # Make the target writable if it exists if( $dstexists ) { MakeFileWritable( $dst ); } my $dir = $dst; $dir =~ s,([^/\\]*$),,; # rip the filename off the end my $filename = $1; # create the target directory if it doesn't exist if( !$dstexists ) { &MakeDirHier( $dir, 0777 ); } # copy the file to its targets. . . we want to see STDERR here if there is an error. my $cmd = "copy $src $dst > nul"; # print STDERR "$cmd\n"; system $cmd; MakeFileReadOnly( $dst ); } } close TXTFILE;
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <ZopeData> <record id="1" aka="AAAAAAAAAAE="> <pickle> <global name="ERP5 Form" module="erp5.portal_type"/> </pickle> <pickle> <dictionary> <item> <key> <string>_bind_names</string> </key> <value> <object> <klass> <global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/> </klass> <tuple/> <state> <dictionary> <item> <key> <string>_asgns</string> </key> <value> <dictionary/> </value> </item> </dictionary> </state> </object> </value> </item> <item> <key> <string>_objects</string> </key> <value> <tuple/> </value> </item> <item> <key> <string>action</string> </key> <value> <string>Base_edit</string> </value> </item> <item> <key> <string>description</string> </key> <value> <string></string> </value> </item> <item> <key> <string>edit_order</string> </key> <value> <list/> </value> </item> <item> <key> <string>encoding</string> </key> <value> <string>UTF-8</string> </value> </item> <item> <key> <string>enctype</string> </key> <value> <string></string> </value> </item> <item> <key> <string>group_list</string> </key> <value> <list> <string>left</string> <string>right</string> <string>center</string> <string>bottom</string> </list> </value> </item> <item> <key> <string>groups</string> </key> <value> <dictionary> <item> <key> <string>bottom</string> </key> <value> <list/> </value> </item> <item> <key> <string>center</string> </key> <value> <list> <string>my_inode_path</string> <string>my_description</string> </list> </value> </item> <item> <key> <string>left</string> </key> <value> <list> <string>my_id</string> <string>my_title</string> <string>my_enabled</string> <string>my_sense_method_id</string> </list> </value> </item> <item> <key> <string>right</string> </key> <value> <list> <string>my_node_list</string> </list> </value> </item> </dictionary> </value> </item> <item> <key> <string>id</string> </key> <value> <string>Inotify_view</string> </value> </item> <item> <key> <string>method</string> </key> <value> <string>POST</string> </value> </item> <item> <key> <string>name</string> </key> <value> <string></string> </value> </item> <item> <key> <string>pt</string> </key> <value> <string>form_view</string> </value> </item> <item> <key> <string>row_length</string> </key> <value> <int>4</int> </value> </item> <item> <key> <string>stored_encoding</string> </key> <value> <string>UTF-8</string> </value> </item> <item> <key> <string>title</string> </key> <value> <string>Inotify</string> </value> </item> <item> <key> <string>unicode_mode</string> </key> <value> <int>0</int> </value> </item> <item> <key> <string>update_action</string> </key> <value> <string></string> </value> </item> <item> <key> <string>update_action_title</string> </key> <value> <string></string> </value> </item> </dictionary> </pickle> </record> </ZopeData>
{ "pile_set_name": "Github" }
/* New Hydra driver using generic 8390 core */ /* Based on old hydra driver by Topi Kanerva (topi@susanna.oulu.fi) */ /* This file is subject to the terms and conditions of the GNU General */ /* Public License. See the file COPYING in the main directory of the */ /* Linux distribution for more details. */ /* Peter De Schrijver (p2@mind.be) */ /* Oldenburg 2000 */ /* The Amiganet is a Zorro-II board made by Hydra Systems. It contains a */ /* NS8390 NIC (network interface controller) clone, 16 or 64K on-board RAM */ /* and 10BASE-2 (thin coax) and AUI connectors. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/bitops.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/amigaints.h> #include <asm/amigahw.h> #include <linux/zorro.h> #define EI_SHIFT(x) (ei_local->reg_offset[x]) #define ei_inb(port) in_8(port) #define ei_outb(val,port) out_8(port,val) #define ei_inb_p(port) in_8(port) #define ei_outb_p(val,port) out_8(port,val) static const char version[] = "8390.c:v1.10cvs 9/23/94 Donald Becker (becker@cesdis.gsfc.nasa.gov)\n"; #include "lib8390.c" #define NE_EN0_DCFG (0x0e*2) #define NESM_START_PG 0x0 /* First page of TX buffer */ #define NESM_STOP_PG 0x40 /* Last page +1 of RX ring */ #define HYDRA_NIC_BASE 0xffe1 #define HYDRA_ADDRPROM 0xffc0 #define HYDRA_VERSION "v3.0alpha" #define WORDSWAP(a) ((((a)>>8)&0xff) | ((a)<<8)) static int __devinit hydra_init_one(struct zorro_dev *z, const struct zorro_device_id *ent); static int __devinit hydra_init(struct zorro_dev *z); static int hydra_open(struct net_device *dev); static int hydra_close(struct net_device *dev); static void hydra_reset_8390(struct net_device *dev); static void hydra_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page); static void hydra_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset); static void hydra_block_output(struct net_device *dev, int count, const unsigned char *buf, int start_page); static void __devexit hydra_remove_one(struct zorro_dev *z); static struct zorro_device_id hydra_zorro_tbl[] __devinitdata = { { ZORRO_PROD_HYDRA_SYSTEMS_AMIGANET }, { 0 } }; static struct zorro_driver hydra_driver = { .name = "hydra", .id_table = hydra_zorro_tbl, .probe = hydra_init_one, .remove = __devexit_p(hydra_remove_one), }; static int __devinit hydra_init_one(struct zorro_dev *z, const struct zorro_device_id *ent) { int err; if (!request_mem_region(z->resource.start, 0x10000, "Hydra")) return -EBUSY; if ((err = hydra_init(z))) { release_mem_region(z->resource.start, 0x10000); return -EBUSY; } return 0; } static int __devinit hydra_init(struct zorro_dev *z) { struct net_device *dev; unsigned long board = ZTWO_VADDR(z->resource.start); unsigned long ioaddr = board+HYDRA_NIC_BASE; const char name[] = "NE2000"; int start_page, stop_page; int j; int err; static u32 hydra_offsets[16] = { 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, }; dev = ____alloc_ei_netdev(0); if (!dev) return -ENOMEM; SET_MODULE_OWNER(dev); for(j = 0; j < ETHER_ADDR_LEN; j++) dev->dev_addr[j] = *((u8 *)(board + HYDRA_ADDRPROM + 2*j)); /* We must set the 8390 for word mode. */ z_writeb(0x4b, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; dev->base_addr = ioaddr; dev->irq = IRQ_AMIGA_PORTS; /* Install the Interrupt handler */ if (request_irq(IRQ_AMIGA_PORTS, __ei_interrupt, IRQF_SHARED, "Hydra Ethernet", dev)) { free_netdev(dev); return -EAGAIN; } ei_status.name = name; ei_status.tx_start_page = start_page; ei_status.stop_page = stop_page; ei_status.word16 = 1; ei_status.bigendian = 1; ei_status.rx_start_page = start_page + TX_PAGES; ei_status.reset_8390 = &hydra_reset_8390; ei_status.block_input = &hydra_block_input; ei_status.block_output = &hydra_block_output; ei_status.get_8390_hdr = &hydra_get_8390_hdr; ei_status.reg_offset = hydra_offsets; dev->open = &hydra_open; dev->stop = &hydra_close; #ifdef CONFIG_NET_POLL_CONTROLLER dev->poll_controller = __ei_poll; #endif __NS8390_init(dev, 0); err = register_netdev(dev); if (err) { free_irq(IRQ_AMIGA_PORTS, dev); free_netdev(dev); return err; } zorro_set_drvdata(z, dev); printk(KERN_INFO "%s: Hydra at 0x%08lx, address " "%02x:%02x:%02x:%02x:%02x:%02x (hydra.c " HYDRA_VERSION ")\n", dev->name, z->resource.start, dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2], dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5]); return 0; } static int hydra_open(struct net_device *dev) { __ei_open(dev); return 0; } static int hydra_close(struct net_device *dev) { if (ei_debug > 1) printk(KERN_DEBUG "%s: Shutting down ethercard.\n", dev->name); __ei_close(dev); return 0; } static void hydra_reset_8390(struct net_device *dev) { printk(KERN_INFO "Hydra hw reset not there\n"); } static void hydra_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page) { int nic_base = dev->base_addr; short *ptrs; unsigned long hdr_start= (nic_base-HYDRA_NIC_BASE) + ((ring_page - NESM_START_PG)<<8); ptrs = (short *)hdr; *(ptrs++) = z_readw(hdr_start); *((short *)hdr) = WORDSWAP(*((short *)hdr)); hdr_start += 2; *(ptrs++) = z_readw(hdr_start); *((short *)hdr+1) = WORDSWAP(*((short *)hdr+1)); } static void hydra_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset) { unsigned long nic_base = dev->base_addr; unsigned long mem_base = nic_base - HYDRA_NIC_BASE; unsigned long xfer_start = mem_base + ring_offset - (NESM_START_PG<<8); if (count&1) count++; if (xfer_start+count > mem_base + (NESM_STOP_PG<<8)) { int semi_count = (mem_base + (NESM_STOP_PG<<8)) - xfer_start; z_memcpy_fromio(skb->data,xfer_start,semi_count); count -= semi_count; z_memcpy_fromio(skb->data+semi_count, mem_base, count); } else z_memcpy_fromio(skb->data, xfer_start,count); } static void hydra_block_output(struct net_device *dev, int count, const unsigned char *buf, int start_page) { unsigned long nic_base = dev->base_addr; unsigned long mem_base = nic_base - HYDRA_NIC_BASE; if (count&1) count++; z_memcpy_toio(mem_base+((start_page - NESM_START_PG)<<8), buf, count); } static void __devexit hydra_remove_one(struct zorro_dev *z) { struct net_device *dev = zorro_get_drvdata(z); unregister_netdev(dev); free_irq(IRQ_AMIGA_PORTS, dev); release_mem_region(ZTWO_PADDR(dev->base_addr)-HYDRA_NIC_BASE, 0x10000); free_netdev(dev); } static int __init hydra_init_module(void) { return zorro_register_driver(&hydra_driver); } static void __exit hydra_cleanup_module(void) { zorro_unregister_driver(&hydra_driver); } module_init(hydra_init_module); module_exit(hydra_cleanup_module); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
# --------------------------------------------------------------------------- # # Copyright (c) 2005, Greg Stein # # 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 software lives at: # http://gstein.googlecode.com/svn/trunk/python/daemonize.py # import os import signal import sys import time import stat import multiprocessing # requires Python 2.6 # possible return values from Daemon.daemonize() DAEMON_RUNNING = 'The daemon is running' DAEMON_NOT_RUNNING = 'The daemon is not running' DAEMON_COMPLETE = 'The daemon has completed its operations' DAEMON_STARTED = 'The daemon has been started' class Daemon(object): def __init__(self, logfile, pidfile): self.logfile = logfile self.pidfile = pidfile def foreground(self): "Run in the foreground." ### we should probably create a pidfile. other systems may try to detect ### the pidfile to see if this "daemon" is running. self.setup() self.run() ### remove the pidfile def daemonize_exit(self): try: result = self.daemonize() except (ChildFailed, DaemonFailed) as e: # duplicate the exit code sys.exit(e.code) except (ChildTerminatedAbnormally, ChildForkFailed, DaemonTerminatedAbnormally, DaemonForkFailed), e: sys.stderr.write('ERROR: %s\n' % e) sys.exit(1) except ChildResumedIncorrectly: sys.stderr.write('ERROR: continued after receiving unknown signal.\n') sys.exit(1) if result == DAEMON_STARTED or result == DAEMON_COMPLETE: sys.exit(0) elif result == DAEMON_NOT_RUNNING: sys.stderr.write('ERROR: the daemon exited with a success code ' 'without signalling its startup.\n') sys.exit(1) # in original process. daemon is up and running. we're done. def daemonize(self): ### review error situations. map to backwards compat. ?? ### be mindful of daemonize_exit(). ### we should try and raise ChildFailed / ChildTerminatedAbnormally. ### ref: older revisions. OR: remove exceptions. child_is_ready = multiprocessing.Event() child_completed = multiprocessing.Event() p = multiprocessing.Process(target=self._first_child, args=(child_is_ready, child_completed)) p.start() # Wait for the child to finish setting things up (in case we need # to communicate with it). It will only exit when ready. ### use a timeout here! (parameterized, of course) p.join() ### need to propagate errors, to adjust the return codes if child_completed.is_set(): ### what was the exit status? return DAEMON_COMPLETE if child_is_ready.is_set(): return DAEMON_RUNNING ### how did we get here?! the immediate child should not exit without ### signalling ready/complete. some kind of error. return DAEMON_STARTED def _first_child(self, child_is_ready, child_completed): # we're in the child. ### NOTE: the original design was a bit bunk. Exceptions raised from ### this point are within the child processes. We need to signal the ### errors to the parent in other ways. # decouple from the parent process os.chdir('/') os.umask(0) os.setsid() # remember this pid so the second child can signal it. thispid = os.getpid() # if the daemon process exits before signalling readiness, then we # need to see the problem. trap SIGCHLD with a SignalCatcher. daemon_exit = SignalCatcher(signal.SIGCHLD) # perform the second fork try: pid = os.fork() except OSError as e: ### this won't make it to the parent process raise DaemonForkFailed(e.errno, e.strerror) if pid > 0: # in the parent. # Wait for the child to be ready for operation. while True: # The readiness event will invariably be signalled early/first. # If it *doesn't* get signalled because the child has prematurely # exited, then we will pause 10ms before noticing the exit. The # pause is acceptable since that is aberrant/unexpected behavior. ### is there a way to break this wait() on a signal such as SIGCHLD? ### parameterize this wait, in case the app knows children may ### fail quickly? if child_is_ready.wait(timeout=0.010): # The child signalled readiness. Yay! break if daemon_exit.signalled: # Whoops. The child exited without signalling :-( break # Python 2.6 compat: .wait() may exit when set, but return None if child_is_ready.is_set(): break # A simple timeout. The child is taking a while to prepare. Go # back and wait for readiness. if daemon_exit.signalled: # Tell the parent that the child has exited. ### we need to communicate the exit status, if possible. child_completed.set() # reap the daemon process, getting its exit code. bubble it up. cpid, status = os.waitpid(pid, 0) assert pid == cpid if os.WIFEXITED(status): code = os.WEXITSTATUS(status) if code: ### this won't make it to the parent process raise DaemonFailed(code) ### this return value is ignored return DAEMON_NOT_RUNNING # the daemon did not exit cleanly. ### this won't make it to the parent process raise DaemonTerminatedAbnormally(status) # child_is_ready got asserted. the daemon is up and running, so # save the pid and return success. if self.pidfile: # Be wary of symlink attacks try: os.remove(self.pidfile) except OSError: pass fd = os.open(self.pidfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) os.write(fd, '%d\n' % pid) os.close(fd) ### this return value is ignored return DAEMON_STARTED ### old code. what to do with this? throw ChildResumedIncorrectly ### or just toss this and the exception. # some other signal popped us out of the pause. the daemon might not # be running. ### this won't make it to the parent process raise ChildResumedIncorrectly() # we're a daemon now. get rid of the final remnants of the parent: # restore the signal handlers and switch std* to the proper files. signal.signal(signal.SIGUSR1, signal.SIG_DFL) signal.signal(signal.SIGCHLD, signal.SIG_DFL) sys.stdout.flush() sys.stderr.flush() si = open('/dev/null', 'r') so = open(self.logfile, 'a+') se = open(self.logfile, 'a+', 0) # unbuffered os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # note: we could not inline the open() calls. after the fileno() completed, # the file would be closed, making the fileno invalid. gotta hold them # open until now: si.close() so.close() se.close() ### TEST: don't release the parent immediately. the whole parent stack ### should pause along with this sleep. #time.sleep(10) # everything is set up. call the initialization function. self.setup() ### TEST: exit before signalling. #sys.exit(0) #sys.exit(1) # the child is now ready for parent/anyone to communicate with it. child_is_ready.set() # start the daemon now. self.run() # The daemon is shutting down, so toss the pidfile. if self.pidfile: try: os.remove(self.pidfile) except OSError: pass ### this return value is ignored return DAEMON_COMPLETE def setup(self): raise NotImplementedError def run(self): raise NotImplementedError class _Detacher(Daemon): def __init__(self, target, logfile='/dev/null', pidfile=None, args=(), kwargs={}): Daemon.__init__(self, logfile, pidfile) self.target = target self.args = args self.kwargs = kwargs def setup(self): pass def run(self): self.target(*self.args, **self.kwargs) def run_detached(target, *args, **kwargs): """Simple function to run TARGET as a detached daemon. The additional arguments/keywords will be passed along. This function does not return -- sys.exit() will be called as appropriate. (capture SystemExit if logging/reporting is necessary) ### if needed, a variant of this func could be written to not exit """ d = _Detacher(target, args=args, kwargs=kwargs) d.daemonize_exit() class SignalCatcher(object): def __init__(self, signum): self.signalled = False signal.signal(signum, self.sig_handler) def sig_handler(self, signum, frame): self.signalled = True class ChildTerminatedAbnormally(Exception): "The child process terminated abnormally." def __init__(self, status): Exception.__init__(self, status) self.status = status def __str__(self): return 'child terminated abnormally (0x%04x)' % self.status class ChildFailed(Exception): "The child process exited with a failure code." def __init__(self, code): Exception.__init__(self, code) self.code = code def __str__(self): return 'child failed with exit code %d' % self.code class ChildForkFailed(Exception): "The child process could not be forked." def __init__(self, errno, strerror): Exception.__init__(self, errno, strerror) self.errno = errno self.strerror = strerror def __str__(self): return 'child fork failed with error %d (%s)' % self.args class ChildResumedIncorrectly(Exception): "The child resumed its operation incorrectly." class DaemonTerminatedAbnormally(Exception): "The daemon process terminated abnormally." def __init__(self, status): Exception.__init__(self, status) self.status = status def __str__(self): return 'daemon terminated abnormally (0x%04x)' % self.status class DaemonFailed(Exception): "The daemon process exited with a failure code." def __init__(self, code): Exception.__init__(self, code) self.code = code def __str__(self): return 'daemon failed with exit code %d' % self.code class DaemonForkFailed(Exception): "The daemon process could not be forked." def __init__(self, errno, strerror): Exception.__init__(self, errno, strerror) self.errno = errno self.strerror = strerror def __str__(self): return 'daemon fork failed with error %d (%s)' % self.args
{ "pile_set_name": "Github" }
<nav class="navbar navbar-default"> <div class="container-fluid center-block result-header"> <div class="navbar-header"> <a class="navbar-brand" href="/"> <img alt="Owllook" width="120px" height="40px" src="static/novels/img/logo_search.png"> </a> </div> <form action="/search" method="get"> <div class="col-sm-6 col-xs-9 search"> <input type="text" name="wd" class="form-control" placeholder="请输入小说名" value="{{name}}"> </div> </form> {% if is_login %} <div class="header"> {% include "login.html" %} </div> {% else %} <div class="login"> <a class="btn btn-primary pull-right" href="#" role="button" data-toggle="modal" data-target="#login">登录</a> </div> {% endif %} </div> </nav>
{ "pile_set_name": "Github" }
import torch from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler from .. import builder from ..registry import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module class GridRCNN(TwoStageDetector): """Grid R-CNN. This detector is the implementation of: - Grid R-CNN (https://arxiv.org/abs/1811.12030) - Grid R-CNN Plus: Faster and Better (https://arxiv.org/abs/1906.05688) """ def __init__(self, backbone, rpn_head, bbox_roi_extractor, bbox_head, grid_roi_extractor, grid_head, train_cfg, test_cfg, neck=None, shared_head=None, pretrained=None): assert grid_head is not None super(GridRCNN, self).__init__( backbone=backbone, neck=neck, shared_head=shared_head, rpn_head=rpn_head, bbox_roi_extractor=bbox_roi_extractor, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) if grid_roi_extractor is not None: self.grid_roi_extractor = builder.build_roi_extractor( grid_roi_extractor) self.share_roi_extractor = False else: self.share_roi_extractor = True self.grid_roi_extractor = self.bbox_roi_extractor self.grid_head = builder.build_head(grid_head) self.init_extra_weights() def init_extra_weights(self): self.grid_head.init_weights() if not self.share_roi_extractor: self.grid_roi_extractor.init_weights() def _random_jitter(self, sampling_results, img_metas, amplitude=0.15): """Ramdom jitter positive proposals for training.""" for sampling_result, img_meta in zip(sampling_results, img_metas): bboxes = sampling_result.pos_bboxes random_offsets = bboxes.new_empty(bboxes.shape[0], 4).uniform_( -amplitude, amplitude) # before jittering cxcy = (bboxes[:, 2:4] + bboxes[:, :2]) / 2 wh = (bboxes[:, 2:4] - bboxes[:, :2]).abs() # after jittering new_cxcy = cxcy + wh * random_offsets[:, :2] new_wh = wh * (1 + random_offsets[:, 2:]) # xywh to xyxy new_x1y1 = (new_cxcy - new_wh / 2) new_x2y2 = (new_cxcy + new_wh / 2) new_bboxes = torch.cat([new_x1y1, new_x2y2], dim=1) # clip bboxes max_shape = img_meta['img_shape'] if max_shape is not None: new_bboxes[:, 0::2].clamp_(min=0, max=max_shape[1] - 1) new_bboxes[:, 1::2].clamp_(min=0, max=max_shape[0] - 1) sampling_result.pos_bboxes = new_bboxes return sampling_results def forward_dummy(self, img): outs = () # backbone x = self.extract_feat(img) # rpn if self.with_rpn: rpn_outs = self.rpn_head(x) outs = outs + (rpn_outs, ) proposals = torch.randn(1000, 4).cuda() # bbox head rois = bbox2roi([proposals]) bbox_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois) if self.with_shared_head: bbox_feats = self.shared_head(bbox_feats) cls_score, bbox_pred = self.bbox_head(bbox_feats) # grid head grid_rois = rois[:100] grid_feats = self.grid_roi_extractor( x[:self.grid_roi_extractor.num_inputs], grid_rois) if self.with_shared_head: grid_feats = self.shared_head(grid_feats) grid_pred = self.grid_head(grid_feats) return rpn_outs, cls_score, bbox_pred, grid_pred def forward_train(self, img, img_meta, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None): x = self.extract_feat(img) losses = dict() # RPN forward and loss if self.with_rpn: rpn_outs = self.rpn_head(x) rpn_loss_inputs = rpn_outs + (gt_bboxes, img_meta, self.train_cfg.rpn) rpn_losses = self.rpn_head.loss( *rpn_loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore) losses.update(rpn_losses) proposal_cfg = self.train_cfg.get('rpn_proposal', self.test_cfg.rpn) proposal_inputs = rpn_outs + (img_meta, proposal_cfg) proposal_list = self.rpn_head.get_bboxes(*proposal_inputs) else: proposal_list = proposals if self.with_bbox: # assign gts and sample proposals bbox_assigner = build_assigner(self.train_cfg.rcnn.assigner) bbox_sampler = build_sampler( self.train_cfg.rcnn.sampler, context=self) num_imgs = img.size(0) if gt_bboxes_ignore is None: gt_bboxes_ignore = [None for _ in range(num_imgs)] sampling_results = [] for i in range(num_imgs): assign_result = bbox_assigner.assign(proposal_list[i], gt_bboxes[i], gt_bboxes_ignore[i], gt_labels[i]) sampling_result = bbox_sampler.sample( assign_result, proposal_list[i], gt_bboxes[i], gt_labels[i], feats=[lvl_feat[i][None] for lvl_feat in x]) sampling_results.append(sampling_result) # bbox head forward and loss rois = bbox2roi([res.bboxes for res in sampling_results]) # TODO: a more flexible way to decide which feature maps to use bbox_feats = self.bbox_roi_extractor( x[:self.bbox_roi_extractor.num_inputs], rois) if self.with_shared_head: bbox_feats = self.shared_head(bbox_feats) cls_score, bbox_pred = self.bbox_head(bbox_feats) bbox_targets = self.bbox_head.get_target(sampling_results, gt_bboxes, gt_labels, self.train_cfg.rcnn) loss_bbox = self.bbox_head.loss(cls_score, bbox_pred, *bbox_targets) losses.update(loss_bbox) # Grid head forward and loss sampling_results = self._random_jitter(sampling_results, img_meta) pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results]) grid_feats = self.grid_roi_extractor( x[:self.grid_roi_extractor.num_inputs], pos_rois) if self.with_shared_head: grid_feats = self.shared_head(grid_feats) # Accelerate training max_sample_num_grid = self.train_cfg.rcnn.get('max_num_grid', 192) sample_idx = torch.randperm( grid_feats.shape[0])[:min(grid_feats. shape[0], max_sample_num_grid)] grid_feats = grid_feats[sample_idx] grid_pred = self.grid_head(grid_feats) grid_targets = self.grid_head.get_target(sampling_results, self.train_cfg.rcnn) grid_targets = grid_targets[sample_idx] loss_grid = self.grid_head.loss(grid_pred, grid_targets) losses.update(loss_grid) return losses def simple_test(self, img, img_meta, proposals=None, rescale=False): """Test without augmentation.""" assert self.with_bbox, "Bbox head must be implemented." x = self.extract_feat(img) proposal_list = self.simple_test_rpn( x, img_meta, self.test_cfg.rpn) if proposals is None else proposals det_bboxes, det_labels = self.simple_test_bboxes( x, img_meta, proposal_list, self.test_cfg.rcnn, rescale=False) # pack rois into bboxes grid_rois = bbox2roi([det_bboxes[:, :4]]) grid_feats = self.grid_roi_extractor( x[:len(self.grid_roi_extractor.featmap_strides)], grid_rois) if grid_rois.shape[0] != 0: self.grid_head.test_mode = True grid_pred = self.grid_head(grid_feats) det_bboxes = self.grid_head.get_bboxes(det_bboxes, grid_pred['fused'], img_meta) if rescale: det_bboxes[:, :4] /= img_meta[0]['scale_factor'] else: det_bboxes = torch.Tensor([]) bbox_results = bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes) return bbox_results
{ "pile_set_name": "Github" }
<root> <styles> <include src="s2r://panorama/styles/dotastyles.vcss_c" /> <include src="s2r://panorama/styles/dashboard.vcss_c" /> <include src="s2r://panorama/styles/tournament_group.vcss_c" /> </styles> <TournamentGroup> <Panel id="GroupTitleSection"> <Label class="GroupTitle" text="#DOTA_TournamentBracket_GroupNumber"/> </Panel> <Panel id="GroupContainer"> <Panel id="GroupHeader"> <Panel id="GroupCellRank" class="GroupHeaderCell"> <Label text="#DOTA_TournamentGroup_Rank"/> </Panel> <Panel id="GroupCellTeam" class="GroupHeaderCell"> <Label text="#DOTA_TournamentGroup_Team"/> </Panel> <Panel id="GroupCellGamesPlayed" class="GroupHeaderCell"> <Label text="#DOTA_TournamentGroup_GamesPlayed"/> </Panel> <Panel id="GroupCellRecord" class="GroupHeaderCell"> <Label text="#DOTA_TournamentGroup_Record"/> </Panel> <Panel id="GroupCellScore" class="GroupHeaderCell"> <Label text="#DOTA_TournamentGroup_Score"/> </Panel> </Panel> <Panel id="GroupRows" class="GroupRows"> <!-- Dynamic --> </Panel> </Panel> </TournamentGroup> </root>
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: ed64773f587bb9846918065b72c58283
{ "pile_set_name": "Github" }
Open Diameter License Open Diameter: Open-source software for the Diameter and Diameter related protocols Copyright (C) 2002-2007 Open Diameter Project This software consists of two parts, namely LGPL Part and GPL Part, which use different licences as described below. ========= LGPL Part ========= Each of the following libraries: - libdiamparser (Diameter parser library) - libdiameter (Diameter library) - libdiametereap (Diameter EAP application library) - libdiameternasreq (Diameter NASREQ application library) - libeap (EAP library) - libeaparchie (EAP-Archie method library) - libpana (PANA library) is licensed under the following terms and conditions. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. In addition, when you copy and redistribute some or the entire part of the source code of this software with or without modification, you MUST include this copyright notice in each copy. If you make any changes that are appeared to be useful, please send sources that include the changed part to diameter-developers@lists.sourceforge.net so that we can reflect your changes to one unified version of this software. ======== GPL Part ======== Each of the following programs (libraries are also programs): - libeaptls (EAP-TLS method library) - libNASREQ (Diameter - freeradius translator) - panad (PANA daemon) - nasd (NAS daemon, including hostapdPatch) - aaad (AAA server daemon) is licensed under the following terms and conditions. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US. If you make any changes that are appeared to be useful, please send sources that include the changed part to diameter-developers@lists.sourceforge.net so that we can reflect your changes to one unified version of this software.
{ "pile_set_name": "Github" }
#include <gtest/gtest.h> int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>PreferenceSpecifiers</key> <array> <dict> <key>FooterText</key> <string>This application makes use of the following third party libraries:</string> <key>Title</key> <string>Acknowledgements</string> <key>Type</key> <string>PSGroupSpecifier</string> </dict> <dict> <key>FooterText</key> <string>Copyright (c) 2013-2015 MJExtension (https://github.com/CoderMJLee/MJExtension) 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. </string> <key>License</key> <string>MIT</string> <key>Title</key> <string>MJExtension</string> <key>Type</key> <string>PSGroupSpecifier</string> </dict> <dict> <key>FooterText</key> <string>The MIT License (MIT) Copyright (c) 2015 ibireme &lt;ibireme@gmail.com&gt; 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. </string> <key>License</key> <string>MIT</string> <key>Title</key> <string>YYModel</string> <key>Type</key> <string>PSGroupSpecifier</string> </dict> <dict> <key>FooterText</key> <string>Generated by CocoaPods - https://cocoapods.org</string> <key>Title</key> <string></string> <key>Type</key> <string>PSGroupSpecifier</string> </dict> </array> <key>StringsTable</key> <string>Acknowledgements</string> <key>Title</key> <string>Acknowledgements</string> </dict> </plist>
{ "pile_set_name": "Github" }
Solution ==K ( V:Term |-> cons ( a , cons ( b , nil , .Vals ) , .Vals ) )
{ "pile_set_name": "Github" }
{% extends '_ical_export.html' %} {% block download_text %} {% trans %}Download current category:{% endtrans %} {% endblock %} {% block javascript %} {{ super() }} <script> exportPopups["{{ item.id }}"] = new ExportIcalInterface( {{ api_mode|tojson }}, {{ persistent_user_enabled|tojson }}, {{ persistent_allowed|tojson }}, {{ api_active|tojson }}, {{ user_logged|tojson }}, setURLs, {{ url_for('api.build_urls')|tojson }}, {categId: "{{ item.id }}"}, {{ request_urls|tojson }}, "{{ item.id }}", "{{ session.user.id if session.user else '' }}" ); </script> {% endblock %}
{ "pile_set_name": "Github" }
<?php namespace Botonomous\utility; use Botonomous\BotonomousException; use Monolog\Handler\StreamHandler; use Monolog\Logger; use Psr\Log\LoggerInterface; /** * Class LoggerUtility. */ class LoggerUtility extends AbstractUtility { const DATE_FORMAT = 'Y-m-d H:i:s'; const TEMP_FOLDER = 'tmp'; const DEBUG = 'debug'; const INFO = 'info'; const NOTICE = 'notice'; const WARNING = 'warning'; const ERROR = 'error'; const CRITICAL = 'critical'; const ALERT = 'alert'; const EMERGENCY = 'emergency'; const HANDLERS_KEY = 'handlers'; public static $levels = [ self::DEBUG, self::INFO, self::NOTICE, self::WARNING, self::ERROR, self::CRITICAL, self::ALERT, self::EMERGENCY, ]; private $logger; /** * LoggerUtility constructor. * * @param null $config * * @throws \Exception */ public function __construct($config = null) { parent::__construct($config); try { $this->initLogger(); } catch (\Exception $e) { throw $e; } } /** * Init the logger. * * @throws \Exception */ private function initLogger() { $monologConfig = $this->getMonologConfig(); if (empty($monologConfig)) { throw new BotonomousException('Monolog config is missing'); } $logger = new Logger($monologConfig['channel']); foreach (array_keys($monologConfig[self::HANDLERS_KEY]) as $value) { $logger = $this->pushMonologHandler($logger, $value); } $this->setLogger($logger); } /** * @throws \Exception * * @return mixed */ private function getMonologConfig() { $loggerConfig = $this->getConfig()->get('logger'); return !empty($loggerConfig['monolog']) ? $loggerConfig['monolog'] : false; } /** * @param Logger $logger * @param string $handlerKey * * @throws \Exception * * @return Logger */ private function pushMonologHandler(Logger $logger, string $handlerKey): Logger { $activeHandlers = []; // if there are more $handlerKey, use switch if ($handlerKey === 'file') { $activeHandlers[] = new StreamHandler($this->getLogFilePath()); } if (!empty($activeHandlers)) { foreach ($activeHandlers as $activeHandler) { $logger->pushHandler($activeHandler); } } return $logger; } /** * @throws \Exception * * @return false|string */ public function getLogFilePath() { $monologConfigFile = $this->getMonologConfigFileName(); if (empty($monologConfigFile)) { return false; } return $this->getTempDir().DIRECTORY_SEPARATOR.$monologConfigFile; } /** * @throws \Exception * * @return mixed */ private function getMonologConfigFileName() { $monologConfig = $this->getMonologConfig(); if (isset($monologConfig[self::HANDLERS_KEY]['file']['fileName'])) { return $monologConfig[self::HANDLERS_KEY]['file']['fileName']; } } /** * @return LoggerInterface */ private function getLogger(): LoggerInterface { return $this->logger; } /** * @param LoggerInterface $logger */ private function setLogger(LoggerInterface $logger) { $this->logger = $logger; } /** * @param string $function * @param string $message * @param string $channel * * @throws \Exception * * @return bool */ public function logChat(string $function, string $message = '', string $channel = ''): bool { try { return $this->logInfo('Log Chat', [ 'function' => $function, 'message' => $message, 'channel' => $channel, ]); } catch (\Exception $e) { throw new BotonomousException($e->getMessage()); } } /** * @throws \Exception * * @return bool */ private function canLog(): bool { $loggerConfig = $this->getConfig()->get('logger'); return empty($loggerConfig['enabled']) ? false : true; } /** * @throws \Exception * * @return string */ public function getTempDir(): string { return dirname(__DIR__).DIRECTORY_SEPARATOR.self::TEMP_FOLDER; } /** * @param $function * @param string $message * @param $channel * * @return string */ public function getLogContent(string $function, string $message, string $channel): string { return "{$function}|{$message}|{$channel}"; } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logDebug(string $message, array $context = []): bool { return $this->log(self::DEBUG, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logInfo(string $message, array $context = []): bool { return $this->log(self::INFO, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logNotice(string $message, array $context = []): bool { return $this->log(self::NOTICE, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logWarning(string $message, array $context = []): bool { return $this->log(self::WARNING, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logError(string $message, array $context = []): bool { return $this->log(self::ERROR, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logCritical(string $message, array $context = []): bool { return $this->log(self::CRITICAL, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logAlert(string $message, array $context = []): bool { return $this->log(self::ALERT, $message, $context); } /** * @param string $message * @param array $context * * @throws \Exception * * @return bool */ public function logEmergency(string $message, array $context = []): bool { return $this->log(self::EMERGENCY, $message, $context); } /** * @param string $level * @param $message * @param array $context * * @throws \Exception * * @return bool */ public function log(string $level, string $message, array $context = []): bool { if ($this->canLog() !== true) { return false; } $logger = $this->getLogger(); if (!in_array($level, self::$levels)) { throw new BotonomousException("'{$level}' is an invalid log level"); } $logger->$level($message, $context); return true; } }
{ "pile_set_name": "Github" }
// Author: Lee Christensen // License: BSD 3-Clause using System; using System.Diagnostics; using System.IO; using System.Reflection; namespace RandomCSharp { public class Program { public static MethodInfo GetMethod(MethodInfo[] methods, string Name) { foreach (var method in methods) { if (method.Name == Name) { return method; } } return null; } public static void Main(string[] args) { Console.WriteLine("PID: " + Process.GetCurrentProcess().Id); string command = @"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Pop pop!');"; var AutomationDllByets = File.ReadAllBytes(@"C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll"); var AutomationAssembly = Assembly.Load(AutomationDllByets); Type PowerShellClassType = AutomationAssembly.GetType("System.Management.Automation.PowerShell"); var PublicStaticMethods = PowerShellClassType.GetMethods((BindingFlags.Public | BindingFlags.Static)); var PublicMethods = PowerShellClassType.GetMethods((BindingFlags.Public | BindingFlags.Instance)); var CreateMethod = GetMethod(PublicStaticMethods, "Create"); var AddScriptMethod = GetMethod(PublicMethods, "AddScript"); var InvokeMethod = GetMethod(PublicMethods, "Invoke"); var PowerShellInstance = CreateMethod.Invoke(PowerShellClassType, new object[] { }); AddScriptMethod.Invoke(PowerShellInstance, new object[] { command }); InvokeMethod.Invoke(PowerShellInstance, new object[] { }); } } }
{ "pile_set_name": "Github" }
============================================================================= This Notice.txt file contains certain notices of software components included with the software that Qualcomm Atheros, Inc. (Qualcomm Atheros) is required to provide you. Except where prohibited by the open source license, the content of this notices file is only provided to satisfy Qualcomm Atheros's attribution and notice requirement; your use of these software components together with the Qualcomm Atheros software (Qualcomm Atheros software hereinafter referred to as Software) is subject to the terms of your agreement from Qualcomm Atheros. Compliance with all copyright laws and software license agreements included in the notice section of this file are the responsibility of the user. Except as may be granted by separate express written agreement, this file provides no license to any patents, trademarks, copyrights, or other intellectual property of Qualcomm Incorporated or any of its subsidiaries. Copyright (c) 2016 Qualcomm Atheros, Inc. All rights reserved. Qualcomm is a trademark of Qualcomm Incorporated, registered in the United States and other countries. All Qualcomm Incorporated trademarks are used with permission. Atheros is a trademark of Qualcomm Atheros, Inc., registered in the United States and other countries. Other products and brand names may be trademarks or registered trademarks of their respective owners. ============================================================================= ======================================================================================================================================== // // Copyright (c) 1991, 1993 // The Regents of the University of California. All rights reserved. // $ATH_LICENSE_NULL$ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by the University of // California, Berkeley and its contributors. // 4. Neither the name of the University nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. ======================================================================================================================================== /* ========================================================================== * * Synopsys SS USB3 Linux Software Driver and documentation (hereinafter, * "Software") is an Unsupported proprietary work of Synopsys, Inc. unless * otherwise expressly agreed to in writing between Synopsys and you. * * The Software IS NOT an item of Licensed Software or Licensed Product under * any End User Software License Agreement or Agreement for Licensed Product * with Synopsys or any supplement thereto. You are permitted to use and * redistribute this Software in source and binary forms, with or without * modification, provided that redistributions of source code must retain this * notice. You may not view, use, disclose, copy or distribute this file or * any information contained herein except pursuant to this license grant from * Synopsys. If you do not agree with this notice, including the disclaimer * below, then you are not authorized to use the Software. * * THIS SOFTWARE IS BEING DISTRIBUTED BY SYNOPSYS SOLELY ON AN "AS IS" BASIS * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE HEREBY DISCLAIMED. IN NO EVENT SHALL SYNOPSYS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * ========================================================================== */ ======================================================================================================================================== ======================================================================================================================================== /* * FILE: sha2.h * AUTHOR: Aaron D. Gifford - http://www.aarongifford.com/ * * Copyright (c) 2000-2001, Aaron D. Gifford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ ======================================================================================================================================== ======================================================================================================================================== /* * Copyright (c)2014 Qualcomm Atheros, Inc. * All Rights Reserved. * Qualcomm Atheros Confidential and Proprietary. * $ATH_LICENSE_TARGET_C$ */ /*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Copyright (c) 2011 The FreeBSD Foundation * All rights reserved. * Portions of this software were developed by David Chisnall * under sponsorship from the FreeBSD Foundation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ ======================================================================================================================================== ======================================================================================================================================== /* * Copyright (c) 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Modified by Synopsys, Inc, 12/12/2007 */ ======================================================================================================================================== ======================================================================================================================================== /* * AES-based functions * * * - AES Key Wrap Algorithm (128-bit KEK) (RFC3394) * - One-Key CBC MAC (OMAC1) hash with AES-128 * - AES-128 CTR mode encryption * - AES-128 EAX mode encryption/decryption * - AES-128 CBC * * Copyright (c) 2003-2005, Jouni Malinen <jkmaline@cc.hut.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ Qualcomm Atheros, Inc. has chosen to take AES-based functions subject to the BSD license and terms ======================================================================================================================================== ======================================================================================================================================== /* * Common helper macros, etc. * Copyright (c) 2002-2005, Jouni Malinen <jkmaline@cc.hut.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * */ Qualcomm Atheros, Inc. has chosen to take common helper macros functions subject to the BSD license and terms ======================================================================================================================================== ======================================================================================================================================== /* * SHA1 hash implementation and interface functions * Copyright (c) 2003-2005, Jouni Malinen <jkmaline@cc.hut.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ Qualcomm Atheros, Inc. has chosen to take SHA1 hash implementation and interface functions subject to the BSD license and terms ======================================================================================================================================== ======================================================================================================================================== /* * MD5 hash implementation and interface functions * Copyright (c) 2003-2005, Jouni Malinen <jkmaline@cc.hut.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ Qualcomm Atheros, Inc. has chosen to take MD5 hash implementation and interface functions subject to the BSD license and terms ======================================================================================================================================== Copyright (c) 1998-2008 Tensilica Inc. * 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. ======================================================================================================================================== /* * Copyright (c) 2012 Qualcomm Atheros, Inc. * All Rights Reserved. * Qualcomm Atheros Confidential and Proprietary. */ //- // Copyright (c) 2002-2004 Sam Leffler, Errno Consulting // All rights reserved. // $ATH_LICENSE_NULL$ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer, // without modification. // 2. Redistributions in binary form must reproduce at minimum a disclaimer // similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any // redistribution must be conditioned upon including a substantially // similar Disclaimer requirement for further binary redistribution. // 3. Neither the names of the above-listed copyright holders nor the names // of any contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // Alternatively, this software may be distributed under the terms of the // GNU General Public License ("GPL") version 2 as published by the Free // Software Foundation. // // NO WARRANTY // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER // IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGES. // ======================================================================================================================================== /* * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ For all files with the above-mentioned dual-license, QCA chooses to receive subject to the BSD license. ======================================================================================================================================== // Copyright (c) 2003-2006 Marcus Geelnard // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // Marcus Geelnard // marcus.geelnard at home.se // ======================================================================================================================================== /* * Copyright (c) 2011 Qualcomm Atheros, Inc. * All Rights Reserved. * Qualcomm Atheros Confidential and Proprietary. * $ATH_LICENSE_NULL$ */ // Copyright (c) 2003-2006 Marcus Geelnard // Copyright (c) 2006-2007 Atheros Communications Inc. // $ATH_LICENSE_NULL$ // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // Marcus Geelnard // marcus.geelnard at home.se // ======================================================================================================================================== // // Copyright (c) 1991, 1993 // The Regents of the University of California. All rights reserved. // $ATH_LICENSE_NULL$ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by the University of // California, Berkeley and its contributors. // 4. Neither the name of the University nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // ======================================================================================================================================== /* ========================================================================== * * Synopsys SS USB3 Linux Software Driver and documentation (hereinafter, * "Software") is an Unsupported proprietary work of Synopsys, Inc. unless * otherwise expressly agreed to in writing between Synopsys and you. * * The Software IS NOT an item of Licensed Software or Licensed Product under * any End User Software License Agreement or Agreement for Licensed Product * with Synopsys or any supplement thereto. You are permitted to use and * redistribute this Software in source and binary forms, with or without * modification, provided that redistributions of source code must retain this * notice. You may not view, use, disclose, copy or distribute this file or * any information contained herein except pursuant to this license grant from * Synopsys. If you do not agree with this notice, including the disclaimer * below, then you are not authorized to use the Software. * * THIS SOFTWARE IS BEING DISTRIBUTED BY SYNOPSYS SOLELY ON AN "AS IS" BASIS * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE HEREBY DISCLAIMED. IN NO EVENT SHALL SYNOPSYS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * ========================================================================== */ ======================================================================================================================================== /* * $DateTime: 2013/07/24 11:35:54 $ */ /* $OpenBSD: string.h,v 1.17 2006/01/06 18:53:04 millert Exp $ */ /* $NetBSD: string.h,v 1.6 1994/10/26 00:56:30 cgd Exp $ */ /*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ ======================================================================================================================================== /* * $DateTime: 2011/01/07 17:50:19 $ */ /* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ /* * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ ======================================================================================================================================
{ "pile_set_name": "Github" }
[ { "type": "npc", "id": "evac_guard3", "//": "Appears in the refugee center as a guard with custom dialogue.", "name_suffix": "Guard", "class": "NC_BOUNTY_HUNTER", "attitude": 0, "mission": 8, "chat": "TALK_EVAC_GUARD3", "faction": "free_merchants" }, { "id": "TALK_EVAC_GUARD3", "type": "talk_topic", "dynamic_line": "Keep to yourself and you won't find any problems.", "responses": [ { "text": "What do you do around here?", "topic": "TALK_EVAC_GUARD3_NEW" }, { "text": "Got tips for avoiding trouble?", "topic": "TALK_EVAC_GUARD3_RULES" }, { "text": "Have you seen anyone who might be hiding something?", "topic": "TALK_EVAC_GUARD3_HIDE1" }, { "text": "Bye…", "topic": "TALK_DONE" } ] }, { "id": "TALK_EVAC_GUARD3_NEW", "type": "talk_topic", "dynamic_line": "I haven't been here for long but I do my best to watch who comes and goes. You can't always predict who will bring trouble.", "responses": [ { "text": "…", "topic": "TALK_EVAC_GUARD3" } ] }, { "id": "TALK_EVAC_GUARD3_RULES", "type": "talk_topic", "dynamic_line": "Keep your head down and stay out of my way.", "responses": [ { "text": "OK…", "topic": "TALK_EVAC_GUARD3" } ] }, { "id": "TALK_EVAC_GUARD3_HIDE1", "type": "talk_topic", "dynamic_line": "Like what?", "responses": [ { "text": "I'm not sure…", "topic": "TALK_EVAC_GUARD3_WASTE" }, { "text": "Like they could be working for someone else?", "topic": "TALK_EVAC_GUARD3_HIDE2" } ] }, { "id": "TALK_EVAC_GUARD3_HIDE2", "type": "talk_topic", "dynamic_line": "You're new here, who the hell put you up to this crap?", "responses": [ { "text": "Get bent, traitor!", "trial": { "type": "INTIMIDATE", "difficulty": 20, "mod": [ [ "FEAR", 3 ] ] }, "success": { "topic": "TALK_EVAC_GUARD3_HOSTILE", "effect": [ { "u_faction_rep": -15 }, { "npc_change_faction": "hells_raiders" } ] }, "failure": { "topic": "TALK_EVAC_GUARD3_INSULT", "effect": { "u_faction_rep": -5 } } }, { "text": "Got something to hide?", "trial": { "type": "PERSUADE", "difficulty": 10, "mod": [ [ "TRUST", 3 ] ] }, "success": { "topic": "TALK_EVAC_GUARD3_DEAD", "effect": { "npc_change_faction": "hells_raiders" } }, "failure": { "topic": "TALK_EVAC_GUARD3_INSULT", "effect": { "u_faction_rep": -5 } } }, { "text": "Sorry, I didn't mean to offend you…", "topic": "TALK_EVAC_GUARD3_WASTE" } ] }, { "id": "TALK_EVAC_GUARD3_WASTE", "type": "talk_topic", "dynamic_line": "If you don't get on with your business I'm going to have to ask you to leave and not come back.", "responses": [ { "text": "Sorry.", "topic": "TALK_EVAC_GUARD3" } ] }, { "id": "TALK_EVAC_GUARD3_DEAD", "type": "talk_topic", "dynamic_line": "That's it, you're dead!", "responses": [ { "text": "I didn't mean it!", "topic": "TALK_DONE" }, { "text": "…", "topic": "TALK_DONE" } ] }, { "id": "TALK_EVAC_GUARD3_HOSTILE", "type": "talk_topic", "dynamic_line": "You must really have a death wish!", "responses": [ { "text": "I didn't mean it!", "topic": "TALK_DONE" }, { "text": "…", "topic": "TALK_DONE" } ] }, { "id": "TALK_EVAC_GUARD3_INSULT", "type": "talk_topic", "dynamic_line": "We don't put-up with garbage like you, finish your business and get the hell out.", "responses": [ { "text": "…", "topic": "TALK_DONE" } ] } ]
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <link href="/static/css/v0.3/jschart.css" rel="stylesheet" type="text/css" media="all"> </head> <body> <script src="/static/js/v0.3/d3.min.js"></script> <script src="/static/js/v0.3/d3-queue.min.js"></script> <script src="/static/js/v0.3/saveSvgAsPng.js"></script> <script src="/static/js/v0.3/jschart.js"></script> <center><h2>haproxy-ocp - router-3-r4103-req_rate_max</h2></center> <div id="chart_1"> <script> create_jschart("lineChart", "timeseries", "chart_1", "req_rate_max: max number of HTTP requests per second observed", null, null, { csvfiles: [ "csv/router-3-r4103-req_rate_max_req_rate_max: max number of HTTP requests per second observed.csv" ], threshold: 0 }); </script> </div> </body> </html>
{ "pile_set_name": "Github" }
<div class="control-group"> <label class="control-label" for="startDate">开始时间:</label> <div class="controls"> <input type="text" id="startDate" name="startDate" value="${startDate}" class="datepicker" data-date-format="yyyy-mm-dd" required /> </div> </div> <div class="control-group"> <label class="control-label" for="endDate">结束时间:</label> <div class="controls"> <input type="text" id="endDate" name="endDate" value="${endDate}" class="datepicker" data-date-format="yyyy-mm-dd" required /> </div> </div> <div class="control-group"> <label class="control-label" for="reason">请假原因:</label> <div class="controls"> <textarea id="reason" name="reason" required>${reason}</textarea> </div> </div> <div class="control-group"> <label class="control-label" for="reason">是否继续申请:</label> <div class="controls"> <select id="reApply" name="reApply"> <option value='true'>重新申请</option> <option value='false'>结束流程</option> </select> </div> </div>
{ "pile_set_name": "Github" }
/* Copyright 2017 The Kubernetes Authors. 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. */ package audit import ( "fmt" "strconv" "strings" "time" auditinternal "k8s.io/apiserver/pkg/apis/audit" ) // EventString creates a 1-line text representation of an audit event, using a subset of the // information in the event struct. func EventString(ev *auditinternal.Event) string { username := "<none>" groups := "<none>" if len(ev.User.Username) > 0 { username = ev.User.Username if len(ev.User.Groups) > 0 { groups = auditStringSlice(ev.User.Groups) } } asuser := "<self>" asgroups := "<lookup>" if ev.ImpersonatedUser != nil { asuser = ev.ImpersonatedUser.Username if ev.ImpersonatedUser.Groups != nil { asgroups = auditStringSlice(ev.ImpersonatedUser.Groups) } } namespace := "<none>" if ev.ObjectRef != nil && len(ev.ObjectRef.Namespace) != 0 { namespace = ev.ObjectRef.Namespace } response := "<deferred>" if ev.ResponseStatus != nil { response = strconv.Itoa(int(ev.ResponseStatus.Code)) } ip := "<unknown>" if len(ev.SourceIPs) > 0 { ip = ev.SourceIPs[0] } return fmt.Sprintf("%s AUDIT: id=%q stage=%q ip=%q method=%q user=%q groups=%q as=%q asgroups=%q namespace=%q uri=%q response=\"%s\"", ev.RequestReceivedTimestamp.Format(time.RFC3339Nano), ev.AuditID, ev.Stage, ip, ev.Verb, username, groups, asuser, asgroups, namespace, ev.RequestURI, response) } func auditStringSlice(inList []string) string { quotedElements := make([]string, len(inList)) for i, in := range inList { quotedElements[i] = fmt.Sprintf("%q", in) } return strings.Join(quotedElements, ",") }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2014 Freek van Tienen <freek.v.tienen@gmail.com> * * This file is part of paparazzi. * * paparazzi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * paparazzi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with paparazzi; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * @file subsystems/imu/imu_navstik.h * Interface for the Navstik magnetometer, accelerometer and gyroscope */ #ifndef IMU_NAVSTIK_H #define IMU_NAVSTIK_H #include "generated/airframe.h" #include "subsystems/imu.h" #include "peripherals/hmc58xx.h" #include "peripherals/mpu60x0_i2c.h" #ifndef NAVSTIK_GYRO_RANGE #define NAVSTIK_GYRO_RANGE MPU60X0_GYRO_RANGE_1000 #endif #ifndef NAVSTIK_ACCEL_RANGE #define NAVSTIK_ACCEL_RANGE MPU60X0_ACCEL_RANGE_8G #endif // Set default sensitivity based on range if needed #if !defined IMU_GYRO_P_SENS & !defined IMU_GYRO_Q_SENS & !defined IMU_GYRO_R_SENS #define IMU_GYRO_P_SENS MPU60X0_GYRO_SENS[NAVSTIK_GYRO_RANGE] #define IMU_GYRO_P_SENS_NUM MPU60X0_GYRO_SENS_FRAC[NAVSTIK_GYRO_RANGE][0] #define IMU_GYRO_P_SENS_DEN MPU60X0_GYRO_SENS_FRAC[NAVSTIK_GYRO_RANGE][1] #define IMU_GYRO_Q_SENS MPU60X0_GYRO_SENS[NAVSTIK_GYRO_RANGE] #define IMU_GYRO_Q_SENS_NUM MPU60X0_GYRO_SENS_FRAC[NAVSTIK_GYRO_RANGE][0] #define IMU_GYRO_Q_SENS_DEN MPU60X0_GYRO_SENS_FRAC[NAVSTIK_GYRO_RANGE][1] #define IMU_GYRO_R_SENS MPU60X0_GYRO_SENS[NAVSTIK_GYRO_RANGE] #define IMU_GYRO_R_SENS_NUM MPU60X0_GYRO_SENS_FRAC[NAVSTIK_GYRO_RANGE][0] #define IMU_GYRO_R_SENS_DEN MPU60X0_GYRO_SENS_FRAC[NAVSTIK_GYRO_RANGE][1] #endif // Set default sensitivity based on range if needed #if !defined IMU_ACCEL_X_SENS & !defined IMU_ACCEL_Y_SENS & !defined IMU_ACCEL_Z_SENS #define IMU_ACCEL_X_SENS MPU60X0_ACCEL_SENS[NAVSTIK_ACCEL_RANGE] #define IMU_ACCEL_X_SENS_NUM MPU60X0_ACCEL_SENS_FRAC[NAVSTIK_ACCEL_RANGE][0] #define IMU_ACCEL_X_SENS_DEN MPU60X0_ACCEL_SENS_FRAC[NAVSTIK_ACCEL_RANGE][1] #define IMU_ACCEL_Y_SENS MPU60X0_ACCEL_SENS[NAVSTIK_ACCEL_RANGE] #define IMU_ACCEL_Y_SENS_NUM MPU60X0_ACCEL_SENS_FRAC[NAVSTIK_ACCEL_RANGE][0] #define IMU_ACCEL_Y_SENS_DEN MPU60X0_ACCEL_SENS_FRAC[NAVSTIK_ACCEL_RANGE][1] #define IMU_ACCEL_Z_SENS MPU60X0_ACCEL_SENS[NAVSTIK_ACCEL_RANGE] #define IMU_ACCEL_Z_SENS_NUM MPU60X0_ACCEL_SENS_FRAC[NAVSTIK_ACCEL_RANGE][0] #define IMU_ACCEL_Z_SENS_DEN MPU60X0_ACCEL_SENS_FRAC[NAVSTIK_ACCEL_RANGE][1] #endif struct ImuNavstik { struct Mpu60x0_I2c mpu; struct Hmc58xx hmc; }; extern struct ImuNavstik imu_navstik; extern void imu_navstik_init(void); extern void imu_navstik_periodic(void); extern void imu_navstik_event(void); #endif /* IMU_NAVSTIK_H */
{ "pile_set_name": "Github" }
import tensorflow as tf import numpy as np writer = tf.python_io.TFRecordWriter("trainArray.tfrecords") for _ in range(100): randomArray = np.random.random((1,3)) array_raw = randomArray.tobytes() example = tf.train.Example(features=tf.train.Features(feature={ "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[0])), 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[array_raw])) })) writer.write(example.SerializeToString()) writer.close()
{ "pile_set_name": "Github" }
package cty import ( "fmt" "testing" ) func TestWalk(t *testing.T) { type Call struct { Path string Type string } val := ObjectVal(map[string]Value{ "string": StringVal("hello"), "number": NumberIntVal(10), "bool": True, "list": ListVal([]Value{True}), "list_empty": ListValEmpty(Bool), "set": SetVal([]Value{True}), "set_empty": ListValEmpty(Bool), "tuple": TupleVal([]Value{True}), "tuple_empty": EmptyTupleVal, "map": MapVal(map[string]Value{"true": True}), "map_empty": MapValEmpty(Bool), "object": ObjectVal(map[string]Value{"true": True}), "object_empty": EmptyObjectVal, "null": NullVal(List(String)), "unknown": UnknownVal(Map(Bool)), }) gotCalls := map[Call]struct{}{} wantCalls := []Call{ {`cty.Path(nil)`, "object"}, {`cty.Path{cty.GetAttrStep{Name:"string"}}`, "string"}, {`cty.Path{cty.GetAttrStep{Name:"number"}}`, "number"}, {`cty.Path{cty.GetAttrStep{Name:"bool"}}`, "bool"}, {`cty.Path{cty.GetAttrStep{Name:"list"}}`, "list of bool"}, {`cty.Path{cty.GetAttrStep{Name:"list"}, cty.IndexStep{Key:cty.NumberIntVal(0)}}`, "bool"}, {`cty.Path{cty.GetAttrStep{Name:"list_empty"}}`, "list of bool"}, {`cty.Path{cty.GetAttrStep{Name:"set"}}`, "set of bool"}, {`cty.Path{cty.GetAttrStep{Name:"set"}, cty.IndexStep{Key:cty.True}}`, "bool"}, {`cty.Path{cty.GetAttrStep{Name:"set_empty"}}`, "list of bool"}, {`cty.Path{cty.GetAttrStep{Name:"tuple"}}`, "tuple"}, {`cty.Path{cty.GetAttrStep{Name:"tuple"}, cty.IndexStep{Key:cty.NumberIntVal(0)}}`, "bool"}, {`cty.Path{cty.GetAttrStep{Name:"tuple_empty"}}`, "tuple"}, {`cty.Path{cty.GetAttrStep{Name:"map"}, cty.IndexStep{Key:cty.StringVal("true")}}`, "bool"}, {`cty.Path{cty.GetAttrStep{Name:"map"}}`, "map of bool"}, {`cty.Path{cty.GetAttrStep{Name:"map_empty"}}`, "map of bool"}, {`cty.Path{cty.GetAttrStep{Name:"object"}}`, "object"}, {`cty.Path{cty.GetAttrStep{Name:"object"}, cty.GetAttrStep{Name:"true"}}`, "bool"}, {`cty.Path{cty.GetAttrStep{Name:"object_empty"}}`, "object"}, {`cty.Path{cty.GetAttrStep{Name:"null"}}`, "list of string"}, {`cty.Path{cty.GetAttrStep{Name:"unknown"}}`, "map of bool"}, } err := Walk(val, func(path Path, val Value) (bool, error) { gotCalls[Call{ Path: fmt.Sprintf("%#v", path), Type: val.Type().FriendlyName(), }] = struct{}{} return true, nil }) if err != nil { t.Fatal(err) } if len(gotCalls) != len(wantCalls) { t.Errorf("wrong number of calls %d; want %d", len(gotCalls), len(wantCalls)) } for gotCall := range gotCalls { t.Logf("got call {%#q, %q}", gotCall.Path, gotCall.Type) } for _, wantCall := range wantCalls { if _, has := gotCalls[wantCall]; !has { t.Errorf("missing call {%#q, %q}", wantCall.Path, wantCall.Type) } } } func TestTransform(t *testing.T) { val := ObjectVal(map[string]Value{ "string": StringVal("hello"), "number": NumberIntVal(10), "bool": True, "list": ListVal([]Value{True}), "list_empty": ListValEmpty(Bool), "set": SetVal([]Value{True}), "set_empty": ListValEmpty(Bool), "tuple": TupleVal([]Value{True}), "tuple_empty": EmptyTupleVal, "map": MapVal(map[string]Value{"true": True}), "map_empty": MapValEmpty(Bool), "object": ObjectVal(map[string]Value{"true": True}), "object_empty": EmptyObjectVal, "null": NullVal(String), "unknown": UnknownVal(Bool), "null_list": NullVal(List(String)), "unknown_map": UnknownVal(Map(Bool)), }) gotVal, err := Transform(val, func(path Path, val Value) (Value, error) { if val.Type().IsPrimitiveType() { return StringVal(fmt.Sprintf("%#v", path)), nil } return val, nil }) if err != nil { t.Fatalf("unexpected error: %s", err) } wantVal := ObjectVal(map[string]Value{ "string": StringVal(`cty.Path{cty.GetAttrStep{Name:"string"}}`), "number": StringVal(`cty.Path{cty.GetAttrStep{Name:"number"}}`), "bool": StringVal(`cty.Path{cty.GetAttrStep{Name:"bool"}}`), "list": ListVal([]Value{StringVal(`cty.Path{cty.GetAttrStep{Name:"list"}, cty.IndexStep{Key:cty.NumberIntVal(0)}}`)}), "list_empty": ListValEmpty(Bool), "set": SetVal([]Value{StringVal(`cty.Path{cty.GetAttrStep{Name:"set"}, cty.IndexStep{Key:cty.True}}`)}), "set_empty": ListValEmpty(Bool), "tuple": TupleVal([]Value{StringVal(`cty.Path{cty.GetAttrStep{Name:"tuple"}, cty.IndexStep{Key:cty.NumberIntVal(0)}}`)}), "tuple_empty": EmptyTupleVal, "map": MapVal(map[string]Value{"true": StringVal(`cty.Path{cty.GetAttrStep{Name:"map"}, cty.IndexStep{Key:cty.StringVal("true")}}`)}), "map_empty": MapValEmpty(Bool), "object": ObjectVal(map[string]Value{"true": StringVal(`cty.Path{cty.GetAttrStep{Name:"object"}, cty.GetAttrStep{Name:"true"}}`)}), "object_empty": EmptyObjectVal, "null": StringVal(`cty.Path{cty.GetAttrStep{Name:"null"}}`), "unknown": StringVal(`cty.Path{cty.GetAttrStep{Name:"unknown"}}`), "null_list": NullVal(List(String)), "unknown_map": UnknownVal(Map(Bool)), }) if !gotVal.RawEquals(wantVal) { if got, want := len(gotVal.Type().AttributeTypes()), len(gotVal.Type().AttributeTypes()); got != want { t.Errorf("wrong length %d; want %d", got, want) } for it := wantVal.ElementIterator(); it.Next(); { key, wantElem := it.Element() attr := key.AsString() if !gotVal.Type().HasAttribute(attr) { t.Errorf("missing attribute %q", attr) continue } gotElem := gotVal.GetAttr(attr) if !gotElem.RawEquals(wantElem) { t.Errorf("wrong value for attribute %q\ngot: %#v\nwant: %#v", attr, gotElem, wantElem) } } } }
{ "pile_set_name": "Github" }
// Copyright (c) 2016-2020 Bluespec, Inc. All Rights Reserved package UART_Model; // ================================================================ // This package implements a slave IP, a UART model. // // This is a basic (and somewhat incomplete) model of a classic 16550 // UART, enough to do basic character reads and writes, interrupts, // etc. Just sends/receives the chars into Get/Put interfaces, // leaving it to external logic to manage actual physical // tranmit/receive. In particular, this module does nothing about // clock speed, baud rates, etc. // // Bus interface width: This slave IP can be attached to fabrics with // 32b- or 64b-wide data channels. The type parameter 'Wd_Data' in // Fabric_Defs.bsv specifies this. // // Address stride: the 16550 UART's registers are just 1-byte wide. // As a slave IP in a system, this IP places them at aligned addresses // with a gap of 4 or 8 bytes. This is controlled by the Integer // parameter 'address_stride' in this file. // Some of the 'truncate()'s and 'zeroExtend()'s below are no-ops but // necessary to satisfy type-checking, to manage these width // variations. // ================================================================ export UART_IFC (..), mkUART; // ================================================================ // BSV library imports import Vector :: *; import FIFOF :: *; import GetPut :: *; import ClientServer :: *; import ConfigReg :: *; // ---------------- // BSV additional libs import Cur_Cycle :: *; import GetPut_Aux :: *; import Semi_FIFOF :: *; // ================================================================ // Project imports import AXI4_Types :: *; import Fabric_Defs :: *; // ================================================================ // UART registers and their address offsets Bit #(3) addr_UART_rbr = 3'h_0; // receiver buffer register (read only) Bit #(3) addr_UART_thr = 3'h_0; // transmitter holding register (write only) Bit #(3) addr_UART_ier = 3'h_1; // interrupt enable register Bit #(3) addr_UART_iir = 3'h_2; // interrupt id register (read-only) Bit #(3) addr_UART_lcr = 3'h_3; // line control reg Bit #(3) addr_UART_mcr = 3'h_4; // modem control reg Bit #(3) addr_UART_lsr = 3'h_5; // line status reg (read-only) Bit #(3) addr_UART_msr = 3'h_6; // modem status reg (read-only) Bit #(3) addr_UART_scr = 3'h_7; // scratch pad reg // Aliased registers, depending on control bits Bit #(3) addr_UART_dll = 3'h_0; // divisor latch low Bit #(3) addr_UART_dlm = 3'h_1; // divisor latch high Bit #(3) addr_UART_fcr = 3'h_2; // fifo control reg (write-only) // Bit fields of ier (Interrupt Enable Register) Bit #(8) uart_ier_erbfi = 8'h_01; // Enable Received Data Available Interrupt Bit #(8) uart_ier_etbei = 8'h_02; // Enable Transmitter Holding Register Empty Interrupt Bit #(8) uart_ier_elsi = 8'h_04; // Enable Receiver Line Status Interrupt Bit #(8) uart_ier_edssi = 8'h_08; // Enable Modem Status Interrupt // iir values (Interrupt Identification Register) in decreasing priority of interrupts Bit #(8) uart_iir_none = 8'h_01; // None (no interrupts pending) Bit #(8) uart_iir_rls = 8'h_06; // Receiver Line Status Bit #(8) uart_iir_rda = 8'h_04; // Received Data Available Bit #(8) uart_iir_cti = 8'h_0C; // Character Timeout Indication Bit #(8) uart_iir_thre = 8'h_02; // Transmitter Holding Register Empty Bit #(8) uart_iir_ms = 8'h_00; // Modem Status // Bit fields of LCR Bit #(8) uart_lcr_dlab = 8'h_80; // Divisor latch access bit Bit #(8) uart_lcr_bc = 8'h_40; // Break control Bit #(8) uart_lcr_sp = 8'h_20; // Stick parity Bit #(8) uart_lcr_eps = 8'h_10; // Even parity Bit #(8) uart_lcr_pen = 8'h_08; // Parity enable Bit #(8) uart_lcr_stb = 8'h_04; // # of stop bits (0=1b,1=2b) Bit #(8) uart_lcr_wls = 8'h_03; // word len (0:5b,1:6b,2:7b,3:8b) // Bit fields of LSR Bit #(8) uart_lsr_rxfe = 8'h_80; // Receiver FIFO error Bit #(8) uart_lsr_temt = 8'h_40; // Transmitter empty Bit #(8) uart_lsr_thre = 8'h_20; // THR empty Bit #(8) uart_lsr_bi = 8'h_10; // Break interrupt Bit #(8) uart_lsr_fe = 8'h_08; // Framing Error Bit #(8) uart_lsr_pe = 8'h_04; // Parity Error Bit #(8) uart_lsr_oe = 8'h_02; // Overrun Error Bit #(8) uart_lsr_dr = 8'h_01; // Data Ready Bit #(8) uart_lsr_reset_value = (uart_lsr_temt | uart_lsr_thre); // ================================================================ // THIS MODULE's INTERFACE interface UART_IFC; // Reset interface Server #(Bit #(0), Bit #(0)) server_reset; // set_addr_map should be called after this module's reset method Action set_addr_map (Fabric_Addr addr_base, Fabric_Addr addr_lim); // Main Fabric Reqs/Rsps interface AXI4_Slave_IFC #(Wd_Id, Wd_Addr, Wd_Data, Wd_User) slave; // To external console interface Get #(Bit #(8)) get_to_console; interface Put #(Bit #(8)) put_from_console; // Interrupt pending (* always_ready *) method Bool intr; endinterface // ================================================================ // Local types and constants // Module state typedef enum {STATE_START, STATE_READY } Module_State deriving (Bits, Eq, FShow); // ================================================================ // Addressing of UART registers // ---------------------------------------------------------------- // UART reg addresses should be at stride 4 or 8. Integer address_stride = 4; // Integer address_stride = 8; // ---------------------------------------------------------------- // Split a bus address into (offset, lsbs), based on the address // stride. function Tuple2 #(Bit #(64), Bit #(3)) split_addr (Bit #(64) addr); Bit #(64) offset = ((address_stride == 4) ? (addr >> 2) : (addr >> 3)); Bit #(3) lsbs = ((address_stride == 4) ? { 1'b0, addr [1:0] } : addr [2:0]); return tuple2 (offset, lsbs); endfunction // ---------------------------------------------------------------- // Extract data from AXI4 byte lanes, based on the AXI4 'strobe' // (byte-enable) bits. function Bit #(64) fn_extract_AXI4_data (Bit #(64) data, Bit #(8) strb); Bit #(64) result = 0; case (strb) 8'b_0000_0001: result = zeroExtend (data [ 7:0]); 8'b_0000_0010: result = zeroExtend (data [15:8]); 8'b_0000_0100: result = zeroExtend (data [23:16]); 8'b_0000_1000: result = zeroExtend (data [31:24]); 8'b_0001_0000: result = zeroExtend (data [39:32]); 8'b_0010_0000: result = zeroExtend (data [47:40]); 8'b_0100_0000: result = zeroExtend (data [55:48]); 8'b_1000_0000: result = zeroExtend (data [63:56]); 8'b_0000_0011: result = zeroExtend (data [15:0]); 8'b_0000_1100: result = zeroExtend (data [31:16]); 8'b_0011_0000: result = zeroExtend (data [47:32]); 8'b_1100_0000: result = zeroExtend (data [63:48]); 8'b_0000_1111: result = zeroExtend (data [31:0]); 8'b_1111_0000: result = zeroExtend (data [63:32]); 8'b_1111_1111: result = zeroExtend (data [63:0]); endcase return result; endfunction // ================================================================ // THIS MODULE's IMPLEMENTATION (* synthesize *) module mkUART (UART_IFC); // 0: quiet; 1: reset and char input/output; 2: + detail Integer verbosity = 0; Reg #(Module_State) rg_state <- mkReg (STATE_START); // These regs represent where this UART is placed in the address space. Reg #(Fabric_Addr) rg_addr_base <- mkRegU; Reg #(Fabric_Addr) rg_addr_lim <- mkRegU; FIFOF #(Bit #(0)) f_reset_reqs <- mkFIFOF; FIFOF #(Bit #(0)) f_reset_rsps <- mkFIFOF; // ---------------- // Connector to AXI4 fabric AXI4_Slave_Xactor_IFC #(Wd_Id, Wd_Addr, Wd_Data, Wd_User) slave_xactor <- mkAXI4_Slave_Xactor; // ---------------- // character queues to and from external circuitry for the console FIFOF #(Bit #(8)) f_from_console <- mkFIFOF; FIFOF #(Bit #(8)) f_to_console <- mkFIFOF; // ---------------- // These are the 16550 UART registers // See fn_addr_offset() above for meaning of 'addr offset' Reg #(Bit #(8)) rg_rbr <- mkRegU; // addr offset 0 Reg #(Bit #(8)) rg_thr <- mkRegU; // addr offset 0 Reg #(Bit #(8)) rg_dll <- mkReg (0); // addr offset 0 Reg #(Bit #(8)) rg_ier <- mkReg (0); // addr offset 1 Reg #(Bit #(8)) rg_dlm <- mkReg (0); // addr offset 1 // IIR is a virtual read-only register computed from other regs Reg #(Bit #(8)) rg_fcr <- mkReg (0); // addr offset 2 Reg #(Bit #(8)) rg_lcr <- mkReg (0); // addr offset 3 Reg #(Bit #(8)) rg_mcr <- mkReg (0); // addr offset 4 Reg #(Bit #(8)) rg_lsr <- mkReg (uart_lsr_reset_value); // addr offset 5 Reg #(Bit #(8)) rg_msr <- mkReg (0); // addr offset 6 Reg #(Bit #(8)) rg_scr <- mkReg (0); // addr offset 7 // ---------------- // Virtual read-only register IIR function Bit #(8) fn_iir (); Bit #(8) iir = uart_iir_none; if ( ((rg_ier & uart_ier_erbfi) != 0) // Rx interrupt enabled && ((rg_lsr & uart_lsr_dr) != 0)) // data ready iir = uart_iir_rda; else if ((rg_ier & uart_ier_etbei) != 0) // Tx Holding Reg Empty intr enabled iir = uart_iir_thre; return iir; endfunction // ---------------- // Test if an interrupt is pending function Bool fn_intr (); let iir = fn_iir (); Bool eip = ((iir & uart_iir_none) == 0); return eip; endfunction // ================================================================ // BEHAVIOR // ---------------------------------------------------------------- // Soft reset (on token in f_reset_reqs) rule rl_reset; f_reset_reqs.deq; rg_dll <= 0; rg_ier <= 0; rg_dlm <= 0; rg_fcr <= 0; rg_lcr <= 0; rg_mcr <= 0; rg_lsr <= uart_lsr_reset_value; rg_msr <= 0; rg_scr <= 0; slave_xactor.reset; rg_state <= STATE_READY; f_reset_rsps.enq (?); if (verbosity != 0) $display ("%0d: UART.rl_reset", cur_cycle); endrule // ---------------------------------------------------------------- // Handle fabric read requests rule rl_process_rd_req (rg_state == STATE_READY); let rda <- pop_o (slave_xactor.o_rd_addr); let byte_addr = rda.araddr - rg_addr_base; match { .offset, .lsbs } = split_addr (zeroExtend (byte_addr)); Bit #(8) rdata_byte = 0; AXI4_Resp rresp = axi4_resp_okay; if ((rda.araddr < rg_addr_base) || (rda.araddr >= rg_addr_lim)) begin $display ("%0d: %m.rl_process_rd_req: ERROR: UART addr out of bounds", cur_cycle); $display (" UART base addr 0x%0h limit addr 0x%0h", rg_addr_base, rg_addr_lim); $display (" AXI4 request: ", fshow (rda)); rresp = axi4_resp_decerr; end else if (lsbs != 0) begin $display ("%0d: %m.rl_process_rd_req: ERROR: UART misaligned addr", cur_cycle); $display (" ", fshow (rda)); rresp = axi4_resp_slverr; end else if (offset [63:3] != 0) begin $display ("%0d: %m.rl_process_rd_req: ERROR: UART unsupported addr", cur_cycle); $display (" Register offset 0x%0h", offset); $display (" ", fshow (rda)); rresp = axi4_resp_decerr; end // offset 0: RBR else if ((offset [2:0] == addr_UART_rbr) && ((rg_lcr & uart_lcr_dlab) == 0)) begin // Read an input char rg_lsr <= (rg_lsr & (~ uart_lsr_dr)); // Reset data-ready rdata_byte = rg_rbr; end // offset 0: DLL else if ((offset [2:0] == addr_UART_dll) && ((rg_lcr & uart_lcr_dlab) != 0)) rdata_byte = rg_dll; // offset 1: IER else if ((offset [2:0] == addr_UART_ier) && ((rg_lcr & uart_lcr_dlab) == 0)) rdata_byte = rg_ier; // offset 1: DLM else if ((offset [2:0] == addr_UART_dlm) && ((rg_lcr & uart_lcr_dlab) != 0)) rdata_byte = rg_dlm; // offset 2: IIR (read-only) else if (offset [2:0] == addr_UART_iir) rdata_byte = fn_iir(); // offset 3: LCR else if (offset [2:0] == addr_UART_lcr) rdata_byte = { 0, rg_lcr }; // offset 4: MCR else if (offset [2:0] == addr_UART_mcr) rdata_byte = { 0, rg_mcr }; // offset 5: LSR else if (offset [2:0] == addr_UART_lsr) rdata_byte = { 0, rg_lsr }; // offset 6: MSR else if (offset [2:0] == addr_UART_msr) rdata_byte = { 0, rg_msr }; // offset 7: SCR else if (offset [2:0] == addr_UART_scr) rdata_byte = { 0, rg_scr }; else begin $display ("%0d: %m.rl_process_rd_req: ERROR: UART unsupported addr", cur_cycle); $display (" ", fshow (rda)); rresp = axi4_resp_decerr; end // Align data byte for AXI4 data bus based on fabric-width Fabric_Data rdata = zeroExtend (rdata_byte); if ((valueOf (Wd_Data) == 64) && (byte_addr [2:0] == 3'b100)) rdata = rdata << 32; // Send read-response to bus let rdr = AXI4_Rd_Data {rid: rda.arid, rdata: rdata, rresp: rresp, rlast: True, ruser: rda.aruser}; slave_xactor.i_rd_data.enq (rdr); if (verbosity > 1) begin $display ("%0d: %m.rl_process_rd_req", cur_cycle); $display (" ", fshow (rda)); $display (" ", fshow (rdr)); $display (" UART reg [%0h] => 0x%0h", offset [2:0], rdata_byte); end endrule // ---------------------------------------------------------------- // Handle fabric write requests rule rl_process_wr_req (rg_state == STATE_READY); let wra <- pop_o (slave_xactor.o_wr_addr); let wrd <- pop_o (slave_xactor.o_wr_data); Bit #(64) wdata = zeroExtend (wrd.wdata); Bit #(8) wstrb = zeroExtend (wrd.wstrb); Bit #(8) data_byte = truncate (fn_extract_AXI4_data (wdata, wstrb)); let byte_addr = wra.awaddr - rg_addr_base; match { .offset, .lsbs } = split_addr (zeroExtend (byte_addr)); AXI4_Resp bresp = axi4_resp_okay; if ((wra.awaddr < rg_addr_base) || (wra.awaddr >= rg_addr_lim)) begin $display ("%0d: %m.rl_process_rd_req: ERROR: UART addr out of bounds", cur_cycle); $display (" UART base addr 0x%0h limit addr 0x%0h", rg_addr_base, rg_addr_lim); $display (" AXI4 request: ", fshow (wra)); bresp = axi4_resp_decerr; end else if (lsbs != 0) begin $display ("%0d: %m.rl_process_wr_req: ERROR: UART misaligned addr", cur_cycle); $display (" ", fshow (wra)); bresp = axi4_resp_slverr; end else if (offset [63:3] != 0) begin $display ("%0d: %m.rl_process_wr_req: ERROR: UART unsupported addr", cur_cycle); $display (" Register offset 0x%0h", offset); $display (" ", fshow (wra)); $display (" ", fshow (wrd)); bresp = axi4_resp_decerr; end // offset 0: THR else if ((offset [2:0] == addr_UART_thr) && ((rg_lcr & uart_lcr_dlab) == 0)) begin // Write a char to the serial line rg_thr <= data_byte; f_to_console.enq (data_byte); if (verbosity != 0) $display ("%0d: %m.rl_process_wr_req: ASCII %0d (0x%0h)", cur_cycle, data_byte, data_byte); end // offset 0: DLL else if ((offset [2:0] == addr_UART_dll) && ((rg_lcr & uart_lcr_dlab) != 0)) rg_dll <= data_byte; // offset 1: IER else if ((offset [2:0] == addr_UART_ier) && ((rg_lcr & uart_lcr_dlab) == 0)) rg_ier <= data_byte; // offset 1: DLM else if ((offset [2:0] == addr_UART_dlm) && ((rg_lcr & uart_lcr_dlab) != 0)) rg_dlm <= data_byte; // offset 2: FCR (write-only) else if (offset [2:0] == addr_UART_fcr) rg_fcr <= data_byte; // offset 3: LCR else if (offset [2:0] == addr_UART_lcr) rg_lcr <= data_byte; // offset 4: MCR else if (offset [2:0] == addr_UART_mcr) rg_mcr <= data_byte; // offset 5: LSR else if (offset [2:0] == addr_UART_lsr) noAction; // LSR is read-only // offset 6: MSR else if (offset [2:0] == addr_UART_msr) noAction; // MSR is read-only // offset 7: SCR else if (offset [2:0] == addr_UART_scr) rg_scr <= data_byte; else begin $display ("%0d: %m.rl_process_wr_req: ERROR: UART unsupported addr", cur_cycle); $display (" ", fshow (wra)); $display (" ", fshow (wrd)); bresp = axi4_resp_decerr; end // Send write-response to bus let wrr = AXI4_Wr_Resp {bid: wra.awid, bresp: bresp, buser: wra.awuser}; slave_xactor.i_wr_resp.enq (wrr); if (verbosity > 1) begin $display ("%0d: %m.rl_process_wr_req", cur_cycle); $display (" ", fshow (wra)); $display (" ", fshow (wrd)); $display (" ", fshow (wrr)); $display (" UART reg [%0h] <= data %0h", offset [2:0], data_byte); end endrule // ---------------------------------------------------------------- // Receive a char from the serial line when RBR is empty (i.e., LSR.DR is 0), // and deposit it into RBR // and set it full (LSR.DR = 1) (* descending_urgency = "rl_receive, rl_process_rd_req" *) rule rl_receive ((rg_lsr & uart_lsr_dr) == 0); let ch <- pop (f_from_console); rg_rbr <= ch; let new_lsr = (rg_lsr | uart_lsr_dr); // Set data-ready rg_lsr <= new_lsr; if (verbosity > 1) $display ("UART_Model.rl_receive: received char 0x%0h; new_lsr = 0x%0h", ch, new_lsr); endrule // ================================================================ // INTERFACE // Reset interface server_reset = toGPServer (f_reset_reqs, f_reset_rsps); // set_addr_map should be called after this module's reset method Action set_addr_map (Fabric_Addr addr_base, Fabric_Addr addr_lim); if (addr_base [2:0] != 0) $display ("%0d: WARNING: UART.set_addr_map: addr_base 0x%0h is not 8-Byte-aligned", cur_cycle, addr_base); if (addr_lim [2:0] != 0) $display ("%0d: WARNING: UART.set_addr_map: addr_lim 0x%0h is not 8-Byte-aligned", cur_cycle, addr_lim); rg_addr_base <= addr_base; rg_addr_lim <= addr_lim; endmethod // Main Fabric Reqs/Rsps interface slave = slave_xactor.axi_side; // To external console interface put_from_console = toPut (f_from_console); interface get_to_console = toGet (f_to_console); // Interrupt pending method Bool intr; return fn_intr (); endmethod endmodule // ================================================================ endpackage
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root>
{ "pile_set_name": "Github" }
// sciter-mfc.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "sciter-mfc.h" #include "MainFrm.h" #pragma comment(lib, "windowscodecs.lib") #ifdef _DEBUG #define new DEBUG_NEW #endif // CSciterMfcApp BEGIN_MESSAGE_MAP(CSciterMfcApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CSciterMfcApp::OnAppAbout) END_MESSAGE_MAP() // CSciterMfcApp construction CSciterMfcApp::CSciterMfcApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("sciter-mfc.AppID.NoVersion")); // TODO: add construction code here, // Place all significant initialization in InitInstance SciterSetOption(NULL, SCITER_SET_SCRIPT_RUNTIME_FEATURES, ALLOW_FILE_IO | ALLOW_SOCKET_IO | ALLOW_EVAL | ALLOW_SYSINFO); SciterSetOption(NULL, SCITER_SET_DEBUG_MODE, TRUE); } // The one and only CSciterMfcApp object CSciterMfcApp theApp; // CSciterMfcApp initialization BOOL CSciterMfcApp::InitInstance() { OleInitialize(NULL); // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); SciterSetOption(NULL, SCITER_SET_SCRIPT_RUNTIME_FEATURES, ALLOW_FILE_IO | ALLOW_SOCKET_IO | ALLOW_EVAL | ALLOW_SYSINFO); // To create the main window, this code creates a new frame window // object and then sets it as the application's main window object CMainFrame* pFrame = new CMainFrame; if (!pFrame) return FALSE; m_pMainWnd = pFrame; // create and load the frame with its resources pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL); // The one and only window has been initialized, so show and update it pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand return TRUE; } int CSciterMfcApp::ExitInstance() { //TODO: handle additional resources you may have added return CWinApp::ExitInstance(); } // CSciterMfcApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CSciterMfcApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CSciterMfcApp message handlers
{ "pile_set_name": "Github" }
/* Feathers Copyright 2012-2020 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.core.FeathersControl; import feathers.core.ITextBaselineControl; import feathers.core.PropertyProxy; import feathers.data.IListCollection; import feathers.events.CollectionEventType; import feathers.events.FeathersEventType; import feathers.layout.Direction; import feathers.layout.FlowLayout; import feathers.layout.HorizontalAlign; import feathers.layout.HorizontalLayout; import feathers.layout.ILayout; import feathers.layout.IVirtualLayout; import feathers.layout.LayoutBoundsResult; import feathers.layout.VerticalAlign; import feathers.layout.VerticalLayout; import feathers.layout.ViewPortBounds; import feathers.skins.IStyleProvider; import flash.utils.Dictionary; import starling.display.DisplayObject; import starling.events.Event; /** * A style name to add to all buttons in this button group. Typically * used by a theme to provide different styles to different button groups. * * <p>The following example provides a custom button style name:</p> * * <listing version="3.0"> * group.customButtonStyleName = "my-custom-button";</listing> * * <p>In your theme, you can target this sub-component style name to * provide different styles than the default:</p> * * <listing version="3.0"> * getStyleProviderForClass( Button ).setFunctionForStyleName( "my-custom-button", setCustomButtonStyles );</listing> * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_BUTTON * @see feathers.core.FeathersControl#styleNameList */ [Style(name="customButtonStyleName",type="String")] /** * A style name to add to the first button in this button group. * Typically used by a theme to provide different styles to the first * button. * * <p>The following example provides a custom first button style name:</p> * * <listing version="3.0"> * group.customFirstButtonStyleName = "my-custom-first-button";</listing> * * <p>In your theme, you can target this sub-component style name to * provide different styles than the default:</p> * * <listing version="3.0"> * getStyleProviderForClass( Button ).setFunctionForStyleName( "my-custom-first-button", setCustomFirstButtonStyles );</listing> * * @default null * * @see feathers.core.FeathersControl#styleNameList */ [Style(name="customFirstButtonStyleName",type="String")] /** * A style name to add to the last button in this button group. * Typically used by a theme to provide different styles to the last * button. * * <p>The following example provides a custom last button style name:</p> * * <listing version="3.0"> * group.customLastButtonStyleName = "my-custom-last-button";</listing> * * <p>In your theme, you can target this sub-component style name to * provide different styles than the default:</p> * * <listing version="3.0"> * getStyleProviderForClass( Button ).setFunctionForStyleName( "my-custom-last-button", setCustomLastButtonStyles );</listing> * * @default null * * @see feathers.core.FeathersControl#styleNameList */ [Style(name="customLastButtonStyleName",type="String")] /** * The button group layout is either vertical or horizontal. * * <p>If the <code>direction</code> is * <code>Direction.HORIZONTAL</code> and * <code>distributeButtonSizes</code> is <code>false</code>, the buttons * may be displayed in multiple rows, if they won't fit in one row * horizontally.</p> * * <p>The following example sets the layout direction of the buttons * to line them up horizontally:</p> * * <listing version="3.0"> * group.direction = Direction.HORIZONTAL;</listing> * * <p><strong>Note:</strong> The <code>Direction.NONE</code> * constant is not supported.</p> * * @default feathers.layout.Direction.VERTICAL * * @see feathers.layout.Direction#HORIZONTAL * @see feathers.layout.Direction#VERTICAL */ [Style(name="direction",type="String")] /** * If <code>true</code>, the buttons will be equally sized in the * direction of the layout. In other words, if the button group is * horizontal, each button will have the same width, and if the button * group is vertical, each button will have the same height. If * <code>false</code>, the buttons will be sized to their ideal * dimensions. * * <p>The following example doesn't distribute the button sizes:</p> * * <listing version="3.0"> * group.distributeButtonSizes = false;</listing> * * @default true */ [Style(name="distributeButtonSizes",type="Boolean")] /** * Space, in pixels, between the first two buttons. If <code>NaN</code>, * the default <code>gap</code> property will be used. * * <p>The following example sets the gap between the first and second * button to a different value than the standard gap:</p> * * <listing version="3.0"> * group.firstGap = 30; * group.gap = 20;</listing> * * @default NaN * * @see #style:gap * @see #style:lastGap */ [Style(name="firstGap",type="Number")] /** * Space, in pixels, between buttons. * * <p>The following example sets the gap used for the button layout to * 20 pixels:</p> * * <listing version="3.0"> * group.gap = 20;</listing> * * @default 0 * * @see #style:firstGap * @see #style:lastGap */ [Style(name="gap",type="Number")] /** * Determines how the buttons are horizontally aligned within the bounds * of the button group (on the x-axis). * * <p>The following example aligns the group's content to the left:</p> * * <listing version="3.0"> * group.horizontalAlign = HorizontalAlign.LEFT;</listing> * * @default feathers.layout.HorizontalAlign.JUSTIFY * * @see feathers.layout.HorizontalAlign#LEFT * @see feathers.layout.HorizontalAlign#CENTER * @see feathers.layout.HorizontalAlign#RIGHT * @see feathers.layout.HorizontalAlign#JUSTIFY */ [Style(name="horizontalAlign",type="String")] /** * Space, in pixels, between the last two buttons. If <code>NaN</code>, * the default <code>gap</code> property will be used. * * <p>The following example sets the gap between the last and next to last * button to a different value than the standard gap:</p> * * <listing version="3.0"> * group.lastGap = 30; * group.gap = 20;</listing> * * @default NaN * * @see #style:gap * @see #style:firstGap */ [Style(name="lastGap",type="Number")] /** * Quickly sets all padding properties to the same value. The * <code>padding</code> getter always returns the value of * <code>paddingTop</code>, but the other padding values may be * different. * * <p>In the following example, the padding of all sides of the group * is set to 20 pixels:</p> * * <listing version="3.0"> * group.padding = 20;</listing> * * @default 0 * * @see #style:paddingTop * @see #style:paddingRight * @see #style:paddingBottom * @see #style:paddingLeft */ [Style(name="padding",type="Number")] /** * The minimum space, in pixels, between the group's top edge and the * group's buttons. * * <p>In the following example, the padding on the top edge of the * group is set to 20 pixels:</p> * * <listing version="3.0"> * group.paddingTop = 20;</listing> * * @default 0 * * @see #style:padding */ [Style(name="paddingTop",type="Number")] /** * The minimum space, in pixels, between the group's right edge and the * group's buttons. * * <p>In the following example, the padding on the right edge of the * group is set to 20 pixels:</p> * * <listing version="3.0"> * group.paddingRight = 20;</listing> * * @default 0 * * @see #style:padding */ [Style(name="paddingRight",type="Number")] /** * The minimum space, in pixels, between the group's bottom edge and the * group's buttons. * * <p>In the following example, the padding on the bottom edge of the * group is set to 20 pixels:</p> * * <listing version="3.0"> * group.paddingBottom = 20;</listing> * * @default 0 * * @see #style:padding */ [Style(name="paddingBottom",type="Number")] /** * The minimum space, in pixels, between the group's left edge and the * group's buttons. * * <p>In the following example, the padding on the left edge of the * group is set to 20 pixels:</p> * * <listing version="3.0"> * group.paddingLeft = 20;</listing> * * @default 0 * * @see #style:padding */ [Style(name="paddingLeft",type="Number")] /** * Determines how the buttons are vertically aligned within the bounds * of the button group (on the y-axis). * * <p>The following example aligns the group's content to the top:</p> * * <listing version="3.0"> * group.verticalAlign = VerticalAlign.TOP;</listing> * * @default feathers.layout.VerticalAlign.JUSTIFY * * @see feathers.layout.VerticalAlign#TOP * @see feathers.layout.VerticalAlign#MIDDLE * @see feathers.layout.VerticalAlign#BOTTOM * @see feathers.layout.VerticalAlign#JUSTIFY */ [Style(name="verticalAlign",type="String")] /** * Dispatched when one of the buttons is triggered. The <code>data</code> * property of the event contains the item from the data provider that is * associated with the button that was triggered. * * <p>The following example listens to <code>Event.TRIGGERED</code> on the * button group instead of on individual buttons:</p> * * <listing version="3.0"> * group.dataProvider = new ArrayCollection( * [ * { label: "Yes" }, * { label: "No" }, * { label: "Cancel" }, * ]); * group.addEventListener( Event.TRIGGERED, function( event:Event, data:Object ):void * { * trace( "The button with label \"" + data.label + "\" was triggered." ); * }</listing> * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>.</td></tr> * <tr><td><code>data</code></td><td>The item associated with the button * that was triggered.</td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. Use the * <code>currentTarget</code> property to always access the Object * listening for the event.</td></tr> * </table> * * @eventType starling.events.Event.TRIGGERED */ [Event(name="triggered", type="starling.events.Event")] /** * A set of related buttons with layout, customized using a data provider. * * <p>The following example creates a button group with a few buttons:</p> * * <listing version="3.0"> * var group:ButtonGroup = new ButtonGroup(); * group.dataProvider = new ArrayCollection( * [ * { label: "Yes", triggered: yesButton_triggeredHandler }, * { label: "No", triggered: noButton_triggeredHandler }, * { label: "Cancel", triggered: cancelButton_triggeredHandler }, * ]); * this.addChild( group );</listing> * * @see ../../../help/button-group.html How to use the Feathers ButtonGroup component * @see feathers.controls.TabBar * * @productversion Feathers 1.0.0 */ public class ButtonGroup extends FeathersControl implements ITextBaselineControl { /** * The default <code>IStyleProvider</code> for all <code>ButtonGroup</code> * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * @private */ protected static const INVALIDATION_FLAG_BUTTON_FACTORY:String = "buttonFactory"; /** * @private */ protected static const LABEL_FIELD:String = "label"; /** * @private */ protected static const ENABLED_FIELD:String = "isEnabled"; /** * @private */ private static const DEFAULT_BUTTON_FIELDS:Vector.<String> = new <String> [ "defaultIcon", "upIcon", "downIcon", "hoverIcon", "disabledIcon", "defaultSelectedIcon", "selectedUpIcon", "selectedDownIcon", "selectedHoverIcon", "selectedDisabledIcon", "isSelected", "isToggle", "isLongPressEnabled", "name", ]; /** * @private */ private static const DEFAULT_BUTTON_EVENTS:Vector.<String> = new <String> [ Event.TRIGGERED, Event.CHANGE, FeathersEventType.LONG_PRESS, ]; /** * The default value added to the <code>styleNameList</code> of the buttons. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_BUTTON:String = "feathers-button-group-button"; /** * @private */ protected static function defaultButtonFactory():Button { return new Button(); } /** * Constructor. */ public function ButtonGroup() { super(); } /** * The value added to the <code>styleNameList</code> of the buttons. * This variable is <code>protected</code> so that sub-classes can * customize the button style name in their constructors instead of * using the default style name defined by * <code>DEFAULT_CHILD_STYLE_NAME_BUTTON</code>. * * <p>To customize the button style name without subclassing, see * <code>customButtonStyleName</code>.</p> * * @see #style:customButtonStyleName * @see feathers.core.FeathersControl#styleNameList */ protected var buttonStyleName:String = DEFAULT_CHILD_STYLE_NAME_BUTTON; /** * The value added to the <code>styleNameList</code> of the first button. * * <p>To customize the first button name without subclassing, see * <code>customFirstButtonStyleName</code>.</p> * * @see #style:customFirstButtonStyleName * @see feathers.core.FeathersControl#styleNameList */ protected var firstButtonStyleName:String = DEFAULT_CHILD_STYLE_NAME_BUTTON; /** * The value added to the <code>styleNameList</code> of the last button. * * <p>To customize the last button style name without subclassing, see * <code>customLastButtonStyleName</code>.</p> * * @see #style:customLastButtonStyleName * @see feathers.core.FeathersControl#styleNameList */ protected var lastButtonStyleName:String = DEFAULT_CHILD_STYLE_NAME_BUTTON; /** * @private */ protected var activeFirstButton:Button; /** * @private */ protected var inactiveFirstButton:Button; /** * @private */ protected var activeLastButton:Button; /** * @private */ protected var inactiveLastButton:Button; /** * @private */ protected var _layoutItems:Vector.<DisplayObject> = new <DisplayObject>[]; /** * @private */ protected var activeButtons:Vector.<Button> = new <Button>[]; /** * @private */ protected var inactiveButtons:Vector.<Button> = new <Button>[]; /** * @private */ protected var _buttonToItem:Dictionary = new Dictionary(true); /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return ButtonGroup.globalStyleProvider; } /** * @private */ protected var _dataProvider:IListCollection; /** * The collection of data to be displayed with buttons. * * <p>The following example sets the button group's data provider:</p> * * <listing version="3.0"> * group.dataProvider = new ArrayCollection( * [ * { label: "Yes", triggered: yesButton_triggeredHandler }, * { label: "No", triggered: noButton_triggeredHandler }, * { label: "Cancel", triggered: cancelButton_triggeredHandler }, * ]);</listing> * * <p>By default, items in the data provider support the following * properties from <code>Button</code></p> * * <ul> * <li>label</li> * <li>defaultIcon</li> * <li>upIcon</li> * <li>downIcon</li> * <li>hoverIcon</li> * <li>disabledIcon</li> * <li>defaultSelectedIcon</li> * <li>selectedUpIcon</li> * <li>selectedDownIcon</li> * <li>selectedHoverIcon</li> * <li>selectedDisabledIcon</li> * <li>isSelected (only supported by <code>ToggleButton</code>)</li> * <li>isToggle (only supported by <code>ToggleButton</code>)</li> * <li>isEnabled</li> * <li>name</li> * </ul> * * <p>Additionally, you can add the following event listeners:</p> * * <ul> * <li>Event.TRIGGERED</li> * <li>Event.CHANGE (only supported by <code>ToggleButton</code>)</li> * </ul> * * <p>Event listeners may have one of the following signatures:</p> * <pre>function(event:Event):void</pre> * <pre>function(event:Event, eventData:Object):void</pre> * <pre>function(event:Event, eventData:Object, dataProviderItem:Object):void</pre> * * <p>To use properties and events that are only supported by * <code>ToggleButton</code>, you must provide a <code>buttonFactory</code> * that returns a <code>ToggleButton</code> instead of a <code>Button</code>.</p> * * <p>You can pass a function to the <code>buttonInitializer</code> * property that can provide custom logic to interpret each item in the * data provider differently. For example, you could use it to support * additional properties or events.</p> * * @default null * * @see feathers.controls.Button * @see #buttonInitializer * @see feathers.data.ArrayCollection * @see feathers.data.VectorCollection * @see feathers.data.XMLListCollection */ public function get dataProvider():IListCollection { return this._dataProvider; } /** * @private */ public function set dataProvider(value:IListCollection):void { if(this._dataProvider == value) { return; } if(this._dataProvider) { this._dataProvider.removeEventListener(CollectionEventType.UPDATE_ALL, dataProvider_updateAllHandler); this._dataProvider.removeEventListener(CollectionEventType.UPDATE_ITEM, dataProvider_updateItemHandler); this._dataProvider.removeEventListener(Event.CHANGE, dataProvider_changeHandler); } this._dataProvider = value; if(this._dataProvider) { this._dataProvider.addEventListener(CollectionEventType.UPDATE_ALL, dataProvider_updateAllHandler); this._dataProvider.addEventListener(CollectionEventType.UPDATE_ITEM, dataProvider_updateItemHandler); this._dataProvider.addEventListener(Event.CHANGE, dataProvider_changeHandler); } this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var layout:ILayout; /** * @private */ protected var _viewPortBounds:ViewPortBounds = new ViewPortBounds(); /** * @private */ protected var _layoutResult:LayoutBoundsResult = new LayoutBoundsResult(); /** * @private */ protected var _direction:String = Direction.VERTICAL; [Inspectable(type="String",enumeration="horizontal,vertical")] /** * @private */ public function get direction():String { return _direction; } /** * @private */ public function set direction(value:String):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._direction === value) { return; } this._direction = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _horizontalAlign:String = HorizontalAlign.JUSTIFY; [Inspectable(type="String",enumeration="left,center,right,justify")] /** * @private */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._horizontalAlign === value) { return; } this._horizontalAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _verticalAlign:String = VerticalAlign.JUSTIFY; [Inspectable(type="String",enumeration="top,middle,bottom,justify")] /** * @private */ public function get verticalAlign():String { return _verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._verticalAlign === value) { return; } this._verticalAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _distributeButtonSizes:Boolean = true; /** * @private */ public function get distributeButtonSizes():Boolean { return this._distributeButtonSizes; } /** * @private */ public function set distributeButtonSizes(value:Boolean):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._distributeButtonSizes === value) { return; } this._distributeButtonSizes = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _gap:Number = 0; /** * @private */ public function get gap():Number { return this._gap; } /** * @private */ public function set gap(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._gap == value) { return; } this._gap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _firstGap:Number = NaN; /** * @private */ public function get firstGap():Number { return this._firstGap; } /** * @private */ public function set firstGap(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._firstGap == value) { return; } this._firstGap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _lastGap:Number = NaN; /** * @private */ public function get lastGap():Number { return this._lastGap; } /** * @private */ public function set lastGap(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._lastGap == value) { return; } this._lastGap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * @private */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._paddingTop == value) { return; } this._paddingTop = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingRight:Number = 0; /** * @private */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._paddingRight == value) { return; } this._paddingRight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingBottom:Number = 0; /** * @private */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingLeft:Number = 0; /** * @private */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _buttonFactory:Function = defaultButtonFactory; /** * Creates each button in the group. A button must be an instance of * <code>Button</code>. This factory can be used to change properties on * the buttons when they are first created. For instance, if you are * skinning Feathers components without a theme, you might use this * factory to set skins and other styles on a button. * * <p>Optionally, the first button and the last button may be different * than the other buttons that are in the middle. Use the * <code>firstButtonFactory</code> and/or the * <code>lastButtonFactory</code> to customize one or both of these * buttons.</p> * * <p>This function is expected to have the following signature:</p> * * <pre>function():Button</pre> * * <p>The following example skins the buttons using a custom button * factory:</p> * * <listing version="3.0"> * group.buttonFactory = function():Button * { * var button:Button = new Button(); * button.defaultSkin = new Image( texture ); * return button; * };</listing> * * @default null * * @see feathers.controls.Button * @see #firstButtonFactory * @see #lastButtonFactory */ public function get buttonFactory():Function { return this._buttonFactory; } /** * @private */ public function set buttonFactory(value:Function):void { if(this._buttonFactory == value) { return; } this._buttonFactory = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _firstButtonFactory:Function; /** * If not <code>null</code>, creates the first button. If the * <code>firstButtonFactory</code> is <code>null</code>, then the button * group will use the <code>buttonFactory</code>. The first button must * be an instance of <code>Button</code>. This factory can be used to * change properties on the first button when it is initially created. * For instance, if you are skinning Feathers components without a * theme, you might use this factory to set skins and other styles on * the first button. * * <p>This function is expected to have the following signature:</p> * * <pre>function():Button</pre> * * <p>The following example skins the first button using a custom * factory:</p> * * <listing version="3.0"> * group.firstButtonFactory = function():Button * { * var button:Button = new Button(); * button.defaultSkin = new Image( texture ); * return button; * };</listing> * * @default null * * @see feathers.controls.Button * @see #buttonFactory * @see #lastButtonFactory */ public function get firstButtonFactory():Function { return this._firstButtonFactory; } /** * @private */ public function set firstButtonFactory(value:Function):void { if(this._firstButtonFactory == value) { return; } this._firstButtonFactory = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _lastButtonFactory:Function; /** * If not <code>null</code>, creates the last button. If the * <code>lastButtonFactory</code> is <code>null</code>, then the button * group will use the <code>buttonFactory</code>. The last button must * be an instance of <code>Button</code>. This factory can be used to * change properties on the last button when it is initially created. * For instance, if you are skinning Feathers components without a * theme, you might use this factory to set skins and other styles on * the last button. * * <p>This function is expected to have the following signature:</p> * * <pre>function():Button</pre> * * <p>The following example skins the last button using a custom * factory:</p> * * <listing version="3.0"> * group.lastButtonFactory = function():Button * { * var button:Button = new Button(); * button.defaultSkin = new Image( texture ); * return button; * };</listing> * * @default null * * @see feathers.controls.Button * @see #buttonFactory * @see #firstButtonFactory */ public function get lastButtonFactory():Function { return this._lastButtonFactory; } /** * @private */ public function set lastButtonFactory(value:Function):void { if(this._lastButtonFactory == value) { return; } this._lastButtonFactory = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _buttonInitializer:Function = defaultButtonInitializer; /** * Modifies a button, perhaps by changing its label and icons, based on the * item from the data provider that the button is meant to represent. The * default buttonInitializer function can set the button's label and icons if * <code>label</code> and/or any of the <code>Button</code> icon fields * (<code>defaultIcon</code>, <code>upIcon</code>, etc.) are present in * the item. You can listen to <code>Event.TRIGGERED</code> and * <code>Event.CHANGE</code> by passing in functions for each. * * <p>This function is expected to have the following signature:</p> * * <pre>function( button:Button, item:Object ):void</pre> * * <p>The following example provides a custom button initializer:</p> * * <listing version="3.0"> * group.buttonInitializer = function( button:Button, item:Object ):void * { * button.label = item.label; * };</listing> * * @see #dataProvider */ public function get buttonInitializer():Function { return this._buttonInitializer; } /** * @private */ public function set buttonInitializer(value:Function):void { if(this._buttonInitializer == value) { return; } this._buttonInitializer = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _buttonReleaser:Function = defaultButtonReleaser; /** * Resets the properties of an individual button, using the item from the * data provider that was associated with the button. * * <p>This function is expected to have one of the following signatures:</p> * <pre>function( tab:Button ):void</pre> * <pre>function( tab:Button, oldItem:Object ):void</pre> * * <p>In the following example, a custom button releaser is passed to the * button group:</p> * * <listing version="3.0"> * group.buttonReleaser = function( button:Button, oldItem:Object ):void * { * button.label = null; * };</listing> * * @see #buttonInitializer */ public function get buttonReleaser():Function { return this._buttonReleaser; } /** * @private */ public function set buttonReleaser(value:Function):void { if(this._buttonReleaser == value) { return; } this._buttonReleaser = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _customButtonStyleName:String; /** * @private */ public function get customButtonStyleName():String { return this._customButtonStyleName; } /** * @private */ public function set customButtonStyleName(value:String):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._customButtonStyleName === value) { return; } this._customButtonStyleName = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _customFirstButtonStyleName:String; /** * @private */ public function get customFirstButtonStyleName():String { return this._customFirstButtonStyleName; } /** * @private */ public function set customFirstButtonStyleName(value:String):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._customFirstButtonStyleName === value) { return; } this._customFirstButtonStyleName = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _customLastButtonStyleName:String; /** * @private */ public function get customLastButtonStyleName():String { return this._customLastButtonStyleName; } /** * @private */ public function set customLastButtonStyleName(value:String):void { if(this.processStyleRestriction(arguments.callee)) { return; } if(this._customLastButtonStyleName === value) { return; } this._customLastButtonStyleName = value; this.invalidate(INVALIDATION_FLAG_BUTTON_FACTORY); } /** * @private */ protected var _buttonProperties:PropertyProxy; /** * An object that stores properties for all of the button group's * buttons, and the properties will be passed down to every button when * the button group validates. For a list of available properties, * refer to <a href="Button.html"><code>feathers.controls.Button</code></a>. * * <p>These properties are shared by every button, so anything that cannot * be shared (such as display objects, which cannot be added to multiple * parents) should be passed to buttons using the * <code>buttonFactory</code> or in the theme.</p> * * <p>If the subcomponent has its own subcomponents, their properties * can be set too, using attribute <code>&#64;</code> notation. For example, * to set the skin on the thumb which is in a <code>SimpleScrollBar</code>, * which is in a <code>List</code>, you can use the following syntax:</p> * <pre>list.verticalScrollBarProperties.&#64;thumbProperties.defaultSkin = new Image(texture);</pre> * * <p>The following example sets some properties on all of the buttons:</p> * * <listing version="3.0"> * group.buttonProperties.horizontalAlign = HorizontalAlign.LEFT; * group.buttonProperties.verticalAlign = VerticalAlign.TOP;</listing> * * <p>Setting properties in a <code>buttonFactory</code> function instead * of using <code>buttonProperties</code> will result in better * performance.</p> * * @default null * * @see #buttonFactory * @see #firstButtonFactory * @see #lastButtonFactory * @see feathers.controls.Button */ public function get buttonProperties():Object { if(!this._buttonProperties) { this._buttonProperties = new PropertyProxy(childProperties_onChange); } return this._buttonProperties; } /** * @private */ public function set buttonProperties(value:Object):void { if(this._buttonProperties == value) { return; } if(!value) { value = new PropertyProxy(); } if(!(value is PropertyProxy)) { var newValue:PropertyProxy = new PropertyProxy(); for(var propertyName:String in value) { newValue[propertyName] = value[propertyName]; } value = newValue; } if(this._buttonProperties) { this._buttonProperties.removeOnChangeCallback(childProperties_onChange); } this._buttonProperties = PropertyProxy(value); if(this._buttonProperties) { this._buttonProperties.addOnChangeCallback(childProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @inheritDoc */ public function get baseline():Number { if(!this.activeButtons || this.activeButtons.length == 0) { return this.scaledActualHeight; } var firstButton:Button = this.activeButtons[0]; return this.scaleY * (firstButton.y + firstButton.baseline); } /** * @private */ override public function dispose():void { this.dataProvider = null; super.dispose(); } /** * @private */ override protected function draw():void { var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var buttonFactoryInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_BUTTON_FACTORY); var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); if(dataInvalid || stateInvalid || buttonFactoryInvalid) { this.refreshButtons(buttonFactoryInvalid); } if(dataInvalid || buttonFactoryInvalid || stylesInvalid) { this.refreshButtonStyles(); } if(dataInvalid || stateInvalid || buttonFactoryInvalid) { this.commitEnabled(); } if(stylesInvalid) { this.refreshLayoutStyles(); } this.layoutButtons(); } /** * @private */ protected function commitEnabled():void { var buttonCount:int = this.activeButtons.length; for(var i:int = 0; i < buttonCount; i++) { var button:Button = this.activeButtons[i]; button.isEnabled &&= this._isEnabled; } } /** * @private */ protected function refreshButtonStyles():void { for(var propertyName:String in this._buttonProperties) { var propertyValue:Object = this._buttonProperties[propertyName]; for each(var button:Button in this.activeButtons) { button[propertyName] = propertyValue; } } } /** * @private */ protected function refreshLayoutStyles():void { if(this._direction == Direction.VERTICAL) { var verticalLayout:VerticalLayout = this.layout as VerticalLayout; if(!verticalLayout) { this.layout = verticalLayout = new VerticalLayout(); } verticalLayout.distributeHeights = this._distributeButtonSizes; verticalLayout.horizontalAlign = this._horizontalAlign; verticalLayout.verticalAlign = (this._verticalAlign == VerticalAlign.JUSTIFY) ? VerticalAlign.TOP : this._verticalAlign; verticalLayout.gap = this._gap; verticalLayout.firstGap = this._firstGap; verticalLayout.lastGap = this._lastGap; verticalLayout.paddingTop = this._paddingTop; verticalLayout.paddingRight = this._paddingRight; verticalLayout.paddingBottom = this._paddingBottom; verticalLayout.paddingLeft = this._paddingLeft; } else //horizontal { if(this._distributeButtonSizes) { var horizontalLayout:HorizontalLayout = this.layout as HorizontalLayout; if(!horizontalLayout) { this.layout = horizontalLayout = new HorizontalLayout(); } horizontalLayout.distributeWidths = true; horizontalLayout.horizontalAlign = (this._horizontalAlign == HorizontalAlign.JUSTIFY) ? HorizontalAlign.LEFT : this._horizontalAlign; horizontalLayout.verticalAlign = this._verticalAlign; horizontalLayout.gap = this._gap; horizontalLayout.firstGap = this._firstGap; horizontalLayout.lastGap = this._lastGap; horizontalLayout.paddingTop = this._paddingTop; horizontalLayout.paddingRight = this._paddingRight; horizontalLayout.paddingBottom = this._paddingBottom; horizontalLayout.paddingLeft = this._paddingLeft; } else { var flowLayout:FlowLayout = this.layout as FlowLayout; if(!flowLayout) { this.layout = flowLayout = new FlowLayout(); } flowLayout.horizontalAlign = (this._horizontalAlign == HorizontalAlign.JUSTIFY) ? HorizontalAlign.LEFT : this._horizontalAlign; flowLayout.verticalAlign = this._verticalAlign; flowLayout.gap = this._gap; flowLayout.firstHorizontalGap = this._firstGap; flowLayout.lastHorizontalGap = this._lastGap; flowLayout.paddingTop = this._paddingTop; flowLayout.paddingRight = this._paddingRight; flowLayout.paddingBottom = this._paddingBottom; flowLayout.paddingLeft = this._paddingLeft; } } if(layout is IVirtualLayout) { IVirtualLayout(layout).useVirtualLayout = false; } } /** * @private */ protected function defaultButtonInitializer(button:Button, item:Object):void { if(item is Object) { if(item.hasOwnProperty(LABEL_FIELD)) { button.label = item.label as String; } else { button.label = item.toString(); } if(item.hasOwnProperty(ENABLED_FIELD)) { button.isEnabled = item.isEnabled as Boolean; } else { button.isEnabled = this._isEnabled; } for each(var field:String in DEFAULT_BUTTON_FIELDS) { if(item.hasOwnProperty(field)) { button[field] = item[field]; } } for each(field in DEFAULT_BUTTON_EVENTS) { var removeListener:Boolean = true; if(item.hasOwnProperty(field)) { var listener:Function = item[field] as Function; if(listener === null) { continue; } removeListener = false; //we can't add the listener directly because we don't //know how to remove it later if the data provider //changes and we lose the old item. we'll use another //event listener that we control as a delegate, and //we'll be able to remove it later. button.addEventListener(field, defaultButtonEventsListener); } if(removeListener) { button.removeEventListener(field, defaultButtonEventsListener); } } } else { button.label = ""; button.isEnabled = this._isEnabled; } } /** * @private */ protected function defaultButtonReleaser(button:Button, oldItem:Object):void { button.label = null; for each(var field:String in DEFAULT_BUTTON_FIELDS) { if(oldItem.hasOwnProperty(field)) { button[field] = null; } } for each(field in DEFAULT_BUTTON_EVENTS) { var removeListener:Boolean = true; if(oldItem.hasOwnProperty(field)) { var listener:Function = oldItem[field] as Function; if(listener === null) { continue; } button.removeEventListener(field, defaultButtonEventsListener); } } } /** * @private */ protected function refreshButtons(isFactoryInvalid:Boolean):void { var temp:Vector.<Button> = this.inactiveButtons; this.inactiveButtons = this.activeButtons; this.activeButtons = temp; this.activeButtons.length = 0; this._layoutItems.length = 0; temp = null; if(isFactoryInvalid) { this.clearInactiveButtons(); } else { if(this.activeFirstButton) { this.inactiveButtons.shift(); } this.inactiveFirstButton = this.activeFirstButton; if(this.activeLastButton) { this.inactiveButtons.pop(); } this.inactiveLastButton = this.activeLastButton; } this.activeFirstButton = null; this.activeLastButton = null; var pushIndex:int = 0; var itemCount:int = this._dataProvider ? this._dataProvider.length : 0; var lastItemIndex:int = itemCount - 1; for(var i:int = 0; i < itemCount; i++) { var item:Object = this._dataProvider.getItemAt(i); if(i == 0) { var button:Button = this.activeFirstButton = this.createFirstButton(item); } else if(i == lastItemIndex) { button = this.activeLastButton = this.createLastButton(item); } else { button = this.createButton(item); } this.activeButtons[pushIndex] = button; this._layoutItems[pushIndex] = button; pushIndex++; } this.clearInactiveButtons(); } /** * @private */ protected function clearInactiveButtons():void { var itemCount:int = this.inactiveButtons.length; for(var i:int = 0; i < itemCount; i++) { var button:Button = this.inactiveButtons.shift(); this.destroyButton(button); } if(this.inactiveFirstButton) { this.destroyButton(this.inactiveFirstButton); this.inactiveFirstButton = null; } if(this.inactiveLastButton) { this.destroyButton(this.inactiveLastButton); this.inactiveLastButton = null; } } /** * @private */ protected function createFirstButton(item:Object):Button { var isNewInstance:Boolean = false; if(this.inactiveFirstButton !== null) { var button:Button = this.inactiveFirstButton; this.releaseButton(button); this.inactiveFirstButton = null; } else { isNewInstance = true; var factory:Function = this._firstButtonFactory != null ? this._firstButtonFactory : this._buttonFactory; button = Button(factory()); if(this._customFirstButtonStyleName) { button.styleNameList.add(this._customFirstButtonStyleName); } else if(this._customButtonStyleName) { button.styleNameList.add(this._customButtonStyleName); } else { button.styleNameList.add(this.firstButtonStyleName); } this.addChild(button); } this._buttonInitializer(button, item); this._buttonToItem[button] = item; if(isNewInstance) { //we need to listen for Event.TRIGGERED after the initializer //is called to avoid runtime errors because the button may be //disposed by the time listeners in the initializer are called. button.addEventListener(Event.TRIGGERED, button_triggeredHandler); } return button; } /** * @private */ protected function createLastButton(item:Object):Button { var isNewInstance:Boolean = false; if(this.inactiveLastButton !== null) { var button:Button = this.inactiveLastButton; this.releaseButton(button); this.inactiveLastButton = null; } else { isNewInstance = true; var factory:Function = this._lastButtonFactory != null ? this._lastButtonFactory : this._buttonFactory; button = Button(factory()); if(this._customLastButtonStyleName) { button.styleNameList.add(this._customLastButtonStyleName); } else if(this._customButtonStyleName) { button.styleNameList.add(this._customButtonStyleName); } else { button.styleNameList.add(this.lastButtonStyleName); } this.addChild(button); } this._buttonInitializer(button, item); this._buttonToItem[button] = item; if(isNewInstance) { //we need to listen for Event.TRIGGERED after the initializer //is called to avoid runtime errors because the button may be //disposed by the time listeners in the initializer are called. button.addEventListener(Event.TRIGGERED, button_triggeredHandler); } return button; } /** * @private */ protected function createButton(item:Object):Button { var isNewInstance:Boolean = false; if(this.inactiveButtons.length == 0) { isNewInstance = true; var button:Button = this._buttonFactory(); if(this._customButtonStyleName) { button.styleNameList.add(this._customButtonStyleName); } else { button.styleNameList.add(this.buttonStyleName); } this.addChild(button); } else { button = this.inactiveButtons.shift(); this.releaseButton(button); } this._buttonInitializer(button, item); this._buttonToItem[button] = item; if(isNewInstance) { //we need to listen for Event.TRIGGERED after the initializer //is called to avoid runtime errors because the button may be //disposed by the time listeners in the initializer are called. button.addEventListener(Event.TRIGGERED, button_triggeredHandler); } return button; } /** * @private */ protected function releaseButton(button:Button):void { var item:Object = this._buttonToItem[button]; delete this._buttonToItem[button]; if(this._buttonReleaser.length == 1) { this._buttonReleaser(button); } else { this._buttonReleaser(button, item); } } /** * @private */ protected function destroyButton(button:Button):void { button.removeEventListener(Event.TRIGGERED, button_triggeredHandler); this.releaseButton(button); this.removeChild(button, true); } /** * @private */ protected function layoutButtons():void { this._viewPortBounds.x = 0; this._viewPortBounds.y = 0; this._viewPortBounds.scrollX = 0; this._viewPortBounds.scrollY = 0; this._viewPortBounds.explicitWidth = this._explicitWidth; this._viewPortBounds.explicitHeight = this._explicitHeight; this._viewPortBounds.minWidth = this._explicitMinWidth; this._viewPortBounds.minHeight = this._explicitMinHeight; this._viewPortBounds.maxWidth = this._explicitMaxWidth; this._viewPortBounds.maxHeight = this._explicitMaxHeight; this.layout.layout(this._layoutItems, this._viewPortBounds, this._layoutResult); var contentWidth:Number = this._layoutResult.contentWidth; var contentHeight:Number = this._layoutResult.contentHeight; //minimum dimensions are the same as the measured dimensions this.saveMeasurements(contentWidth, contentHeight, contentWidth, contentHeight); //final validation to avoid juggler next frame issues for each(var button:Button in this.activeButtons) { button.validate(); } } /** * @private */ protected function childProperties_onChange(proxy:PropertyProxy, name:String):void { this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected function dataProvider_changeHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected function dataProvider_updateAllHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected function dataProvider_updateItemHandler(event:Event, index:int):void { this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected function button_triggeredHandler(event:Event):void { //if this was called after dispose, ignore it if(!this._dataProvider || !this.activeButtons) { return; } var button:Button = Button(event.currentTarget); var index:int = this.activeButtons.indexOf(button); var item:Object = this._dataProvider.getItemAt(index); this.dispatchEventWith(Event.TRIGGERED, false, item); } /** * @private */ protected function defaultButtonEventsListener(event:Event):void { var button:Button = Button(event.currentTarget); var index:int = this.activeButtons.indexOf(button); var item:Object = this._dataProvider.getItemAt(index); var field:String = event.type; if(item.hasOwnProperty(field)) { var listener:Function = item[field] as Function; if(listener == null) { return; } var argCount:int = listener.length; switch(argCount) { case 3: { listener(event, event.data, item); break; } case 2: { listener(event, event.data); break; } case 1: { listener(event); break; } default: { listener(); } } } } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingTop="7dp" android:paddingBottom="7dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingEnd="16dp" android:paddingStart="16dp"> <TextView android:id="@+id/NameLabel" android:textSize="@dimen/default_list_text_size" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
{ "pile_set_name": "Github" }
type identity('a) = Identity('a); let lazy_return = Lazy.from_fun(a => Identity(a)); let ap = (Identity(f), a) => Identity(f(a)); include Monad.MakeBasic({ type t('a) = identity('a); let bind = (Identity(a), f) => f(a) let return = a => Identity(a); let fmap = `DefineWithBind; });
{ "pile_set_name": "Github" }
// // Wowwww.m // dummy // // Created by Mark Larsen on 5/9/14. // Copyright (c) 2014 marklarr. All rights reserved. // #import "Wowwww.h" @implementation Wowwww @end
{ "pile_set_name": "Github" }
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Definition of the preprocessor context http://www.boost.org/ Copyright (c) 2001-2012 Hartmut Kaiser. 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) =============================================================================*/ #if !defined(CPP_ITERATION_CONTEXT_HPP_00312288_9DDB_4668_AFE5_25D3994FD095_INCLUDED) #define CPP_ITERATION_CONTEXT_HPP_00312288_9DDB_4668_AFE5_25D3994FD095_INCLUDED #include <iterator> #include <fstream> #if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS) #include <sstream> #endif #include <boost/wave/wave_config.hpp> #include <boost/wave/cpp_exceptions.hpp> #include <boost/wave/language_support.hpp> #include <boost/wave/util/file_position.hpp> // #include <boost/spirit/include/iterator/classic_multi_pass.hpp> // make_multi_pass // this must occur after all of the includes and before any code appears #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { namespace iteration_context_policies { /////////////////////////////////////////////////////////////////////////////// // // The iteration_context_policies templates are policies for the // boost::wave::iteration_context which allows to control, how a given // input file is to be represented by a pair of iterators pointing to the // begin and the end of the resulting input sequence. // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // // load_file_to_string // // Loads a file into a string and returns the iterators pointing to // the beginning and the end of the loaded string. // /////////////////////////////////////////////////////////////////////////// struct load_file_to_string { template <typename IterContextT> class inner { public: template <typename PositionT> static void init_iterators(IterContextT &iter_ctx, PositionT const &act_pos, language_support language) { typedef typename IterContextT::iterator_type iterator_type; // read in the file std::ifstream instream(iter_ctx.filename.c_str()); if (!instream.is_open()) { BOOST_WAVE_THROW_CTX(iter_ctx.ctx, preprocess_exception, bad_include_file, iter_ctx.filename.c_str(), act_pos); return; } instream.unsetf(std::ios::skipws); iter_ctx.instring.assign( std::istreambuf_iterator<char>(instream.rdbuf()), std::istreambuf_iterator<char>()); iter_ctx.first = iterator_type( iter_ctx.instring.begin(), iter_ctx.instring.end(), PositionT(iter_ctx.filename), language); iter_ctx.last = iterator_type(); } private: std::string instring; }; }; } // namespace iteration_context_policies /////////////////////////////////////////////////////////////////////////////// // Base class for iteration contexts template <typename ContextT, typename IteratorT> struct base_iteration_context { enum file_type { // this iteration context handles ... main_file, // ... the main preprocessed file system_header, // ... a header file included used #include <> user_header // ... a header file included using #include "" }; base_iteration_context(ContextT& ctx_, BOOST_WAVE_STRINGTYPE const &fname, std::size_t if_block_depth = 0) : real_filename(fname), real_relative_filename(fname), filename(fname), line(1), emitted_lines(0), if_block_depth(if_block_depth), ctx(ctx_), type(main_file) {} base_iteration_context(ContextT& ctx_, IteratorT const &first_, IteratorT const &last_, BOOST_WAVE_STRINGTYPE const &fname, std::size_t if_block_depth = 0, file_type type_ = main_file) : first(first_), last(last_), real_filename(fname), real_relative_filename(fname), filename(fname), line(1), emitted_lines(0), if_block_depth(if_block_depth), ctx(ctx_), type(type_) {} // the actual input stream IteratorT first; // actual input stream position IteratorT last; // end of input stream BOOST_WAVE_STRINGTYPE real_filename; // real name of the current file BOOST_WAVE_STRINGTYPE real_relative_filename; // real relative name of the current file BOOST_WAVE_STRINGTYPE filename; // actual processed file std::size_t line; // line counter of underlying stream std::size_t emitted_lines; // count of emitted newlines std::size_t if_block_depth; // depth of #if block recursion ContextT& ctx; // corresponding context<> object file_type type; // the type of the handled file }; /////////////////////////////////////////////////////////////////////////////// // template < typename ContextT, typename IteratorT, typename InputPolicyT = typename ContextT::input_policy_type > struct iteration_context : public base_iteration_context<ContextT, IteratorT>, public InputPolicyT::template inner<iteration_context<ContextT, IteratorT, InputPolicyT> > { typedef IteratorT iterator_type; typedef typename IteratorT::token_type::position_type position_type; typedef base_iteration_context<ContextT, IteratorT> base_type; typedef iteration_context<ContextT, IteratorT, InputPolicyT> self_type; iteration_context(ContextT& ctx, BOOST_WAVE_STRINGTYPE const &fname, position_type const &act_pos, boost::wave::language_support language_, typename base_type::file_type type = base_type::main_file) : base_iteration_context<ContextT, IteratorT>(ctx, fname, type) { InputPolicyT::template inner<self_type>::init_iterators( *this, act_pos, language_); } }; /////////////////////////////////////////////////////////////////////////////// } // namespace wave } // namespace boost // the suffix header occurs after all of the code #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // !defined(CPP_ITERATION_CONTEXT_HPP_00312288_9DDB_4668_AFE5_25D3994FD095_INCLUDED)
{ "pile_set_name": "Github" }
You may be able to register a civil partnership or get married at the British embassy or consulate in Albania. [Make an appointment at the embassy in Tirana.](https://www.consular-appointments.service.gov.uk/fco/#!/british-embassy-tirana/notice-of-marriage-or-civil-partnership/slot_picker) ##What documents you’ll need You need to have been living in Albania for 21 days. You and your partner will need to sign a declaration and provide proof of residence for example, an employer’s letter or a bank statement. You’ll both need to bring your original passports. You’ll also need evidence that your partner is free to marry - a document from their government or their passport that says they are unmarried. If either of you have been divorced, widowed or in a civil partnership before, you’ll also need to provide: - a [decree absolute or final order](/copy-decree-absolute-final-order) - the [death certificate](/order-copy-birth-death-marriage-certificate/) ##What you need to do At your appointment the embassy or consulate will give you: - a notice of registration - a declaration that you and your partner will need to swear, stating that you’re legally entitled to marry or enter into a civil partnership Once you’ve completed these and paid the registration fee, the embassy or consulate will display your notice publicly for 14 days. As long as nobody registers an objection you can get married or enter into a civil partnership up to 3 months after you gave notice. You’ll need to bring two witnesses to your ceremony - they’ll need to show their photo ID (for example passport or driver’s licence). You’ll need to pay a fee to register your marriage or civil partnership and a fee for your marriage or civil partnership certificate. ^All same-sex marriages must take place under English and Welsh or Scottish law even if you live in or are from Northern Ireland. Tell the embassy or consulate which law you want to get married under at your appointment.^ ##Naturalisation of your partner if they move to the UK Your partner can apply to [become a British citizen](/becoming-a-british-citizen/if-your-spouse-is-a-british-citizen) once they’ve lived in the UK for 3 years. ## Fees <%= render partial: 'consular_fees_table_items', collection: calculator.services, as: :service, locals: { calculator: calculator } %> You normally have to pay fees for consular services in the local currency - these are shown in the list of [consular fees for Albania](/government/publications/albania-consular-fees). <%= render partial: 'how_to_pay', locals: {calculator: calculator} %> ##Convert a civil partnership to a same-sex marriage If you’ve already entered into a civil partnership you may be able to convert it to a same-sex marriage - read [‘Convert a civil partnership to a same-sex marriage abroad’](/convert-civil-partnership-abroad).
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. 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. */ package workqueue import ( "sync" "time" ) // This file provides abstractions for setting the provider (e.g., prometheus) // of metrics. type queueMetrics interface { add(item t) get(item t) done(item t) } // GaugeMetric represents a single numerical value that can arbitrarily go up // and down. type GaugeMetric interface { Inc() Dec() } // CounterMetric represents a single numerical value that only ever // goes up. type CounterMetric interface { Inc() } // SummaryMetric captures individual observations. type SummaryMetric interface { Observe(float64) } type noopMetric struct{} func (noopMetric) Inc() {} func (noopMetric) Dec() {} func (noopMetric) Observe(float64) {} type defaultQueueMetrics struct { // current depth of a workqueue depth GaugeMetric // total number of adds handled by a workqueue adds CounterMetric // how long an item stays in a workqueue latency SummaryMetric // how long processing an item from a workqueue takes workDuration SummaryMetric addTimes map[t]time.Time processingStartTimes map[t]time.Time } func (m *defaultQueueMetrics) add(item t) { if m == nil { return } m.adds.Inc() m.depth.Inc() if _, exists := m.addTimes[item]; !exists { m.addTimes[item] = time.Now() } } func (m *defaultQueueMetrics) get(item t) { if m == nil { return } m.depth.Dec() m.processingStartTimes[item] = time.Now() if startTime, exists := m.addTimes[item]; exists { m.latency.Observe(sinceInMicroseconds(startTime)) delete(m.addTimes, item) } } func (m *defaultQueueMetrics) done(item t) { if m == nil { return } if startTime, exists := m.processingStartTimes[item]; exists { m.workDuration.Observe(sinceInMicroseconds(startTime)) delete(m.processingStartTimes, item) } } // Gets the time since the specified start in microseconds. func sinceInMicroseconds(start time.Time) float64 { return float64(time.Since(start).Nanoseconds() / time.Microsecond.Nanoseconds()) } type retryMetrics interface { retry() } type defaultRetryMetrics struct { retries CounterMetric } func (m *defaultRetryMetrics) retry() { if m == nil { return } m.retries.Inc() } // MetricsProvider generates various metrics used by the queue. type MetricsProvider interface { NewDepthMetric(name string) GaugeMetric NewAddsMetric(name string) CounterMetric NewLatencyMetric(name string) SummaryMetric NewWorkDurationMetric(name string) SummaryMetric NewRetriesMetric(name string) CounterMetric } type noopMetricsProvider struct{} func (_ noopMetricsProvider) NewDepthMetric(name string) GaugeMetric { return noopMetric{} } func (_ noopMetricsProvider) NewAddsMetric(name string) CounterMetric { return noopMetric{} } func (_ noopMetricsProvider) NewLatencyMetric(name string) SummaryMetric { return noopMetric{} } func (_ noopMetricsProvider) NewWorkDurationMetric(name string) SummaryMetric { return noopMetric{} } func (_ noopMetricsProvider) NewRetriesMetric(name string) CounterMetric { return noopMetric{} } var metricsFactory = struct { metricsProvider MetricsProvider setProviders sync.Once }{ metricsProvider: noopMetricsProvider{}, } func newQueueMetrics(name string) queueMetrics { var ret *defaultQueueMetrics if len(name) == 0 { return ret } return &defaultQueueMetrics{ depth: metricsFactory.metricsProvider.NewDepthMetric(name), adds: metricsFactory.metricsProvider.NewAddsMetric(name), latency: metricsFactory.metricsProvider.NewLatencyMetric(name), workDuration: metricsFactory.metricsProvider.NewWorkDurationMetric(name), addTimes: map[t]time.Time{}, processingStartTimes: map[t]time.Time{}, } } func newRetryMetrics(name string) retryMetrics { var ret *defaultRetryMetrics if len(name) == 0 { return ret } return &defaultRetryMetrics{ retries: metricsFactory.metricsProvider.NewRetriesMetric(name), } } // SetProvider sets the metrics provider of the metricsFactory. func SetProvider(metricsProvider MetricsProvider) { metricsFactory.setProviders.Do(func() { metricsFactory.metricsProvider = metricsProvider }) }
{ "pile_set_name": "Github" }
#ifndef LAYER_H #define LAYER_H #include<iostream> #include<vector> #include "utils.h" #include "Network.h" namespace tk { namespace dnn { enum layerType_t { LAYER_INPUT, LAYER_DENSE, LAYER_CONV2D, LAYER_DECONV2D, LAYER_DEFORMCONV2D, LAYER_LSTM, LAYER_ACTIVATION, LAYER_ACTIVATION_CRELU, LAYER_ACTIVATION_LEAKY, LAYER_ACTIVATION_MISH, LAYER_FLATTEN, LAYER_RESHAPE, LAYER_MULADD, LAYER_POOLING, LAYER_SOFTMAX, LAYER_ROUTE, LAYER_REORG, LAYER_SHORTCUT, LAYER_UPSAMPLE, LAYER_REGION, LAYER_YOLO }; #define TKDNN_BN_MIN_EPSILON 1e-5 /** Simple layer Father class */ class Layer { public: Layer(Network *net); virtual ~Layer(); virtual layerType_t getLayerType() = 0; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData) { std::cout<<"No infer action for this layer\n"; return NULL; } void setFinal() { this->final = true; } dataDim_t input_dim, output_dim; dnnType *dstData = nullptr; //where results will be putted int id = 0; bool final; //if the layer is the final one std::string getLayerName() { layerType_t type = getLayerType(); switch(type) { case LAYER_INPUT: return "Input"; case LAYER_DENSE: return "Dense"; case LAYER_CONV2D: return "Conv2d"; case LAYER_DECONV2D: return "DeConv2d"; case LAYER_DEFORMCONV2D: return "DeformConv2d"; case LAYER_LSTM: return "LSTM"; case LAYER_ACTIVATION: return "Activation"; case LAYER_ACTIVATION_CRELU: return "ActivationCReLU"; case LAYER_ACTIVATION_LEAKY: return "ActivationLeaky"; case LAYER_ACTIVATION_MISH: return "ActivationMish"; case LAYER_FLATTEN: return "Flatten"; case LAYER_RESHAPE: return "Reshape"; case LAYER_MULADD: return "MulAdd"; case LAYER_POOLING: return "Pooling"; case LAYER_SOFTMAX: return "Softmax"; case LAYER_ROUTE: return "Route"; case LAYER_REORG: return "Reorg"; case LAYER_SHORTCUT: return "Shortcut"; case LAYER_UPSAMPLE: return "Upsample"; case LAYER_REGION: return "Region"; case LAYER_YOLO: return "Yolo"; default: return "unknown"; } } protected: Network *net; cudnnTensorDescriptor_t srcTensorDesc, dstTensorDesc; }; /** Father class of all layer that need to load trained weights */ class LayerWgs : public Layer { public: LayerWgs(Network *net, int inputs, int outputs, int kh, int kw, int kt, std::string fname_weights, bool batchnorm = false, bool additional_bias = false, bool deConv = false, int groups = 1); virtual ~LayerWgs(); int inputs, outputs; std::string weights_path; dnnType *data_h, *data_d; dnnType *bias_h, *bias_d; // additional bias for DCN bool additional_bias; dnnType *bias2_h = nullptr, *bias2_d = nullptr; //batchnorm bool batchnorm; dnnType *power_h = nullptr; dnnType *scales_h = nullptr, *scales_d = nullptr; dnnType *mean_h = nullptr, *mean_d = nullptr; dnnType *variance_h = nullptr, *variance_d = nullptr; //fp16 __half *data16_h = nullptr, *bias16_h = nullptr; __half *data16_d = nullptr, *bias16_d = nullptr; __half *bias216_h = nullptr, *bias216_d = nullptr; __half *power16_h = nullptr, *power16_d = nullptr; __half *scales16_h = nullptr, *scales16_d = nullptr; __half *mean16_h = nullptr, *mean16_d = nullptr; __half *variance16_h = nullptr, *variance16_d = nullptr; void releaseHost(bool release32 = true, bool release16 = true) { if(release32) { if( data_h != nullptr) { delete [] data_h; data_h = nullptr; } if( bias_h != nullptr) { delete [] bias_h; bias_h = nullptr; } if( bias2_h != nullptr) { delete [] bias2_h; bias2_h = nullptr; } if( scales_h != nullptr) { delete [] scales_h; scales_h = nullptr; } if( mean_h != nullptr) { delete [] mean_h; mean_h = nullptr; } if(variance_h != nullptr) { delete [] variance_h; variance_h = nullptr; } if( power_h != nullptr) { delete [] power_h; power_h = nullptr; } } if(net->fp16 && release16) { if( data16_h != nullptr) { delete [] data16_h; data16_h = nullptr; } if( bias16_h != nullptr) { delete [] bias16_h; bias16_h = nullptr; } if( bias216_h != nullptr) { delete [] bias216_h; bias216_h = nullptr; } if( scales16_h != nullptr) { delete [] scales16_h; scales16_h = nullptr; } if( mean16_h != nullptr) { delete [] mean16_h; mean16_h = nullptr; } if(variance16_h != nullptr) { delete [] variance16_h; variance16_h = nullptr; } if( power16_h != nullptr) { delete [] power16_h; power16_h = nullptr; } } } void releaseDevice(bool release32 = true, bool release16 = true) { if(release32) { if( data_d != nullptr) { cudaFree( data_d); data_d = nullptr; } if( bias_d != nullptr) { cudaFree( bias_d); bias_d = nullptr; } if( bias2_d != nullptr) { cudaFree( bias2_d); bias2_d = nullptr; } if( scales_d != nullptr) { cudaFree( scales_d); scales_d = nullptr; } if( mean_d != nullptr) { cudaFree( mean_d); mean_d = nullptr; } if(variance_d != nullptr) { cudaFree(variance_d); variance_d = nullptr; } } if(net->fp16 && release16) { if( data16_d != nullptr) { cudaFree( data16_d); data16_d = nullptr; } if( bias16_d != nullptr) { cudaFree( bias16_d); bias16_d = nullptr; } if( bias216_d != nullptr) { cudaFree( bias216_d); bias216_d = nullptr; } if( scales16_d != nullptr) { cudaFree( scales16_d); scales16_d = nullptr; } if( mean16_d != nullptr) { cudaFree( mean16_d); mean16_d = nullptr; } if(variance16_d != nullptr) { cudaFree(variance16_d); variance16_d = nullptr; } if( power16_d != nullptr) { cudaFree( power16_d); power16_d = nullptr; } } } }; /** Input layer (it doesn't need weights) */ class Input : public Layer { public: Input(Network *net, dataDim_t &dim, dnnType* srcData) : Layer(net) { input_dim = dim; output_dim = dim; dstData = srcData; } virtual ~Input() {} virtual layerType_t getLayerType() { return LAYER_INPUT; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData) { dim = output_dim; return dstData; } }; /** Dense (full interconnection) layer */ class Dense : public LayerWgs { public: Dense(Network *net, int out_ch, std::string fname_weights); virtual ~Dense(); virtual layerType_t getLayerType() { return LAYER_DENSE; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); }; /** Available activation functions */ typedef enum { ACTIVATION_ELU = 100, ACTIVATION_LEAKY = 101, ACTIVATION_MISH = 102 } tkdnnActivationMode_t; /** Activation layer (it doesn't need weights) */ class Activation : public Layer { public: int act_mode; float ceiling; Activation(Network *net, int act_mode, const float ceiling=0.0); virtual ~Activation(); virtual layerType_t getLayerType() { if(act_mode == CUDNN_ACTIVATION_CLIPPED_RELU) return LAYER_ACTIVATION_CRELU; else if (act_mode == ACTIVATION_LEAKY) return LAYER_ACTIVATION_LEAKY; else if (act_mode == ACTIVATION_MISH) return LAYER_ACTIVATION_MISH; else return LAYER_ACTIVATION; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); protected: cudnnActivationDescriptor_t activDesc; }; /** Convolutional 2D layer WEIGHTS shape: OUTCH, INCH, KH, KW ... BIAS shape: OUTCH with BATCHNORM: scales: OUTCH means: OUTCH variance: OUTCH */ class Conv2d : public LayerWgs { public: Conv2d( Network *net, int out_ch, int kernelH, int kernelW, int strideH, int strideW, int paddingH, int paddingW, std::string fname_weights, bool batchnorm = false, bool deConv = false, int groups = 1, bool additional_bias=false); virtual ~Conv2d(); virtual layerType_t getLayerType() { return LAYER_CONV2D; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); int kernelH, kernelW, strideH, strideW, paddingH, paddingW; bool deConv, additional_bias; int groups; protected: cudnnFilterDescriptor_t filterDesc; cudnnConvolutionDescriptor_t convDesc; cudnnConvolutionFwdAlgoPerf_t algo; cudnnConvolutionBwdDataAlgoPerf_t bwAlgo; cudnnTensorDescriptor_t biasTensorDesc; void initCUDNN(bool back = false); void inferCUDNN(dnnType* srcData, bool back = false); void* workSpace; size_t ws_sizeInBytes; }; /** Bidirectional LSTM layer ONLY BIDIRECTIONAL (TODO: more configurable) currently implemented as 2 inferences: forward and backward (TODO: only 1 cudnn inference) implementation info: https://github.com/jiangnanhugo/seq2seq_cuda/blob/e4dbdcfa0517c972bfd4beea9f11a5233954093c/src/rnn.cpp https://github.com/Jeffery-Song/mxnet-test/blob/aab666faad44011f7a67b527b5f6c960367d0422/src/operator/cudnn_rnn-inl.h https://stackoverflow.com/a/38737941 https://colah.github.io/posts/2015-08-Understanding-LSTMs/ PARAMS (numlayers*2): layer0: ( INCH, ? ) ??? ( HIDDEN, ? ) ??? ( HIDDEN * 8 ) ??? layer2: ( INCH, ? ) ??? ( HIDDEN, ? ) ??? ( HIDDEN * 8 ) ??? OUTPUT shape: (N, C, 1, W) ---> LSTM(HIDDEN, returnSeq=True) ---> (N, 2*HIDDEN, 1, W) # W is seqLength (N, C, 1, W) ---> LSTM(HIDDEN, returnSeq=False) ---> (N, 2*HIDDEN, 1, 1) */ class LSTM : public Layer { public: LSTM(Network *net, int hiddensize, bool returnSeq, std::string fname_weights); virtual ~LSTM(); virtual layerType_t getLayerType() { return LAYER_LSTM; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); const bool bidirectional = true; /**> is the net bidir */ bool returnSeq = false; /**> if false return only the result of last timestamp */ int stateSize = 0; /**> number of hidden states */ int seqLen = 0; /**> number of timestamp */ int numLayers = 1; /**> number of internal layers */ protected: cudnnRNNDescriptor_t rnnDesc; cudnnDropoutDescriptor_t dropoutDesc; dnnType *dropout_states_, *work_space_; size_t workspace_byte_, dropout_byte_; int workspace_size_, dropout_size_; std::vector<cudnnTensorDescriptor_t> x_desc_vec_, y_desc_vec_; cudnnTensorDescriptor_t hx_desc_, cx_desc_; cudnnTensorDescriptor_t hy_desc_, cy_desc_; dnnType *hx_ptr, *cx_ptr, *hy_ptr, *cy_ptr; int stateDataDim; cudnnFilterDescriptor_t w_desc_; dnnType *w_ptr; dnnType *w_h; dnnType *wf_ptr, *wb_ptr; // params pointer forward and backward layer // used during inference dataDim_t one_output_dim; // output dim of as single inference dnnType *srcF, *srcB; // input of single inference dnnType *dstF, *dstB_NR, *dstB; // output of single inference, dstB_NR = dstB not reversed }; /** Convolutional 2D layer */ class DeConv2d : public Conv2d { public: DeConv2d( Network *net, int out_ch, int kernelH, int kernelW, int strideH, int strideW, int paddingH, int paddingW, std::string fname_weights, bool batchnorm = false, int groups = 1) : Conv2d(net, out_ch, kernelH, kernelW, strideH, strideW, paddingH, paddingW, fname_weights, batchnorm, true, groups) {} virtual ~DeConv2d() {} virtual layerType_t getLayerType() { return LAYER_DECONV2D; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); }; /** Deformable Convolutional 2d layer */ class DeformConv2d : public LayerWgs { public: DeformConv2d( Network *net, int out_ch, int deformable_group, int kernelH, int kernelW, int strideH, int strideW, int paddingH, int paddingW, std::string d_fname_weights, std::string fname_weights, bool batchnorm); virtual ~DeformConv2d(); virtual layerType_t getLayerType() { return LAYER_DEFORMCONV2D; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); tk::dnn::Conv2d *preconv; int out_ch; int deformableGroup; int kernelH, kernelW, strideH, strideW, paddingH, paddingW; dnnType *ones_d1; dnnType *ones_d2; int chunk_dim; dnnType *offset, *mask; dnnType *output_conv; cublasStatus_t stat; cublasHandle_t handle; protected: cudnnTensorDescriptor_t biasTensorDesc; void initCUDNN(); }; /** Flatten layer is actually a matrix transposition */ class Flatten : public Layer { public: Flatten(Network *net); virtual ~Flatten(); virtual layerType_t getLayerType() { return LAYER_FLATTEN; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); }; /** Reshape layer */ class Reshape : public Layer { public: Reshape(Network *net, dataDim_t new_dim); virtual ~Reshape(); virtual layerType_t getLayerType() { return LAYER_RESHAPE; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); }; /** MulAdd layer apply a multiplication and then an addition for each data */ class MulAdd : public Layer { public: MulAdd(Network *net, dnnType mul, dnnType add); virtual ~MulAdd(); virtual layerType_t getLayerType() { return LAYER_MULADD; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); protected: dnnType mul, add; dnnType *add_vector; }; /** Available pooling functions (padding on tkDNN is not supported) */ typedef enum { POOLING_MAX = 0, POOLING_AVERAGE = 1, // count for average includes padded values POOLING_AVERAGE_EXCLUDE_PADDING = 2, // count for average does not include padded values POOLING_MAX_FIXEDSIZE = 100 // max pool darknet fashion } tkdnnPoolingMode_t; /** Pooling layer currently supported only 2d pooing (also on 3d input) */ class Pooling : public Layer { public: int winH, winW; int strideH, strideW; int paddingH, paddingW; bool size; tkdnnPoolingMode_t pool_mode; Pooling(Network *net, int winH, int winW, int strideH, int strideW, int paddingH, int paddingW, tkdnnPoolingMode_t pool_mode); virtual ~Pooling(); virtual layerType_t getLayerType() { return LAYER_POOLING; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); protected: cudnnPoolingDescriptor_t poolingDesc; dnnType *tmpInputData, *tmpOutputData; bool poolOn3d; }; /** Softmax layer */ class Softmax : public Layer { public: Softmax(Network *net, const tk::dnn::dataDim_t* dim=nullptr, const cudnnSoftmaxMode_t mode=CUDNN_SOFTMAX_MODE_CHANNEL); virtual ~Softmax(); virtual layerType_t getLayerType() { return LAYER_SOFTMAX; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); dataDim_t dim; cudnnSoftmaxMode_t mode; }; /** Route layer Merge a list of layers */ class Route : public Layer { public: Route(Network *net, Layer **layers, int layers_n, int groups = 1, int group_id = 0); virtual ~Route(); virtual layerType_t getLayerType() { return LAYER_ROUTE; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); public: static const int MAX_LAYERS = 32; Layer *layers[MAX_LAYERS]; //ids of layers to be merged int layers_n; //number of layers int groups; int group_id; }; /** Reorg layer Maintains same dimension but change C*H*W distribution */ class Reorg : public Layer { public: Reorg(Network *net, int stride); virtual ~Reorg(); virtual layerType_t getLayerType() { return LAYER_REORG; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); int stride; }; /** Shortcut layer sum with stride another layer */ class Shortcut : public Layer { public: Shortcut(Network *net, Layer *backLayer); virtual ~Shortcut(); virtual layerType_t getLayerType() { return LAYER_SHORTCUT; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); public: Layer *backLayer; }; /** Upsample layer Maintains same dimension but change C*H*W distribution */ class Upsample : public Layer { public: Upsample(Network *net, int stride); virtual ~Upsample(); virtual layerType_t getLayerType() { return LAYER_UPSAMPLE; }; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); int stride; bool reverse; }; struct box { int cl; float x, y, w, h; float prob; std::vector<float> probs; void print() { std::cout<<"x: "<<x<<"\ty: "<<y<<"\tw: "<<w<<"\th: "<<h<<"\tcl: "<<cl<<"\tprob: "<<prob<<std::endl; } }; struct sortable_bbox { int index; int cl; float **probs; }; /** Yolo3 layer */ class Yolo : public Layer { public: struct box { float x, y, w, h; }; struct detection{ Yolo::box bbox; int classes; float *prob; float *mask; float objectness; int sort_class; }; Yolo(Network *net, int classes, int num, std::string fname_weights,int n_masks=3, float scale_xy=1); virtual ~Yolo(); virtual layerType_t getLayerType() { return LAYER_YOLO; }; int classes, num, n_masks; dnnType *mask_h, *mask_d; //anchors dnnType *bias_h, *bias_d; //anchors float scaleXY; std::vector<std::string> classesNames; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); int computeDetections(Yolo::detection *dets, int &ndets, int netw, int neth, float thresh); dnnType *predictions; static const int MAX_DETECTIONS = 8192; static Yolo::detection *allocateDetections(int nboxes, int classes); static void mergeDetections(Yolo::detection *dets, int ndets, int classes); }; /** Region layer */ class Region : public Layer { public: Region(Network *net, int classes, int coords, int num); virtual ~Region(); virtual layerType_t getLayerType() { return LAYER_REGION; }; int classes, coords, num; virtual dnnType* infer(dataDim_t &dim, dnnType* srcData); }; class RegionInterpret { public: RegionInterpret(dataDim_t input_dim, dataDim_t output_dim, int classes, int coords, int num, float thresh, std::string fname_weights); ~RegionInterpret(); dataDim_t input_dim, output_dim; dnnType *bias_h, *bias_d; //anchors int classes, coords, num; float thresh; box *boxes; float **probs; sortable_bbox *s; box res_boxes[256]; int res_boxes_n; box get_region_box(float *x, float *biases, int n, int index, int i, int j, int w, int h, int stride); void get_region_boxes( float *input, int w, int h, int netw, int neth, float thresh, float **probs, box *boxes, int only_objectness, int *map, float tree_thresh, int relative); void correct_region_boxes(box *boxes, int n, int w, int h, int netw, int neth, int relative); void interpretData(dnnType *data_h, int imageW = 0, int imageH = 0); void showImageResult(dnnType *input_h); static float box_iou(box a, box b); }; }} #endif //LAYER_H
{ "pile_set_name": "Github" }
package hex.pca; import hex.DataInfo; import hex.pca.PCAModel.PCAParameters; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import water.DKV; import water.Key; import water.Scope; import water.TestUtil; import water.fvec.Frame; import water.util.Log; import java.util.Random; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertTrue; import static org.junit.runners.Parameterized.Parameter; import static org.junit.runners.Parameterized.Parameters; import static water.TestUtil.parse_test_file; /** * Created by wendycwong on 2/27/17. */ @RunWith(Parameterized.class) public class PCAWideDataSetsTests extends TestUtil { public static final double _TOLERANCE = 1e-6; public static String _smallDataset = "smalldata/pca_test/decathlon.csv"; public static final String _prostateDataset = "smalldata/prostate/prostate_cat.csv"; public static final DataInfo.TransformType[] _transformTypes = {DataInfo.TransformType.NONE, DataInfo.TransformType.STANDARDIZE, DataInfo.TransformType.DEMEAN, DataInfo.TransformType.DESCALE}; public Random _rand = new Random(); public PCAModel _golden = null; // private PCAParameters pcaParameters; @Parameters public static PCAImplementation[] parametersForSvdImplementation() { return hex.pca.PCAImplementation.values(); } @Parameter public PCAImplementation PCAImplementation; @BeforeClass public static void setup() { stall_till_cloudsize(1); } @Before public void setupPcaParameters() { pcaParameters = new PCAParameters(); pcaParameters._pca_implementation = PCAImplementation; water.util.Log.info("pcaParameters._PCAImplementation: " + pcaParameters._pca_implementation.name()); } /* This unit test will test that pca method GramSVD works with wide datasets. It will first build a model using GramSVD under normal setting (_wideDataset is set to false). Next, it builds a GramSVD model with _wideDataSet set to true. The eigenvalues and eigenvectors from the two models are compared. Test will fail if any difference exceeds 1e-6. Six test cases are used: case 1. we test with a small dataset with all numerical data columns and make sure it works. case 2. we add NA rows to the small dataset with all numerical data columns. case 3. test with the same small dataset while preserving the categorical columns; case 4. test with the same small dataset with categorical columns and add NA rows; case 5. test with prostate dataset; case 6. test with prostate dataset with NA rows added. */ @Test public void testWideDataSetGramSVD() throws InterruptedException, ExecutionException { ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GramSVD, _TOLERANCE, _smallDataset, false, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 1 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GramSVD, _TOLERANCE, _smallDataset, true, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 2 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GramSVD, _TOLERANCE, _smallDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 3 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GramSVD, _TOLERANCE, _smallDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 4 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GramSVD, _TOLERANCE, _prostateDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 5 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GramSVD, _TOLERANCE, _prostateDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 6 } /* This unit test will test that pca method Power works with wide datasets. It will first build a model using GramSVD under normal setting (_wideDataset is set to false). Next, it builds a Power model with _wideDataSet set to true. The eigenvalues and eigenvectors from the two models are compared. Test will fail if any difference exceeds 1e-6. The same six test cases are used here. */ @Test public void testWideDataSetPower() throws InterruptedException, ExecutionException { ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Power, _TOLERANCE, _smallDataset, false, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 1 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Power, _TOLERANCE, _smallDataset, true, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 2 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Power, _TOLERANCE, _smallDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 3 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Power, _TOLERANCE, _smallDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 4 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Power, _TOLERANCE, _prostateDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 5 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Power, _TOLERANCE, _prostateDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 6 } /* This unit test will test that pca method Randomized works with wide datasets. It will first build a model using GramSVD under normal setting (_wideDataset is set to false). Next, it builds a Randomized model with _wideDataSet set to true. The eigenvalues and eigenvectors from the two models are compared. Test will fail if any difference exceeds 1e-6. The same six test cases are used here. */ @Test public void testWideDataSetRandomized() throws InterruptedException, ExecutionException { ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Randomized, _TOLERANCE, _smallDataset, false, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 1 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Randomized, _TOLERANCE, _smallDataset, true, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 2 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Randomized, _TOLERANCE, _smallDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 3 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Randomized, _TOLERANCE, _smallDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 4 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Randomized, _TOLERANCE, _prostateDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 5 ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.Randomized, _TOLERANCE, _prostateDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 6 } /* This unit test will test that pca method GLRM works with wide datasets. It will first build a model using GramSVD under normal setting (_wideDataset is set to false). Next, it builds a GLRM model with _wideDataSet set to true. The eigenvalues and eigenvectors from the two models are compared. Test will fail if any difference exceeds 1e-6 only for numerical dataset. For categorical datasets, GLRM will not generate the same set of eigenvalues/vectors. Hence for datasets with Enum columns, we will compare the two models built with normal and widedataset GLRM. */ @Test public void testWideDataSetGLRM() throws InterruptedException, ExecutionException { ActualPCATests.testWideDataSets(PCAParameters.Method.GramSVD, PCAParameters.Method.GLRM, 0.0001, _smallDataset, false, true, _transformTypes[1], (PCAParameters) pcaParameters.clone()); // case 1 numerical ActualPCATests.testWideDataSets(PCAParameters.Method.GLRM, PCAParameters.Method.GLRM,_TOLERANCE, _smallDataset, true, true, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 2 ActualPCATests.testWideDataSets(PCAParameters.Method.GLRM, PCAParameters.Method.GLRM,_TOLERANCE, _smallDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 3 ActualPCATests.testWideDataSets(PCAParameters.Method.GLRM, PCAParameters.Method.GLRM,_TOLERANCE, _smallDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 4 ActualPCATests.testWideDataSets(PCAParameters.Method.GLRM, PCAParameters.Method.GLRM, _TOLERANCE, _prostateDataset, false, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 5 ActualPCATests.testWideDataSets(PCAParameters.Method.GLRM, PCAParameters.Method.GLRM, _TOLERANCE, _prostateDataset, true, false, _transformTypes[_rand.nextInt(_transformTypes.length)], (PCAParameters) pcaParameters.clone()); // case 6 } } /* This class performs the actual PCA tests. */ class ActualPCATests { public static void testWideDataSets(PCAParameters.Method pcaMethod, PCAParameters.Method pcaMethod2, double tolerance, String datafile, boolean addNAs, boolean removeColumns, DataInfo.TransformType transformType, PCAParameters pcaParameters) throws InterruptedException, ExecutionException { Scope.enter(); PCAModel modelN = null; // store PCA models generated with original implementation PCAModel modelW = null; // store PCA models generated with wideDataSet set to true Frame train = null, scoreN = null, scoreW = null; try { train = parse_test_file(Key.make(datafile), datafile); Scope.track(train); if (removeColumns) { train.remove(12).remove(); // remove categorical columns train.remove(11).remove(); train.remove(10).remove(); } if (addNAs) { train.vec(0).setNA(0); // set NAs train.vec(3).setNA(10); train.vec(5).setNA(20); } DKV.put(train); pcaParameters._train = train._key; pcaParameters._k = 3; pcaParameters._transform = transformType; Log.info("Data transformation applied is "+pcaParameters._transform.name()); pcaParameters._use_all_factor_levels = true; pcaParameters._pca_method = pcaMethod; pcaParameters._impute_missing = false; pcaParameters._seed = 12345; PCAParameters pcaParameters2 = (PCAParameters) pcaParameters.clone(); PCA pcaParms = new PCA(pcaParameters); modelN = pcaParms.trainModel().get(); // get normal data scoreN = modelN.score(train); Scope.track(scoreN); Scope.track_generic(modelN); pcaParameters2._pca_method = pcaMethod2; PCA pcaParmsW = new PCA(pcaParameters2); pcaParmsW.setWideDataset(true); // force to treat dataset as wide even though it is not. modelW = pcaParmsW.trainModel().get(); scoreW = modelW.score(train); Scope.track(scoreW); Scope.track_generic(modelW); // compare eigenvectors and eigenvalues generated by original PCA and wide dataset PCA. TestUtil.checkStddev(modelW._output._std_deviation, modelN._output._std_deviation, tolerance); boolean[] flippedEig = TestUtil.checkEigvec(modelW._output._eigenvectors, modelN._output._eigenvectors, tolerance); TestUtil.checkProjection(scoreW, scoreN, tolerance, flippedEig); if (!(pcaMethod == PCAParameters.Method.GLRM)) { // GLRM only works with numerical columns well // Build a POJO, check results with original PCA assertTrue(modelN.testJavaScoring(train, scoreN, tolerance)); // Build a POJO, check results with wide dataset PCA assertTrue(modelW.testJavaScoring(train, scoreW, tolerance)); } } finally { Scope.exit(); } } }
{ "pile_set_name": "Github" }
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd netbsd package socket func (h *msghdr) setIov(vs []iovec) { h.Iov = &vs[0] h.Iovlen = int32(len(vs)) }
{ "pile_set_name": "Github" }
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given as first name, von and last name.</li> * <li>First names will be abbreviated.</li> * <li>Individual authors separated by comma.</li> * <li>There is no command in front the and of a list of three or more authors.</li> * </ul> */ public class AuthorFirstAbbrLastCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, true, false); } }
{ "pile_set_name": "Github" }
/* * 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. */ package org.ops4j.pax.web.jettyconftest; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class UploadCheckServlet */ @WebServlet(name = "helloWorld", urlPatterns = {"/upload-check"}) public class UploadCheckServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("POST data size is: " + request.getParameter("data").length()); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <metadata name="TTip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>123, 3</value> </metadata> <metadata name="tShowStats.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>14, 2</value> </metadata> <metadata name="tCheckOL.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>196, 3</value> </metadata> <metadata name="tZergRush.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>295, 3</value> </metadata> <metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>25</value> </metadata> </root>
{ "pile_set_name": "Github" }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you 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. * */ package org.unitime.timetable.model.dao; import org.unitime.timetable.model.base.BaseStudentAreaClassificationMajorDAO; public class StudentAreaClassificationMajorDAO extends BaseStudentAreaClassificationMajorDAO { public StudentAreaClassificationMajorDAO() {} }
{ "pile_set_name": "Github" }
#pragma checksum "..\..\Busy.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "F887AB7178E218BEAFC9F54749050A3F" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using NMT.Wpf.Controls; using PS4_PSP_Classics_GUI; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace PS4_PSP_Classics_GUI { /// <summary> /// Busy /// </summary> public partial class Busy : System.Windows.Window, System.Windows.Markup.IComponentConnector { #line 15 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label lblTitle; #line default #line hidden #line 19 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock lblTask; #line default #line hidden #line 25 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock txtExtraInfo; #line default #line hidden #line 37 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal NMT.Wpf.Controls.PulseButton btnPositive; #line default #line hidden #line 56 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnNutral; #line default #line hidden #line 61 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button btnNegative; #line default #line hidden #line 73 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label Username; #line default #line hidden #line 79 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.StackPanel OptionsView; #line default #line hidden #line 80 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label LabelOn; #line default #line hidden #line 81 "..\..\Busy.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label labelOff; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/PS4 PSP Classics GUI;component/busy.xaml", System.UriKind.Relative); #line 1 "..\..\Busy.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: #line 9 "..\..\Busy.xaml" ((PS4_PSP_Classics_GUI.Busy)(target)).Loaded += new System.Windows.RoutedEventHandler(this.Window_Loaded); #line default #line hidden return; case 2: this.lblTitle = ((System.Windows.Controls.Label)(target)); return; case 3: this.lblTask = ((System.Windows.Controls.TextBlock)(target)); return; case 4: this.txtExtraInfo = ((System.Windows.Controls.TextBlock)(target)); return; case 5: this.btnPositive = ((NMT.Wpf.Controls.PulseButton)(target)); return; case 6: this.btnNutral = ((System.Windows.Controls.Button)(target)); return; case 7: this.btnNegative = ((System.Windows.Controls.Button)(target)); return; case 8: this.Username = ((System.Windows.Controls.Label)(target)); return; case 9: this.OptionsView = ((System.Windows.Controls.StackPanel)(target)); return; case 10: this.LabelOn = ((System.Windows.Controls.Label)(target)); return; case 11: this.labelOff = ((System.Windows.Controls.Label)(target)); return; } this._contentLoaded = true; } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" standalone="no" ?> <!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd"> <pov> <cbid>EAGLE_00004</cbid> <replay> <write> <data>aPenFullOfSheep:)\n</data> <data>mov r2,1725045291\npush r2\n</data> <data>mov r3,1450729592\npush r3\n</data> <data>pop r2\nout r2\nmov m0,r2\n</data> <data>mov r3,-1897323157\npush r3\n</data> <data>mov r0,-2005945785\npush r0\n</data> <data>pop r0\nout r0\nmov m1,r0\n</data> <data>pop m2\nout m2\n</data> <data>push 2018573937\n</data> <data>push -1419413568\n</data> <data>pop m3\nout m3\n</data> <data>push -1939915448\n</data> <data>mov r1,1196496339\npush r1\n</data> <data>push -1465487741\n</data> <data>pop r0\nout r0\nmov m4,r0\n</data> <data>pop r0\nout r0\nmov m5,r0\n</data> <data>pop r2\nout r2\nmov m6,r2\n</data> <data>pop r1\nout r1\nmov m7,r1\n</data> <data>mov r3,-1260981549\npush r3\n</data> <data>pop m8\nout m8\n</data> <data>pop m9\nout m9\n</data> <data>mov r3,-1286317346\npush r3\n</data> <data>mov r3,1998540554\npush r3\n</data> <data>pop r1\nout r1\nmov m10,r1\n</data> <data>pop r3\nout r3\nmov m11,r3\n</data> <data>push -895410655\n</data> <data>mov r2,-2045732974\npush r2\n</data> <data>mov r3,-624469811\npush r3\n</data> <data>mov r1,-1977088461\npush r1\n</data> <data>pop r3\nout r3\nmov m12,r3\n</data> <data>push 495006369\n</data> <data>push 1961044257\n</data> <data>pop r0\nout r0\nmov m13,r0\n</data> <data>pop r0\nout r0\nmov m14,r0\n</data> <data>pop m15\nout m15\n</data> <data>push 2001386112\n</data> <data>mov r3,-1074547778\npush r3\n</data> <data>mov r1,1496146222\npush r1\n</data> <data>push 1773031590\n</data> <data>push -1360482807\n</data> <data>push -1820143761\n</data> <data>pop m16\nout m16\n</data> <data>push -1151787495\n</data> <data>pop m17\nout m17\n</data> <data>mov r3,1305237549\npush r3\n</data> <data>mov r0,-288520965\npush r0\n</data> <data>push 2127091490\n</data> <data>pop m18\nout m18\n</data> <data>pop r2\nout r2\nmov m19,r2\n</data> <data>push -1253518706\n</data> <data>push -1400322771\n</data> <data>pop m20\nout m20\n</data> <data>mov r3,582043321\npush r3\n</data> <data>mov r1,389753294\npush r1\n</data> <data>pop r3\nout r3\nmov m21,r3\n</data> <data>pop r2\nout r2\nmov m22,r2\n</data> <data>pop m23\nout m23\n</data> <data>push 810073222\n</data> <data>push 1233990304\n</data> <data>mov r2,-1822517930\npush r2\n</data> <data>pop r3\nout r3\nmov m24,r3\n</data> <data>pop r3\nout r3\nmov m25,r3\n</data> <data>push -1997263345\n</data> <data>pop r2\nout r2\nmov m26,r2\n</data> <data>push -2057495741\n</data> <data>mov r3,-1611862746\npush r3\n</data> <data>pop r0\nout r0\nmov m27,r0\n</data> <data>pop r0\nout r0\nmov m28,r0\n</data> <data>push 1865024675\n</data> <data>pop r2\nout r2\nmov m29,r2\n</data> <data>mov r0,1721075161\npush r0\n</data> <data>pop r1\nout r1\nmov m30,r1\n</data> <data>pop r1\nout r1\nmov m31,r1\n</data> <data>pop r3\nout r3\nmov m32,r3\n</data> <data>pop r2\nout r2\nmov m33,r2\n</data> <data>pop m34\nout m34\n</data> <data>pop m35\nout m35\n</data> <data>pop r0\nout r0\nmov m36,r0\n</data> <data>pop r0\nout r0\nmov m37,r0\n</data> <data>pop m38\nout m38\n</data> <data>pop m39\nout m39\n</data> <data>mov r1,-1540796594\n</data> <data>mul r1,m0\n</data> <data>out r1\n</data> <data>out -777360240\n</data> <data>mov r0,m1\nadd r1,r0\n</data> <data>out r1\n</data> <data>out 1511661271\n</data> <data>add r1,m2\n</data> <data>out r1\n</data> <data>out -385661886\n</data> <data>add r1,m3\n</data> <data>out r1\n</data> <data>out -1805075454\n</data> <data>mov r3,m4\nmul r1,r3\n</data> <data>out r1\n</data> <data>out 732762374\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 101821739\n</data> <data>shr r1,1\n</data> <data>out r1\n</data> <data>out 50910869\n</data> <data>mov r2,m5\nadd r1,r2\n</data> <data>out r1\n</data> <data>out 1247407208\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 1760319818\n</data> <data>mov r2,m6\nsub r1,r2\n</data> <data>out r1\n</data> <data>out -594732030\n</data> <data>shr r1,2\n</data> <data>out r1\n</data> <data>out -148683008\n</data> <data>add r1,m7\n</data> <data>out r1\n</data> <data>out 1869890929\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 1900377199\n</data> <data>mov r0,m8\nadd r1,r0\n</data> <data>out r1\n</data> <data>out 639395650\n</data> <data>mov r2,m9\nsub r1,r2\n</data> <data>out r1\n</data> <data>out -1085649641\n</data> <data>mov r0,m10\nadd r1,r0\n</data> <data>out r1\n</data> <data>out 912890913\n</data> <data>mov r3,m11\nsub r1,r3\n</data> <data>out r1\n</data> <data>out -2095759037\n</data> <data>shl r1,5\n</data> <data>out r1\n</data> <data>out 1655187552\n</data> <data>mov r2,m12\nmul r1,r2\n</data> <data>out r1\n</data> <data>out -1485681888\n</data> <data>shl r1,3\n</data> <data>out r1\n</data> <data>out 999446784\n</data> <data>div r1,m13\n</data> <data>out r1\n</data> <data>out 0\n</data> <data>mov r2,m14\nsub r1,r2\n</data> <data>out r1\n</data> <data>out -495006369\n</data> <data>shl r1,7\n</data> <data>out r1\n</data> <data>out 1063694208\n</data> <data>add r1,m15\n</data> <data>out r1\n</data> <data>out 439224397\n</data> <data>shr r1,7\n</data> <data>out r1\n</data> <data>out 3431440\n</data> <data>mov r2,m16\nmul r1,r2\n</data> <data>out r1\n</data> <data>out 1564793584\n</data> <data>shr r1,6\n</data> <data>out r1\n</data> <data>out 24449899\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 1796437249\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 24449899\n</data> <data>add r1,m17\n</data> <data>out r1\n</data> <data>out -1127337596\n</data> <data>add r1,m18\n</data> <data>out r1\n</data> <data>out 999753894\n</data> <data>shr r1,4\n</data> <data>out r1\n</data> <data>out 62484618\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out -1972324093\n</data> <data>mov r2,m19\nadd r1,r2\n</data> <data>out r1\n</data> <data>out 2034122238\n</data> <data>mov r3,m20\ndiv r1,r3\n</data> <data>out r1\n</data> <data>out -1\n</data> <data>shl r1,6\n</data> <data>out r1\n</data> <data>out -64\n</data> <data>add r1,m21\n</data> <data>out r1\n</data> <data>out 389753230\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out -1909900521\n</data> <data>mov r0,m22\nsub r1,r0\n</data> <data>out r1\n</data> <data>out 1803023454\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 1593079659\n</data> <data>shr r1,7\n</data> <data>out r1\n</data> <data>out 12445934\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out -286737152\n</data> <data>shr r1,2\n</data> <data>out r1\n</data> <data>out -71684288\n</data> <data>mul r1,m23\n</data> <data>out r1\n</data> <data>out -435636864\n</data> <data>mov r2,m24\nmul r1,r2\n</data> <data>out r1\n</data> <data>out 2106620160\n</data> <data>mov r3,m25\nadd r1,r3\n</data> <data>out r1\n</data> <data>out -954356832\n</data> <data>shr r1,0\n</data> <data>out r1\n</data> <data>out -954356832\n</data> <data>shr r1,4\n</data> <data>out r1\n</data> <data>out -59647302\n</data> <data>mod r1,m26\n</data> <data>out r1\n</data> <data>out -59647302\n</data> <data>shr r1,3\n</data> <data>out r1\n</data> <data>out -7455913\n</data> <data>mov r2,m27\nmul r1,r2\n</data> <data>out r1\n</data> <data>out 1497389546\n</data> <data>mov r0,m28\nsub r1,r0\n</data> <data>out r1\n</data> <data>out -740082009\n</data> <data>shl r1,2\n</data> <data>out r1\n</data> <data>out 1334639260\n</data> <data>add r1,m29\n</data> <data>out r1\n</data> <data>out -1095303361\n</data> <data>mod r1,m30\n</data> <data>out r1\n</data> <data>out -1095303361\n</data> <data>add r1,m31\n</data> <data>out r1\n</data> <data>out -285230139\n</data> <data>shl r1,6\n</data> <data>out r1\n</data> <data>out -1074859712\n</data> <data>mov r2,m32\nsub r1,r2\n</data> <data>out r1\n</data> <data>out 1914870035\n</data> <data>shr r1,3\n</data> <data>out r1\n</data> <data>out 239358754\n</data> <data>add r1,m33\n</data> <data>out r1\n</data> <data>out -1121124053\n</data> <data>swp r1\n</data> <data>out r1\n</data> <data>out 721497533\n</data> <data>shr r1,1\n</data> <data>out r1\n</data> <data>out 360748766\n</data> <data>shr r1,5\n</data> <data>out r1\n</data> <data>out 11273398\n</data> <data>shl r1,3\n</data> <data>out r1\n</data> <data>out 90187184\n</data> <data>div r1,m34\n</data> <data>out r1\n</data> <data>out 0\n</data> <data>div r1,m35\n</data> <data>out r1\n</data> <data>out 0\n</data> <data>mov r2,m36\nsub r1,r2\n</data> <data>out r1\n</data> <data>out 1074547778\n</data> <data>mov r0,m37\nmod r1,r0\n</data> <data>out r1\n</data> <data>out 1074547778\n</data> <data>shl r1,7\n</data> <data>out r1\n</data> <data>out 103162112\n</data> <data>add r1,m38\n</data> <data>out r1\n</data> <data>out -1942570862\n</data> <data>sub r1,m39\n</data> <data>out r1\n</data> <data>out -1047160207\n</data> <data>END\n</data> </write> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x56786078\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x886fb247\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8ee9256b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xab6577c0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xa8a66e83\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x475115d3\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8c5f3d48\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x7850fe71\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xb4d6f2d3\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x66d21a2b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x771f4f0a\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xb3545ade\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8a280633\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x74e32921\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x1d8132a1\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xdac758cd\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x9382cf6f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbb591e19\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x7ec8d722\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xeecd84fb\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xac88c52d\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x173b29ce\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x22b146b9\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xb548d28e\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x935e9556\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x498d32a0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x88f42e0f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x9feced26\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x855d1b43\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6f2a04a3\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x669585d9\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3048bc86\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x4dcc582d\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xaee8ae09\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x69ae50a6\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x592d612e\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbff3b3be\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x774aba80\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x86109792\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xcaa11e21\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xd1aa6c90\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xd1aa6c90\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x5a1a1ed7\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x5a1a1ed7\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xe9034442\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xe9034442\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x9468bc02\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x9468bc02\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x2bad1106\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x2bad1106\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0611ad2b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0611ad2b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0308d695\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0308d695\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x4a59ec68\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x4a59ec68\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x68ec594a\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x68ec594a\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xdc8d1c02\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xdc8d1c02\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xf7234700\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xf7234700\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6f744571\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6f744571\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x7145746f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x7145746f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x261c6742\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x261c6742\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbf4a4d17\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbf4a4d17\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x36699c21\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x36699c21\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x83154143\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x83154143\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x62a82860\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x62a82860\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xa7724b20\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xa7724b20\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3b925900\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3b925900\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00000000\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00000000\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xe27ecd5f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xe27ecd5f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3f66af80\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3f66af80\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x1a2e084d\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x1a2e084d\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00345c10\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00345c10\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x5d44daf0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x5d44daf0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0175136b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0175136b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6b137501\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6b137501\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0175136b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0175136b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbcce3184\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbcce3184\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3b9708a6\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x3b9708a6\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x03b9708a\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x03b9708a\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8a70b903\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8a70b903\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x793e3dfe\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x793e3dfe\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xffffffff\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xffffffff\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xffffffc0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xffffffc0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x173b298e\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x173b298e\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8e293b17\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8e293b17\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6b77f45e\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x6b77f45e\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x5ef4776b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x5ef4776b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00bde8ee\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00bde8ee\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xeee8bd00\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xeee8bd00\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xfbba2f40\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xfbba2f40\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xe608b580\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xe608b580\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x7d907900\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x7d907900\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xc71daba0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xc71daba0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xc71daba0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xc71daba0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xfc71daba\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xfc71daba\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xfc71daba\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xfc71daba\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xff8e3b57\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xff8e3b57\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x594059ea\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x594059ea\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xd3e33ea7\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xd3e33ea7\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x4f8cfa9c\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x4f8cfa9c\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbeb6ff3f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbeb6ff3f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbeb6ff3f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbeb6ff3f\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xeeffbbc5\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xeeffbbc5\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbfeef140\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbfeef140\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x72229913\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x72229913\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0e445322\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x0e445322\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbd2d012b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xbd2d012b\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x2b012dbd\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x2b012dbd\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x158096de\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x158096de\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00ac04b6\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00ac04b6\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x056025b0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x056025b0\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00000000\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00000000\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00000000\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x00000000\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x400c4c42\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x400c4c42\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x400c4c42\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x400c4c42\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x06262100\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x06262100\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8c36b892\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0x8c36b892\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xc1959a71\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>OUT: 0xc1959a71\n</data></match></read> <read echo="ascii"><delim>\n</delim><match><data>COMPLETE\n</data></match></read> </replay> </pov>
{ "pile_set_name": "Github" }
#format: frame checksums #version: 2 #hash: MD5 #tb 0: 1/48000 #media_type 0: audio #codec_id 0: pcm_s24le #sample_rate 0: 48000 #channel_layout 0: 60f #stream#, dts, pts, duration, size, hash 0, 0, 0, 512, 9216, a2b724b146069938f0e2cb82490dea54 0, 512, 512, 512, 9216, 13a95890b5f0947d6f058ca9c30a3e01 0, 1024, 1024, 512, 9216, 13ee6aa61ed484c3d64c9d6546e296bb 0, 1536, 1536, 512, 9216, 4db0762920d0bb3ecd765168e2acd296 0, 2048, 2048, 512, 9216, 6253047a99cbc0e6b1d484b7828466b6 0, 2560, 2560, 512, 9216, 2977e1080514c6d2150ed2fde267e714
{ "pile_set_name": "Github" }
/** * WordPress dependencies */ import { applyFilters } from '@wordpress/hooks' export const showOptions = blockProps => { const { design = 'basic', showSubtitle = true, showTitle = true, showDescription = true, showArrow = false, } = blockProps.attributes return applyFilters( 'stackable.image-box.show', { columnBackground: true, borderRadius: true, shadow: true, line: design === 'box' || design === 'line', subtitleSpacing: showSubtitle, titleSpacing: showTitle, lineSpacing: design === 'line', descriptionSpacing: showDescription, arrowSpacing: showArrow, }, blockProps ) }
{ "pile_set_name": "Github" }
<?php /** * Message translations. * * This file is automatically generated by 'yii message/extract' command. * It contains the localizable messages extracted from source code. * You may modify this file by translating the extracted messages. * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of '@@' marks. * * Message string can be used with plural forms format. Check i18n section * of the guide for details. * * NOTE: this file must be saved in UTF-8 encoding. */ return [ 'Author' => '', 'Content' => '', 'Content Type' => '', 'Scope' => '', 'Sorting' => '', 'Topic' => '', 'Visibility' => '', ];
{ "pile_set_name": "Github" }
/* vi: set sw=4 ts=4: */ /* * universal getopt32 implementation for busybox * * Copyright (C) 2003-2005 Vladimir Oleynik <dzo@simtreas.ru> * * Licensed under GPLv2 or later, see file LICENSE in this source tree. */ #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG # include <getopt.h> #endif #include "libbb.h" /* Documentation uint32_t getopt32(char **argv, const char *applet_opts, ...) The command line options must be declared in const char *applet_opts as a string of chars, for example: flags = getopt32(argv, "rnug"); If one of the given options is found, a flag value is added to the return value (an unsigned long). The flag value is determined by the position of the char in applet_opts string. For example, in the above case: flags = getopt32(argv, "rnug"); "r" will add 1 (bit 0) "n" will add 2 (bit 1) "u" will add 4 (bit 2) "g" will add 8 (bit 3) and so on. You can also look at the return value as a bit field and each option sets one bit. On exit, global variable optind is set so that if you will do argc -= optind; argv += optind; then argc will be equal to number of remaining non-option arguments, first one would be in argv[0], next in argv[1] and so on (options and their parameters will be moved into argv[] positions prior to argv[optind]). ":" If one of the options requires an argument, then add a ":" after the char in applet_opts and provide a pointer to store the argument. For example: char *pointer_to_arg_for_a; char *pointer_to_arg_for_b; char *pointer_to_arg_for_c; char *pointer_to_arg_for_d; flags = getopt32(argv, "a:b:c:d:", &pointer_to_arg_for_a, &pointer_to_arg_for_b, &pointer_to_arg_for_c, &pointer_to_arg_for_d); The type of the pointer (char* or llist_t*) may be controlled by the "::" special separator that is set in the external string opt_complementary (see below for more info). "::" If option can have an *optional* argument, then add a "::" after its char in applet_opts and provide a pointer to store the argument. Note that optional arguments _must_ immediately follow the option: -oparam, not -o param. "+" If the first character in the applet_opts string is a plus, then option processing will stop as soon as a non-option is encountered in the argv array. Useful for applets like env which should not process arguments to subprograms: env -i ls -d / Here we want env to process just the '-i', not the '-d'. "!" Report bad option, missing required options, inconsistent options with all-ones return value (instead of abort). const char *applet_long_options This struct allows you to define long options: static const char applet_longopts[] ALIGN1 = //"name\0" has_arg val "verbose\0" No_argument "v" ; applet_long_options = applet_longopts; The last member of struct option (val) typically is set to matching short option from applet_opts. If there is no matching char in applet_opts, then: - return bit have next position after short options - if has_arg is not "No_argument", use ptr for arg also - opt_complementary affects it too Note: a good applet will make long options configurable via the config process and not a required feature. The current standard is to name the config option CONFIG_FEATURE_<applet>_LONG_OPTIONS. const char *opt_complementary ":" The colon (":") is used to separate groups of two or more chars and/or groups of chars and special characters (stating some conditions to be checked). "abc" If groups of two or more chars are specified, the first char is the main option and the other chars are secondary options. Their flags will be turned on if the main option is found even if they are not specifed on the command line. For example: opt_complementary = "abc"; flags = getopt32(argv, "abcd") If getopt() finds "-a" on the command line, then getopt32's return value will be as if "-a -b -c" were found. "ww" Adjacent double options have a counter associated which indicates the number of occurrences of the option. For example the ps applet needs: if w is given once, GNU ps sets the width to 132, if w is given more than once, it is "unlimited" int w_counter = 0; // must be initialized! opt_complementary = "ww"; getopt32(argv, "w", &w_counter); if (w_counter) width = (w_counter == 1) ? 132 : INT_MAX; else get_terminal_width(...&width...); w_counter is a pointer to an integer. It has to be passed to getopt32() after all other option argument sinks. For example: accept multiple -v to indicate the level of verbosity and for each -b optarg, add optarg to my_b. Finally, if b is given, turn off c and vice versa: llist_t *my_b = NULL; int verbose_level = 0; opt_complementary = "vv:b::b-c:c-b"; f = getopt32(argv, "vb:c", &my_b, &verbose_level); if (f & 2) // -c after -b unsets -b flag while (my_b) dosomething_with(llist_pop(&my_b)); if (my_b) // but llist is stored if -b is specified free_llist(my_b); if (verbose_level) printf("verbose level is %d\n", verbose_level); Special characters: "-" A group consisting of just a dash forces all arguments to be treated as options, even if they have no leading dashes. Next char in this case can't be a digit (0-9), use ':' or end of line. Example: opt_complementary = "-:w-x:x-w"; // "-w-x:x-w" would also work, getopt32(argv, "wx"); // but is less readable This makes it possible to use options without a dash (./program w x) as well as with a dash (./program -x). NB: getopt32() will leak a small amount of memory if you use this option! Do not use it if there is a possibility of recursive getopt32() calls. "--" A double dash at the beginning of opt_complementary means the argv[1] string should always be treated as options, even if it isn't prefixed with a "-". This is useful for special syntax in applets such as "ar" and "tar": tar xvf foo.tar NB: getopt32() will leak a small amount of memory if you use this option! Do not use it if there is a possibility of recursive getopt32() calls. "-N" A dash as the first char in a opt_complementary group followed by a single digit (0-9) means that at least N non-option arguments must be present on the command line "=N" An equal sign as the first char in a opt_complementary group followed by a single digit (0-9) means that exactly N non-option arguments must be present on the command line "?N" A "?" as the first char in a opt_complementary group followed by a single digit (0-9) means that at most N arguments must be present on the command line. "V-" An option with dash before colon or end-of-line results in bb_show_usage() being called if this option is encountered. This is typically used to implement "print verbose usage message and exit" option. "a-b" A dash between two options causes the second of the two to be unset (and ignored) if it is given on the command line. [FIXME: what if they are the same? like "x-x"? Is it ever useful?] For example: The du applet has the options "-s" and "-d depth". If getopt32 finds -s, then -d is unset or if it finds -d then -s is unset. (Note: busybox implements the GNU "--max-depth" option as "-d".) To obtain this behavior, you set opt_complementary = "s-d:d-s". Only one flag value is added to getopt32's return value depending on the position of the options on the command line. If one of the two options requires an argument pointer (":" in applet_opts as in "d:") optarg is set accordingly. char *smax_print_depth; opt_complementary = "s-d:d-s:x-x"; opt = getopt32(argv, "sd:x", &smax_print_depth); if (opt & 2) max_print_depth = atoi(smax_print_depth); if (opt & 4) printf("Detected odd -x usage\n"); "a--b" A double dash between two options, or between an option and a group of options, means that they are mutually exclusive. Unlike the "-" case above, an error will be forced if the options are used together. For example: The cut applet must have only one type of list specified, so -b, -c and -f are mutually exclusive and should raise an error if specified together. In this case you must set opt_complementary = "b--cf:c--bf:f--bc". If two of the mutually exclusive options are found, getopt32 will call bb_show_usage() and die. "x--x" Variation of the above, it means that -x option should occur at most once. "a+" A plus after a char in opt_complementary means that the parameter for this option is a nonnegative integer. It will be processed with xatoi_positive() - allowed range is 0..INT_MAX. int param; // "unsigned param;" will also work opt_complementary = "p+"; getopt32(argv, "p:", &param); "a::" A double colon after a char in opt_complementary means that the option can occur multiple times. Each occurrence will be saved as a llist_t element instead of char*. For example: The grep applet can have one or more "-e pattern" arguments. In this case you should use getopt32() as follows: llist_t *patterns = NULL; (this pointer must be initializated to NULL if the list is empty as required by llist_add_to_end(llist_t **old_head, char *new_item).) opt_complementary = "e::"; getopt32(argv, "e:", &patterns); $ grep -e user -e root /etc/passwd root:x:0:0:root:/root:/bin/bash user:x:500:500::/home/user:/bin/bash "a?b" A "?" between an option and a group of options means that at least one of them is required to occur if the first option occurs in preceding command line arguments. For example from "id" applet: // Don't allow -n -r -rn -ug -rug -nug -rnug opt_complementary = "r?ug:n?ug:u--g:g--u"; flags = getopt32(argv, "rnug"); This example allowed only: $ id; id -u; id -g; id -ru; id -nu; id -rg; id -ng; id -rnu; id -rng "X" A opt_complementary group with just a single letter means that this option is required. If more than one such group exists, at least one option is required to occur (not all of them). For example from "start-stop-daemon" applet: // Don't allow -KS -SK, but -S or -K is required opt_complementary = "K:S:K--S:S--K"; flags = getopt32(argv, "KS...); Don't forget to use ':'. For example, "?322-22-23X-x-a" is interpreted as "?3:22:-2:2-2:2-3Xa:2--x" - max 3 args; count uses of '-2'; min 2 args; if there is a '-2' option then unset '-3', '-X' and '-a'; if there is a '-2' and after it a '-x' then error out. But it's far too obfuscated. Use ':' to separate groups. */ /* Code here assumes that 'unsigned' is at least 32 bits wide */ const char *const bb_argv_dash[] = { "-", NULL }; const char *opt_complementary; enum { PARAM_STRING, PARAM_LIST, PARAM_INT, }; typedef struct { unsigned char opt_char; smallint param_type; unsigned switch_on; unsigned switch_off; unsigned incongruously; unsigned requires; void **optarg; /* char**, llist_t** or int *. */ int *counter; } t_complementary; /* You can set applet_long_options for parse called long options */ #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG static const struct option bb_null_long_options[1] = { { 0, 0, 0, 0 } }; const char *applet_long_options; #endif uint32_t option_mask32; uint32_t FAST_FUNC getopt32(char **argv, const char *applet_opts, ...) { int argc; unsigned flags = 0; unsigned requires = 0; t_complementary complementary[33]; /* last stays zero-filled */ char first_char; int c; const unsigned char *s; t_complementary *on_off; va_list p; #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG const struct option *l_o; struct option *long_options = (struct option *) &bb_null_long_options; #endif unsigned trigger; char **pargv; int min_arg = 0; int max_arg = -1; #define SHOW_USAGE_IF_ERROR 1 #define ALL_ARGV_IS_OPTS 2 #define FIRST_ARGV_IS_OPT 4 int spec_flgs = 0; /* skip 0: some applets cheat: they do not actually HAVE argv[0] */ argc = 1; while (argv[argc]) argc++; va_start(p, applet_opts); c = 0; on_off = complementary; memset(on_off, 0, sizeof(complementary)); /* skip bbox extension */ first_char = applet_opts[0]; if (first_char == '!') applet_opts++; /* skip GNU extension */ s = (const unsigned char *)applet_opts; if (*s == '+' || *s == '-') s++; while (*s) { if (c >= 32) break; on_off->opt_char = *s; on_off->switch_on = (1 << c); if (*++s == ':') { on_off->optarg = va_arg(p, void **); while (*++s == ':') continue; } on_off++; c++; } #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG if (applet_long_options) { const char *optstr; unsigned i, count; count = 1; optstr = applet_long_options; while (optstr[0]) { optstr += strlen(optstr) + 3; /* skip NUL, has_arg, val */ count++; } /* count == no. of longopts + 1 */ long_options = alloca(count * sizeof(*long_options)); memset(long_options, 0, count * sizeof(*long_options)); i = 0; optstr = applet_long_options; while (--count) { long_options[i].name = optstr; optstr += strlen(optstr) + 1; long_options[i].has_arg = (unsigned char)(*optstr++); /* long_options[i].flag = NULL; */ long_options[i].val = (unsigned char)(*optstr++); i++; } for (l_o = long_options; l_o->name; l_o++) { if (l_o->flag) continue; for (on_off = complementary; on_off->opt_char; on_off++) if (on_off->opt_char == l_o->val) goto next_long; if (c >= 32) break; on_off->opt_char = l_o->val; on_off->switch_on = (1 << c); if (l_o->has_arg != no_argument) on_off->optarg = va_arg(p, void **); c++; next_long: ; } /* Make it unnecessary to clear applet_long_options * by hand after each call to getopt32 */ applet_long_options = NULL; } #endif /* ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG */ for (s = (const unsigned char *)opt_complementary; s && *s; s++) { t_complementary *pair; unsigned *pair_switch; if (*s == ':') continue; c = s[1]; if (*s == '?') { if (c < '0' || c > '9') { spec_flgs |= SHOW_USAGE_IF_ERROR; } else { max_arg = c - '0'; s++; } continue; } if (*s == '-') { if (c < '0' || c > '9') { if (c == '-') { spec_flgs |= FIRST_ARGV_IS_OPT; s++; } else spec_flgs |= ALL_ARGV_IS_OPTS; } else { min_arg = c - '0'; s++; } continue; } if (*s == '=') { min_arg = max_arg = c - '0'; s++; continue; } for (on_off = complementary; on_off->opt_char; on_off++) if (on_off->opt_char == *s) goto found_opt; /* Without this, diagnostic of such bugs is not easy */ bb_error_msg_and_die("NO OPT %c!", *s); found_opt: if (c == ':' && s[2] == ':') { on_off->param_type = PARAM_LIST; continue; } if (c == '+' && (s[2] == ':' || s[2] == '\0')) { on_off->param_type = PARAM_INT; s++; continue; } if (c == ':' || c == '\0') { requires |= on_off->switch_on; continue; } if (c == '-' && (s[2] == ':' || s[2] == '\0')) { flags |= on_off->switch_on; on_off->incongruously |= on_off->switch_on; s++; continue; } if (c == *s) { on_off->counter = va_arg(p, int *); s++; } pair = on_off; pair_switch = &pair->switch_on; for (s++; *s && *s != ':'; s++) { if (*s == '?') { pair_switch = &pair->requires; } else if (*s == '-') { if (pair_switch == &pair->switch_off) pair_switch = &pair->incongruously; else pair_switch = &pair->switch_off; } else { for (on_off = complementary; on_off->opt_char; on_off++) if (on_off->opt_char == *s) { *pair_switch |= on_off->switch_on; break; } } } s--; } opt_complementary = NULL; va_end(p); if (spec_flgs & (FIRST_ARGV_IS_OPT | ALL_ARGV_IS_OPTS)) { pargv = argv + 1; while (*pargv) { if (pargv[0][0] != '-' && pargv[0][0] != '\0') { /* Can't use alloca: opts with params will * return pointers to stack! * NB: we leak these allocations... */ char *pp = xmalloc(strlen(*pargv) + 2); *pp = '-'; strcpy(pp + 1, *pargv); *pargv = pp; } if (!(spec_flgs & ALL_ARGV_IS_OPTS)) break; pargv++; } } /* In case getopt32 was already called: * reset the libc getopt() function, which keeps internal state. * run_nofork_applet() does this, but we might end up here * also via gunzip_main() -> gzip_main(). Play safe. */ #ifdef __GLIBC__ optind = 0; #else /* BSD style */ optind = 1; /* optreset = 1; */ #endif /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */ /* Note: just "getopt() <= 0" will not work well for * "fake" short options, like this one: * wget $'-\203' "Test: test" http://kernel.org/ * (supposed to act as --header, but doesn't) */ #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG while ((c = getopt_long(argc, argv, applet_opts, long_options, NULL)) != -1) { #else while ((c = getopt(argc, argv, applet_opts)) != -1) { #endif /* getopt prints "option requires an argument -- X" * and returns '?' if an option has no arg, but one is reqd */ c &= 0xff; /* fight libc's sign extension */ for (on_off = complementary; on_off->opt_char != c; on_off++) { /* c can be NUL if long opt has non-NULL ->flag, * but we construct long opts so that flag * is always NULL (see above) */ if (on_off->opt_char == '\0' /* && c != '\0' */) { /* c is probably '?' - "bad option" */ goto error; } } if (flags & on_off->incongruously) goto error; trigger = on_off->switch_on & on_off->switch_off; flags &= ~(on_off->switch_off ^ trigger); flags |= on_off->switch_on ^ trigger; flags ^= trigger; if (on_off->counter) (*(on_off->counter))++; if (optarg) { if (on_off->param_type == PARAM_LIST) { llist_add_to_end((llist_t **)(on_off->optarg), optarg); } else if (on_off->param_type == PARAM_INT) { //TODO: xatoi_positive indirectly pulls in printf machinery *(unsigned*)(on_off->optarg) = xatoi_positive(optarg); } else if (on_off->optarg) { *(char **)(on_off->optarg) = optarg; } } } /* check depending requires for given options */ for (on_off = complementary; on_off->opt_char; on_off++) { if (on_off->requires && (flags & on_off->switch_on) && (flags & on_off->requires) == 0 ) { goto error; } } if (requires && (flags & requires) == 0) goto error; argc -= optind; if (argc < min_arg || (max_arg >= 0 && argc > max_arg)) goto error; option_mask32 = flags; return flags; error: if (first_char != '!') bb_show_usage(); return (int32_t)-1; }
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Arcanedev\Support\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider; use Illuminate\Support\Facades\Gate; /** * Class AuthorizationServiceProvider * * @author ARCANEDEV <arcanedev.maroc@gmail.com> */ abstract class AuthorizationServiceProvider extends AuthServiceProvider { /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * Define policies. * * @param string $class * @param array $policies */ protected function defineMany($class, array $policies) { foreach ($policies as $ability => $method) { Gate::define($ability, "$class@$method"); } } }
{ "pile_set_name": "Github" }
<snippet> <content><![CDATA[$1]]></content> </snippet>
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft. All rights reserved. #![deny(unused_extern_crates, warnings)] #![deny(clippy::all, clippy::pedantic)] use std::str; use std::sync::Mutex; use bytes::Bytes; use lazy_static::lazy_static; use edgelet_core::crypto::Sign; use edgelet_core::crypto::Signature; use edgelet_core::crypto::SignatureAlgorithm; use edgelet_core::KeyIdentity; use edgelet_core::KeyStore; use edgelet_hsm::{HsmLock, TpmKeyStore}; mod test_utils; use test_utils::TestHSMEnvSetup; lazy_static! { static ref LOCK: Mutex<()> = Mutex::new(()); } const TEST_KEY_BASE64: &str = "D7PuplFy7vIr0349blOugqCxyfMscyVZDoV9Ii0EFnA="; // This tests the following: // 1) A well known identity key K can be installed in the TPM // 2) The HMACSHA256 digest sign request for a known payload DATA // should return a digest whose value would be diferent based on the identity. #[test] fn tpm_identity_affects_digest() { // arrange let _setup_home_dir = TestHSMEnvSetup::new(&LOCK, None); let hsm_lock = HsmLock::new(); let key_store = TpmKeyStore::new(hsm_lock).unwrap(); let decoded_key = base64::decode(TEST_KEY_BASE64).unwrap(); let decoded_key_str = unsafe { str::from_utf8_unchecked(&decoded_key) }; let module1_identity: KeyIdentity = KeyIdentity::Module("module1".to_string()); key_store .activate_key(&Bytes::from(decoded_key_str)) .unwrap(); let key1 = key_store.get(&module1_identity, "primary").unwrap(); let key2 = key_store.get(&module1_identity, "secondary").unwrap(); let data_to_be_signed = b"I am the very model of a modern major general"; // act let digest1 = key1 .sign(SignatureAlgorithm::HMACSHA256, data_to_be_signed) .unwrap(); let digest2 = key2 .sign(SignatureAlgorithm::HMACSHA256, data_to_be_signed) .unwrap(); // assert assert_ne!(digest1.as_bytes(), digest2.as_bytes()); }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="style.css" type="text/css" rel="stylesheet"> <title>MINSD—Return Minimum Scalar Double-Precision Floating-Point Value </title></head> <body> <h1>MINSD—Return Minimum Scalar Double-Precision Floating-Point Value</h1> <table> <tr> <th>Opcode/Instruction</th> <th>Op/En</th> <th>64/32-bit Mode</th> <th>CPUID Feature Flag</th> <th>Description</th></tr> <tr> <td> <p>F2 0F 5D /<em>r</em></p> <p>MINSD <em>xmm1</em>, <em>xmm2/m64</em></p></td> <td>RM</td> <td>V/V</td> <td>SSE2</td> <td>Return the minimum scalar double-precision floating-point value between <em>xmm2/mem64 </em>and<em> xmm1</em>.</td></tr> <tr> <td> <p>VEX.NDS.LIG.F2.0F.WIG 5D /r</p> <p>VMINSD <em>xmm1, xmm2, xmm3/m64</em></p></td> <td>RVM</td> <td>V/V</td> <td>AVX</td> <td>Return the minimum scalar double precision floating-point value between <em>xmm3/mem64 </em>and <em>xmm2</em>.</td></tr></table> <h3>Instruction Operand Encoding</h3> <table> <tr> <td>Op/En</td> <td>Operand 1</td> <td>Operand 2</td> <td>Operand 3</td> <td>Operand 4</td></tr> <tr> <td>RM</td> <td>ModRM:reg (r, w)</td> <td>ModRM:r/m (r)</td> <td>NA</td> <td>NA</td></tr> <tr> <td>RVM</td> <td>ModRM:reg (w)</td> <td>VEX.vvvv (r)</td> <td>ModRM:r/m (r)</td> <td>NA</td></tr></table> <h2>Description</h2> <p>Compares the low double-precision floating-point values in the first source operand and the second source operand, and returns the minimum value to the low quadword of the destination operand. When the source operand is a memory operand, only the 64 bits are accessed. The high quadword of the destination operand is copied from the same bits in the first source operand.</p> <p>If the values being compared are both 0.0s (of either sign), the value in the second source operand is returned. If a value in the second source operand is an SNaN, that SNaN is returned unchanged to the destination (that is, a QNaN version of the SNaN is not returned).</p> <p>If only one value is a NaN (SNaN or QNaN) for this instruction, the second source operand, either a NaN or a valid floating-point value, is written to the result. If instead of this behavior, it is required that the NaN source operand (from either the first or second source) be returned, the action of MINSD can be emulated using a sequence of instructions, such as, a comparison followed by AND, ANDN and OR.</p> <p>The second source operand can be an XMM register or a 64-bit memory location. The first source and destination operands are XMM registers.</p> <p>In 64-bit mode, use of the REX.R prefix permits this instruction to access additional registers (XMM8-XMM15).</p> <p>128-bit Legacy SSE version: The destination and first source operand are the same. Bits (VLMAX-1:64) of the corresponding YMM destination register remain unchanged.</p> <p>VEX.128 encoded version: Bits (127:64) of the XMM register destination are copied from corresponding bits in the first source operand. Bits (VLMAX-1:128) of the destination YMM register are zeroed.</p> <h2>Operation</h2> <p><strong>MIN(SRC1, SRC2)</strong></p> <pre>{ IF ((SRC1 = 0.0) and (SRC2 = 0.0)) THEN DEST ← SRC2; ELSE IF (SRC1 = SNaN) THEN DEST ← SRC2; FI; ELSE IF SRC2 = SNaN) THEN DEST ← SRC2; FI; ELSE IF (SRC1 &lt; SRC2) THEN DEST ← SRC1; ELSE DEST ← SRC2; FI; }</pre> <p><strong>MINSD (128-bit Legacy SSE version)</strong></p> <pre>DEST[63:0] ← MIN(SRC1[63:0], SRC2[63:0]) DEST[VLMAX-1:64] (Unmodified)</pre> <p><strong>MINSD (VEX.128 encoded version)</strong></p> <pre>DEST[63:0] ← MIN(SRC1[63:0], SRC2[63:0]) DEST[127:64] ← SRC1[127:64] DEST[VLMAX-1:128] ← 0</pre> <h2>Intel C/C++ Compiler Intrinsic Equivalent</h2> <p>MINSD:</p> <p> __m128d _mm_min_sd(__m128d a, __m128d b)</p> <h2>SIMD Floating-Point Exceptions</h2> <p>Invalid (including QNaN source operand), Denormal.</p> <h2>Other Exceptions</h2> <p>See Exceptions Type 3.</p></body></html>
{ "pile_set_name": "Github" }
solid ascii facet normal -1 0 0 outer loop vertex 0.59 0 0 vertex 0.59 0 0.05 vertex 0.59 0.1 0 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0.1 0.05 vertex 0.59 0.1 0 vertex 0.59 0 0.05 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0 0.05 vertex 0.59 0 0.1 vertex 0.59 0.1 0.05 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0.1 0.1 vertex 0.59 0.1 0.05 vertex 0.59 0 0.1 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0.1 0 vertex 0.59 0.1 0.05 vertex 0.59 0.2 0 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0.2 0.05 vertex 0.59 0.2 0 vertex 0.59 0.1 0.05 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0.1 0.05 vertex 0.59 0.1 0.1 vertex 0.59 0.2 0.05 endloop endfacet facet normal -1 0 0 outer loop vertex 0.59 0.2 0.1 vertex 0.59 0.2 0.05 vertex 0.59 0.1 0.1 endloop endfacet endsolid
{ "pile_set_name": "Github" }
#ifndef LIBXMP_LFO_H #define LIBXMP_LFO_H #include "common.h" struct lfo { int type; int rate; int depth; int phase; }; int libxmp_lfo_get(struct context_data *, struct lfo *, int); void libxmp_lfo_update(struct lfo *); void libxmp_lfo_set_phase(struct lfo *, int); void libxmp_lfo_set_depth(struct lfo *, int); void libxmp_lfo_set_rate(struct lfo *, int); void libxmp_lfo_set_waveform(struct lfo *, int); #endif
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. import { Constants, RetryOptions } from "@azure/core-amqp"; /** * @internal * @ignore */ export function getRetryAttemptTimeoutInMs(retryOptions: RetryOptions | undefined): number { const timeoutInMs = retryOptions == undefined || typeof retryOptions.timeoutInMs !== "number" || !isFinite(retryOptions.timeoutInMs) || retryOptions.timeoutInMs < Constants.defaultOperationTimeoutInMs ? Constants.defaultOperationTimeoutInMs : retryOptions.timeoutInMs; return timeoutInMs; }
{ "pile_set_name": "Github" }
export default { name: 'resourceSimple', component: () => import('./index.vue'), dispatchs: ['Workbench:add', 'Footer:updateRunningJob'], } ;
{ "pile_set_name": "Github" }
################################################################################ # # xlib_libxkbfile # ################################################################################ XLIB_LIBXKBFILE_VERSION = 1.0.9 XLIB_LIBXKBFILE_SOURCE = libxkbfile-$(XLIB_LIBXKBFILE_VERSION).tar.bz2 XLIB_LIBXKBFILE_SITE = http://xorg.freedesktop.org/releases/individual/lib XLIB_LIBXKBFILE_LICENSE = MIT XLIB_LIBXKBFILE_LICENSE_FILES = COPYING XLIB_LIBXKBFILE_INSTALL_STAGING = YES XLIB_LIBXKBFILE_DEPENDENCIES = xlib_libX11 xorgproto HOST_XLIB_LIBXKBFILE_DEPENDENCIES = host-xlib_libX11 host-xorgproto $(eval $(autotools-package)) $(eval $(host-autotools-package))
{ "pile_set_name": "Github" }
<?php /* +--------------------------------------------------------------------+ | Copyright CiviCRM LLC. All rights reserved. | | | | This work is published under the GNU AGPLv3 license with some | | permitted exceptions and without any warranty. For full license | | and copyright information, see https://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC https://civicrm.org/licensing */ namespace api\v4\Entity; use Civi\Api4\ActivityContact; use Civi\Api4\Contact; use api\v4\UnitTestCase; use Civi\Test\TransactionalInterface; /** * Assert that interchanging data between APIv3 and APIv4 yields consistent * encodings. * * @group headless */ class ContactInterchangeTest extends UnitTestCase implements TransactionalInterface { public function getExamples() { $apiWriters = [ 'create_3', 'create_4', ]; $apiReaderSets = [ ['readNameById_3', 'readNameByValueEq_3'], ['readNameById_4', 'readNameByValueEq_4', 'readNameByValueIn_4'], ['readNameByActSubjectChain_3', /* 'readNameByActSubjectJoin_3' */], ['readNameByActSubjectChain_4', 'readNameByActSubjectJoin_4'], [/*'readNameByActDetailsChain_3',*/ 'readNameByActDetailsJoin_3'], ['readNameByActDetailsChain_4', 'readNameByActDetailsJoin_4'], ]; $strings = [ // Values chosen for backwards compatibility. ['api' => 'Little Bobby :> & :<', 'db' => 'Little Bobby :&gt; & :&lt;'], ['api' => 'Little Bobby &amp; Bob', 'db' => 'Little Bobby &amp; Bob'], ['api' => 'It\'s', 'db' => 'It\'s'], ]; $cases = \CRM_Utils_Array::product([ 'w' => $apiWriters, 'r' => $apiReaderSets, 'strs' => $strings, ]); foreach ($cases as $case) { yield [$case['w'], $case['r'], $case['strs']]; } } /** * Use the given $writer to create a row with some funny data. * Then use the given $reader to load the row. * Assert that the funny data looks the same. * * @dataProvider getExamples */ public function testReadWriteAPI($writer, $readers, $strs) { $caseName = sprintf("writer=%s, strs.api=%s", $writer, $strs['api']); $cid = call_user_func([$this, $writer], $strs); $dbGet = \CRM_Core_DAO::singleValueQuery('SELECT first_name FROM civicrm_contact WHERE id = %1', [ 1 => [$cid, 'Positive'], ]); $this->assertEquals($strs['db'], $dbGet, "Check DB content ($caseName)"); $this->assertNotEmpty($readers); foreach ($readers as $reader) { $get = call_user_func([$this, $reader], $cid, $strs); // $get = $this->autoWrapException([$this, $reader], [$cid, $strs], "Check API content (reader=$reader $caseName)"); $this->assertEquals($strs['api'], $get, "Check API content (reader=$reader $caseName)"); } } private function autoWrapException($callable, $args, $message) { try { return call_user_func_array($callable, $args); } catch (\Exception $e) { throw new \Exception($message . $e->getMessage(), 0, $e); } } public function create_3($strs) { $contact = civicrm_api3('Contact', 'create', [ 'contact_type' => 'Individual', 'first_name' => $strs['api'], 'api.Activity.create' => [ 'source_contact_id' => '$value.id', 'subject' => $strs['api'], 'details' => $strs['api'], 'activity_type_id' => 2, ], ]); return $contact['id']; } public function create_4($strs) { $contact = civicrm_api4('Contact', 'create', [ 'values' => [ 'contact_type' => 'Individual', 'first_name' => $strs['api'], ], 'chain' => [ 'my_call' => [ 'Activity', 'create', [ 'values' => [ 'source_contact_id' => '$id', 'subject' => $strs['api'], 'details' => $strs['api'], 'activity_type_id' => 2, ], ], ], ], ]); return $contact->first()['id']; } public function readNameById_3($cid, $strs) { $get = civicrm_api3('Contact', 'getsingle', [ 'id' => $cid, 'return' => 'first_name', ]); return $get['first_name']; } public function readNameByValueEq_3($cid, $strs) { $get = civicrm_api3('Contact', 'getsingle', [ 'first_name' => $strs['api'], ]); return $get['first_name']; } public function readNameById_4($cid, $strs) { $get = Contact::get() ->addWhere('id', '=', $cid) ->addSelect('first_name') ->execute(); return $get->first()['first_name']; } public function readNameByValueEq_4($cid, $strs) { $get = Contact::get() ->addWhere('first_name', '=', $strs['api']) ->addSelect('first_name') ->execute(); return $get->first()['first_name']; } public function readNameByValueIn_4($cid, $strs) { $get = Contact::get() ->addWhere('first_name', 'IN', [$strs['api']]) ->addSelect('first_name') ->execute(); return $get->first()['first_name']; } public function readNameByActSubjectJoin_3($cid, $strs) { $get = civicrm_api3('ActivityContact', 'getsingle', [ 'record_type_id' => 'Activity Source', 'activity_id.subject' => $strs['api'], 'return' => ['contact_id.first_name'], ]); return $get['contact_id.first_name']; } public function readNameByActSubjectChain_3($cid, $strs) { $get = civicrm_api3('Activity', 'getsingle', [ 'subject' => $strs['api'], 'api.ActivityContact.getsingle' => [ 'activity_id' => '$value.id', 'record_type_id' => 'Activity Source', 'api.Contact.getsingle' => [ 'id' => '$value.contact_id', 'return' => 'first_name', ], ], 'return' => ['id'], ]); return $get['api.ActivityContact.getsingle']['api.Contact.getsingle']['first_name']; } public function readNameByActSubjectJoin_4($cid, $strs) { $get = ActivityContact::get() ->addWhere('record_type_id:label', '=', 'Activity Source') ->addWhere('activity.subject', '=', $strs['api']) ->addSelect('contact.first_name') ->execute(); return $get->first()['contact.first_name']; } public function readNameByActSubjectChain_4($cid, $strs) { $get = ActivityContact::get() ->addWhere('record_type_id:label', '=', 'Activity Source') ->addWhere('activity.subject', '=', $strs['api']) ->setSelect(['activity_id', 'contact_id']) ->setChain([ 'the_contact' => [ 'Contact', 'get', ['where' => [['id', '=', '$contact_id']], 'select' => ['first_name']], 0, ], ]) ->execute(); $result = $get->first(); return $result['the_contact']['first_name']; } public function readNameByActDetailsJoin_3($cid, $strs) { $get = civicrm_api3('ActivityContact', 'getsingle', [ 'record_type_id' => 'Activity Source', 'activity_id.details' => $strs['api'], 'return' => ['contact_id.first_name'], ]); return $get['contact_id.first_name']; } public function readNameByActDetailsChain_3($cid, $strs) { $get = civicrm_api3('Activity', 'getsingle', [ 'details' => $strs['api'], 'api.ActivityContact.getsingle' => [ 'activity_id' => '$value.id', 'record_type_id' => 'Activity Source', 'api.Contact.getsingle' => [ 'id' => '$value.contact_id', 'return' => 'first_name', ], ], 'return' => ['id'], ]); return $get['api.ActivityContact.getsingle']['api.Contact.getsingle']['first_name']; } public function readNameByActDetailsJoin_4($cid, $strs) { $get = ActivityContact::get() ->addWhere('record_type_id:label', '=', 'Activity Source') ->addWhere('activity.details', '=', $strs['api']) ->addSelect('contact.first_name') ->execute(); return $get->first()['contact.first_name']; } public function readNameByActDetailsChain_4($cid, $strs) { $get = ActivityContact::get() ->addWhere('record_type_id:label', '=', 'Activity Source') ->addWhere('activity.details', '=', $strs['api']) ->setSelect(['activity_id', 'contact_id']) ->setChain([ 'the_contact' => [ 'Contact', 'get', ['where' => [['id', '=', '$contact_id']], 'select' => ['first_name']], 0, ], ]) ->execute(); $result = $get->first(); return $result['the_contact']['first_name']; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must 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. */ package com.oracle.truffle.js.builtins.intl; import com.oracle.truffle.js.builtins.JSBuiltinsContainer; import com.oracle.truffle.js.nodes.function.JSBuiltin; import com.oracle.truffle.js.nodes.intl.SupportedLocalesOfNodeGen; import com.oracle.truffle.js.runtime.JSContext; import com.oracle.truffle.js.runtime.builtins.BuiltinEnum; import com.oracle.truffle.js.runtime.builtins.intl.JSRelativeTimeFormat; /** * Contains built-ins for {@linkplain JSRelativeTimeFormat} function (constructor). */ public final class RelativeTimeFormatFunctionBuiltins extends JSBuiltinsContainer.SwitchEnum<RelativeTimeFormatFunctionBuiltins.RelativeTimeFormatFunction> { public static final JSBuiltinsContainer BUILTINS = new RelativeTimeFormatFunctionBuiltins(); protected RelativeTimeFormatFunctionBuiltins() { super(JSRelativeTimeFormat.CLASS_NAME, RelativeTimeFormatFunction.class); } public enum RelativeTimeFormatFunction implements BuiltinEnum<RelativeTimeFormatFunction> { supportedLocalesOf(1); private final int length; RelativeTimeFormatFunction(int length) { this.length = length; } @Override public int getLength() { return length; } } @Override protected Object createNode(JSContext context, JSBuiltin builtin, boolean construct, boolean newTarget, RelativeTimeFormatFunction builtinEnum) { switch (builtinEnum) { case supportedLocalesOf: return SupportedLocalesOfNodeGen.create(context, builtin, args().fixedArgs(2).createArgumentNodes(context)); } return null; } }
{ "pile_set_name": "Github" }
# Locally calculated sha256 bfb39434f31d10f1b8c7b6bc6ec612309838c2819022561541c4d2d5a424e3f2 genpart-1.0.2.tar.bz2
{ "pile_set_name": "Github" }
/* global describe, it */ var filter = require('../lib/filter') var assert = require('assert') var compiledMask var object var expected // a,b(d/*/z,b(g)),c compiledMask = { a: { type: 'object' }, b: { type: 'array', properties: { d: { type: 'object', properties: { '*': { type: 'object', properties: { z: { type: 'object' } } } } }, b: { type: 'array', properties: { g: { type: 'object' } } } } }, c: { type: 'object' } } object = { a: 11, n: 0, b: [{ d: { g: { z: 22 }, b: 34, c: { a: 32 } }, b: [{ z: 33 }], k: 99 }], c: 44, g: 99 } expected = { a: 11, b: [{ d: { g: { z: 22 }, c: {} }, b: [{}] }], c: 44 } describe('filter', function () { it('should filter object for a compiled mask', function () { assert.deepStrictEqual(filter(object, compiledMask), expected) }) })
{ "pile_set_name": "Github" }
<?php /** * DboOracleTest file * * PHP versions 4 and 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package cake * @subpackage cake.cake.libs * @since CakePHP(tm) v 1.2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) { define('CAKEPHP_UNIT_TEST_EXECUTION', 1); } require_once LIBS . 'model' . DS . 'datasources' . DS . 'dbo_source.php'; require_once LIBS . 'model' . DS . 'datasources' . DS . 'dbo' . DS . 'dbo_oracle.php'; /** * DboOracleTest class * * @package cake * @subpackage cake.tests.cases.libs.model.datasources.dbo */ class DboOracleTest extends CakeTestCase { /** * fixtures property */ var $fixtures = array('core.oracle_user'); /** * setup method * * @access public * @return void */ function setUp() { $this->_initDb(); } /** * skip method * * @access public * @return void */ function skip() { $this->_initDb(); $this->skipUnless($this->db->config['driver'] == 'oracle', '%s Oracle connection not available'); } /** * testLastErrorStatement method * * @access public * @return void */ function testLastErrorStatement() { if ($this->skip('testLastErrorStatement')) { return; } $this->expectError(); $this->db->execute("SELECT ' FROM dual"); $e = $this->db->lastError(); $r = 'ORA-01756: quoted string not properly terminated'; $this->assertEqual($e, $r); } /** * testLastErrorConnect method * * @access public * @return void */ function testLastErrorConnect() { if ($this->skip('testLastErrorConnect')) { return; } $config = $this->db->config; $old_pw = $this->db->config['password']; $this->db->config['password'] = 'keepmeout'; $this->db->connect(); $e = $this->db->lastError(); $r = 'ORA-01017: invalid username/password; logon denied'; $this->assertEqual($e, $r); $this->db->config['password'] = $old_pw; $this->db->connect(); } /** * testName method * * @access public * @return void */ function testName() { $Db = $this->db; #$Db =& new DboOracle($config = null, $autoConnect = false); $r = $Db->name($Db->name($Db->name('foo.last_update_date'))); $e = 'foo.last_update_date'; $this->assertEqual($e, $r); $r = $Db->name($Db->name($Db->name('foo._update'))); $e = 'foo."_update"'; $this->assertEqual($e, $r); $r = $Db->name($Db->name($Db->name('foo.last_update_date'))); $e = 'foo.last_update_date'; $this->assertEqual($e, $r); $r = $Db->name($Db->name($Db->name('last_update_date'))); $e = 'last_update_date'; $this->assertEqual($e, $r); $r = $Db->name($Db->name($Db->name('_update'))); $e = '"_update"'; $this->assertEqual($e, $r); } }
{ "pile_set_name": "Github" }
/* ** ----------------------------------------------------------------------------- ** ** Perle Specialix driver for Linux ** Ported from existing RIO Driver for SCO sources. * * (C) 1990 - 2000 Specialix International Ltd., Byfleet, Surrey, UK. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ** Module : map.h ** SID : 1.2 ** Last Modified : 11/6/98 11:34:11 ** Retrieved : 11/6/98 11:34:21 ** ** ident @(#)map.h 1.2 ** ** ----------------------------------------------------------------------------- */ #ifndef __rio_map_h__ #define __rio_map_h__ /* ** mapping structure passed to and from the config.rio program to ** determine the current topology of the world */ #define MAX_MAP_ENTRY 17 #define TOTAL_MAP_ENTRIES (MAX_MAP_ENTRY*RIO_SLOTS) #define MAX_NAME_LEN 32 struct Map { unsigned int HostUniqueNum; /* Supporting hosts unique number */ unsigned int RtaUniqueNum; /* Unique number */ /* ** The next two IDs must be swapped on big-endian architectures ** when using a v2.04 /etc/rio/config with a v3.00 driver (when ** upgrading for example). */ unsigned short ID; /* ID used in the subnet */ unsigned short ID2; /* ID of 2nd block of 8 for 16 port */ unsigned long Flags; /* Booted, ID Given, Disconnected */ unsigned long SysPort; /* First tty mapped to this port */ struct Top Topology[LINKS_PER_UNIT]; /* ID connected to each link */ char Name[MAX_NAME_LEN]; /* Cute name by which RTA is known */ }; /* ** Flag values: */ #define RTA_BOOTED 0x00000001 #define RTA_NEWBOOT 0x00000010 #define MSG_DONE 0x00000020 #define RTA_INTERCONNECT 0x00000040 #define RTA16_SECOND_SLOT 0x00000080 #define BEEN_HERE 0x00000100 #define SLOT_TENTATIVE 0x40000000 #define SLOT_IN_USE 0x80000000 /* ** HostUniqueNum is the unique number from the host card that this RTA ** is to be connected to. ** RtaUniqueNum is the unique number of the RTA concerned. It will be ZERO ** if the slot in the table is unused. If it is the same as the HostUniqueNum ** then this slot represents a host card. ** Flags contains current boot/route state info ** SysPort is a value in the range 0-504, being the number of the first tty ** on this RTA. Each RTA supports 8 ports. The SysPort value must be modulo 8. ** SysPort 0-127 correspond to /dev/ttyr001 to /dev/ttyr128, with minor ** numbers 0-127. SysPort 128-255 correspond to /dev/ttyr129 to /dev/ttyr256, ** again with minor numbers 0-127, and so on for SysPorts 256-383 and 384-511 ** ID will be in the range 0-16 for a `known' RTA. ID will be 0xFFFF for an ** unused slot/unknown ID etc. ** The Topology array contains the ID of the unit connected to each of the ** four links on this unit. The entry will be 0xFFFF if NOTHING is connected ** to the link, or will be 0xFF00 if an UNKNOWN unit is connected to the link. ** The Name field is a null-terminated string, upto 31 characters, containing ** the 'cute' name that the sysadmin/users know the RTA by. It is permissible ** for this string to contain any character in the range \040 to \176 inclusive. ** In particular, ctrl sequences and DEL (0x7F, \177) are not allowed. The ** special character '%' IS allowable, and needs no special action. ** */ #endif
{ "pile_set_name": "Github" }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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. */ package org.spongepowered.common.registry.type.world; import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import org.spongepowered.api.registry.RegistryModule; import org.spongepowered.api.registry.util.RegisterCatalog; import org.spongepowered.api.world.ChunkRegenerateFlags; import org.spongepowered.common.registry.RegistryHelper; import org.spongepowered.common.world.SpongeChunkRegenerateFlag; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; public final class ChunkRegenerateFlagRegistryModule implements RegistryModule { @RegisterCatalog(ChunkRegenerateFlags.class) private final Map<String, SpongeChunkRegenerateFlag> flags = new LinkedHashMap<>(4); private final Int2ObjectMap<SpongeChunkRegenerateFlag> maskedFlags = new Int2ObjectLinkedOpenHashMap<>(4); private static ChunkRegenerateFlagRegistryModule INSTANCE = new ChunkRegenerateFlagRegistryModule(); public static ChunkRegenerateFlagRegistryModule getInstance() { return INSTANCE; } private ChunkRegenerateFlagRegistryModule() { } public static SpongeChunkRegenerateFlag fromNativeInt(int flag) { final SpongeChunkRegenerateFlag spongeChunkRegenerateFlag = getInstance().maskedFlags.get(flag); if (spongeChunkRegenerateFlag != null) { return spongeChunkRegenerateFlag; } return (SpongeChunkRegenerateFlag) ChunkRegenerateFlags.ALL; } @Override public void registerDefaults() { register(new SpongeChunkRegenerateFlag("NONE".toLowerCase(Locale.ENGLISH), Flags.NONE)); register(new SpongeChunkRegenerateFlag("ALL".toLowerCase(Locale.ENGLISH), Flags.ALL)); register(new SpongeChunkRegenerateFlag("CREATE".toLowerCase(Locale.ENGLISH), Flags.CREATE)); register(new SpongeChunkRegenerateFlag("ENTITIES".toLowerCase(Locale.ENGLISH), Flags.ENTITIES)); RegistryHelper.mapFields(ChunkRegenerateFlags.class, this.flags); } private void register(SpongeChunkRegenerateFlag flag) { this.maskedFlags.put(flag.getRawFlag(), flag); this.flags.put(flag.getName(), flag); } public Collection<SpongeChunkRegenerateFlag> getValues() { return Collections.unmodifiableCollection(this.flags.values()); } public static final class Flags { public static final int CREATE = 0b00000001; public static final int ENTITIES = 0b00000010; public static final int NONE = 0000000000; public static final int ALL = CREATE | ENTITIES; } }
{ "pile_set_name": "Github" }
<!-- Copyright (C) 2015 The Android Open Source Project 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. --> <!--suppress AndroidElementNotAllowed --> <set xmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator android:duration="200" android:interpolator="@interpolator/ic_volume_collapse_animation_interpolator_0" android:propertyName="rotation" android:valueFrom="-45.0" android:valueTo="45.0" android:valueType="floatType"/> </set>
{ "pile_set_name": "Github" }
/* ** Copyright 2002, Travis Geiselbrecht. All rights reserved. ** Distributed under the terms of the NewOS License. */ #ifndef _NEWOS_KERNEL_ARCH_SPARC64_ELF_H #define _NEWOS_KERNEL_ARCH_SPARC64_ELF_H #define ELF_PREPEND_UNDERSCORE 0 #endif
{ "pile_set_name": "Github" }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package mobile const ( // ErrCodeAccountActionRequiredException for service response error code // "AccountActionRequiredException". // // Account Action is required in order to continue the request. ErrCodeAccountActionRequiredException = "AccountActionRequiredException" // ErrCodeBadRequestException for service response error code // "BadRequestException". // // The request cannot be processed because some parameter is not valid or the // project state prevents the operation from being performed. ErrCodeBadRequestException = "BadRequestException" // ErrCodeInternalFailureException for service response error code // "InternalFailureException". // // The service has encountered an unexpected error condition which prevents // it from servicing the request. ErrCodeInternalFailureException = "InternalFailureException" // ErrCodeLimitExceededException for service response error code // "LimitExceededException". // // There are too many AWS Mobile Hub projects in the account or the account // has exceeded the maximum number of resources in some AWS service. You should // create another sub-account using AWS Organizations or remove some resources // and retry your request. ErrCodeLimitExceededException = "LimitExceededException" // ErrCodeNotFoundException for service response error code // "NotFoundException". // // No entity can be found with the specified identifier. ErrCodeNotFoundException = "NotFoundException" // ErrCodeServiceUnavailableException for service response error code // "ServiceUnavailableException". // // The service is temporarily unavailable. The request should be retried after // some time delay. ErrCodeServiceUnavailableException = "ServiceUnavailableException" // ErrCodeTooManyRequestsException for service response error code // "TooManyRequestsException". // // Too many requests have been received for this AWS account in too short a // time. The request should be retried after some time delay. ErrCodeTooManyRequestsException = "TooManyRequestsException" // ErrCodeUnauthorizedException for service response error code // "UnauthorizedException". // // Credentials of the caller are insufficient to authorize the request. ErrCodeUnauthorizedException = "UnauthorizedException" )
{ "pile_set_name": "Github" }
E700: E701: E702: E703: E704: E705: E706: E707: E708: E709: E70A: E70B: E70C: E70D: E70E: E70F: E710: E711: E712: E713: E714: E715: E716: E717: E718: E719: E71A: E71B: E71C: E71D: E71E: E71F: E720: E721: E722: E723: E724: E725: E726: E727: E728: E729: E72A: E72B: E72C: E72D: E72E: E72F: E730: E731: E732: E733: E734: E735: E736: E737: E738: E739: E73A: E73B: E73C: E73D: E73E: E73F: E740: E741: E742: E743: E744: E745: E746: E747: E748: E749: E74A: E74B: E74C: E74D: E74E: E74F: E750: E751: E752: E753: E754: E755: E756: E757: E758: E759: E75A: E75B: E75C: E75D: E75E: E75F: E760: E761: E762: E763: E764: E765: E766: E767: E768: E769: E76A: E76B: E76C: E76D: E76E: E76F: E770: E771: E772: E773: E774: E775: E776: E777: E778: E779: E77A: E77B: E77C: E77D: E77E: E77F: E780: E781: E782: E783: E784: E785: E786: E787: E788: E789: E78A: E78B: E78C: E78D: E78E: E78F: E790: E791: E792: E793: E794: E795: E796: E797: E798: E799: E79A: E79B: E79C: E79D: E79E: E79F: E7A0: E7A1: E7A2: E7A3: E7A4: E7A5: E7A6: E7A7: E7A8: E7A9: E7AA: E7AB: E7AC: E7AD: E7AE: E7AF: E7B0: E7B1: E7B2: E7B3: E7B4: E7B5: E7B6: E7B7: E7B8: E7B9: E7BA: E7BB: E7BC: E7BD: E7BE: E7BF: E7C0: E7C1: E7C2: E7C3: E7C4: E7C5: E7C6: E7C7: E7C8: E7C9: E7CA: E7CB: E7CC: E7CD: E7CE: E7CF: E7D0: E7D1: E7D2: E7D3: E7D4: E7D5: E7D6: E7D7: E7D8: E7D9: E7DA: E7DB: E7DC: E7DD: E7DE: E7DF: E7E0: E7E1: E7E2: E7E3: E7E4: E7E5: E7E6: E7E7: E7E8: E7E9: E7EA: E7EB: E7EC: E7ED: E7EE: E7EF: E7F0: E7F1: E7F2: E7F3: E7F4: E7F5: E7F6: E7F7: E7F8: E7F9: E7FA: E7FB: E7FC: E7FD: E7FE: E7FF:
{ "pile_set_name": "Github" }
Car 0.00 0 1.8566885153439383 190.82 191.12 433.59 327.39 1.4173637706606101 1.5720861249328995 4.081195341549911 -3.89 1.73 10.20 1.492342691086201 0.9999987 Car 0.00 0 -1.848410622277532 730.74 181.53 942.14 324.99 1.478390001115055 1.6342595715732717 3.5787478556261445 2.58 1.58 9.18 -1.5744324575459212 0.9999902 Car 0.00 0 -1.612545264014278 657.18 174.63 734.98 234.88 1.5157374538300943 1.6429197287843966 3.8399998304770375 2.22 1.54 19.93 -1.5016126972886645 0.889077 Pedestrian 0.00 1 1.3899542401221137 401.96 180.16 436.14 249.87 1.704326277077551 0.6936238314297867 0.8845623401710891 -4.62 1.80 17.29 1.1288479431516132 0.96171564 Car 0.00 1 2.932966665425573 374.27 170.17 484.60 221.24 1.565795578417034 1.6244370781542206 4.061152802907028 -6.68 1.73 26.79 2.6886029003238114 0.9571819 Misc 0.00 2 1.4823191250350813 641.36 133.13 713.30 219.41 1.6878994855849456 1.6410416187909835 3.9716589619741822 2.35 1.58 27.03 1.5690414992161046 0.9999161 Car 0.00 0 1.3958854089167456 540.41 176.11 562.09 194.32 1.5556406009762 1.6567067608894253 4.094872133933105 -5.19 1.86 63.92 1.314867893452736 0.7186308 DontCare -1 -1 -1.5935451696303229 567.90 171.90 586.69 188.61 1.505270393919797 1.682418546891346 3.8305250165388967 -1000 -1000 -1000 -0.8081470062328746 0.96813077 DontCare -1 -1 -0.9965711990979056 617.90 170.85 652.32 193.81 1.4312485907046508 1.6571503516943598 3.7234564443455125 -1000 -1000 -1000 -0.2111730357004573 0.9991698
{ "pile_set_name": "Github" }
#if !defined(RESIP_WSCOOKIEAUTHMANAGER_HXX) #define RESIP_WSCOOKIEAUTHMANAGER_HXX #include <map> #include <set> #include "resip/stack/SipMessage.hxx" #include "DumFeature.hxx" #include "resip/stack/Cookie.hxx" #include "resip/stack/WsCookieContext.hxx" namespace resip { class DialogUsageManager; class WsCookieAuthManager : public DumFeature { public: enum Result { Authorized, Skipped, Rejected }; WsCookieAuthManager(DialogUsageManager& dum, TargetCommand::Target& target); virtual ~WsCookieAuthManager(); virtual ProcessingResult process(Message* msg); protected: // can return Authorized, Rejected, Skipped virtual Result handle(SipMessage* sipMsg); /// compares URI user and host, allows wildcards in first URI bool cookieUriMatch(const resip::Uri &first, const resip::Uri &second); /// should return true if the passed in user is authorized for the provided uri bool authorizedForThisIdentity(const MethodTypes method, const WsCookieContext &wsCookieContext, const resip::Uri &fromUri, const resip::Uri &toUri); /// should return true if the request must be challenged /// The default is to challenge all requests - override this class to change this beviour virtual bool requiresAuthorization(const SipMessage& msg); }; } #endif /* ==================================================================== * BSD License * * Copyright (c) 2013 Catalin Constantin Usurelu All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the author(s) nor the names of any contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ==================================================================== * */
{ "pile_set_name": "Github" }
package io.joyrpc.cluster.distribution.loadbalance.adaptive.judge; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import io.joyrpc.cluster.Node; import io.joyrpc.cluster.Region; import io.joyrpc.cluster.distribution.loadbalance.adaptive.AdaptivePolicy; import io.joyrpc.cluster.distribution.loadbalance.adaptive.NodeMetric; import io.joyrpc.cluster.distribution.loadbalance.adaptive.Rank; /** * 地域机房评分 */ public class ZoneAwareJudge extends AbstractJudge { public ZoneAwareJudge() { super(JudgeType.ZoneAware); } @Override public Rank score(final NodeMetric metric, final AdaptivePolicy policy) { Node node = metric.getNode(); Region region = metric.getCluster().getRegion(); MatchType area = match(region == null ? null : region.getRegion(), node.getRegion()); if (area == MatchType.None) { //地域不匹配 return Rank.Poor; } MatchType room = match(region == null ? null : region.getDataCenter(), node.getDataCenter()); if (area == MatchType.Exact && room == MatchType.Exact) { //地域和机房都匹配 return Rank.Good; } //地域匹配 return Rank.Fair; } /** * 匹配 * * @param source 源字符串 * @param target 目标字符串 * @return 匹配类型 */ protected MatchType match(final String source, final String target) { if (source == null || source.isEmpty() || target == null || target.isEmpty()) { return MatchType.Fuzzy; } return source.equals(target) ? MatchType.Exact : MatchType.None; } /** * 匹配类型 */ protected enum MatchType { /** * 精确 */ Exact, /** * 模糊匹配 */ Fuzzy, /** * 不匹配 */ None; } }
{ "pile_set_name": "Github" }
/** File: candy.js * Make several Candy actions accessible via the message box when prefixed with a slash "/" * * Authors: * - Ben Klang <bklang@mojolingo.com> * * Contributors: * - Troy McCabe <troy.mccabe@geeksquad.com> * - Jonatan Männchen <jonatan.maennchen@amiadogroup.com> * - Sudrien <_+github@sudrien.net> * * Copyright: * - (c) 2014 Mojo Lingo LLC. All rights reserved. */ /* global alert, Candy, jQuery, $build */ var CandyShop = (function(self) { return self; }(CandyShop || {})); CandyShop.SlashCommands = (function(self, Candy, $) { /** Object: about * About SlashCommands plugin * * Contains: * (String) name - Candy Plugin SlashCommands * (Float) version - Candy Plugin Available Rooms version */ self.about = { name: 'Candy Plugin SlashCommands', version: '0.2.0' }; self.commands = [ 'join', 'part', 'clear', 'topic', 'available', 'away', 'dnd', 'nick', 'leave', 'invite', 'kick' ]; /* This is not a command. me-does can handle /me formatting */ self.passthrough = [ 'me', ]; self.defaultConferenceDomain = null; /** Function: init * Initializes the Slash Commands plugin with the default settings. */ self.init = function(){ $(Candy).on('candy:view.connection.status-5', self.setDefaultConferenceDomain); $(Candy).on('candy:view.connection.status-8', self.setDefaultConferenceDomain); $(Candy).bind('candy:view.message.before-send', function(e, args) { try { // (strip colors) var input = args.message.replace(/\|c:\d+\|/, ''); if (input[0] !== '/') { return; } var match = input.match(/^\/([^\s]+)(?:\s+(.*))?$/m); if (match === null) { return; } var command = match[1]; var data = match[2]; // pass though some commands, they only merit formatting elsewhere if ($.inArray(command, self.passthrough) !== -1) { } // Match only whitelisted commands else if ($.inArray(command, self.commands) !== -1) { self[command](data); args.message = ''; } else { Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "Invalid command: " + command); args.message = ''; } } catch (ex) { // Without an exception catcher, the page will reload and the user will be logged out Candy.Core.log(ex); } }); }; /** Function: join * Joins a room * * Parameters: * (String) args The name of the room and the optional password, separated by a space */ self.join = function(args) { if(args === undefined || args === ''){ Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "usage: /join room OR /join room roomPassword"); return false; } args = args.trim().split(' '); var room = args[0]; var password = args[1]; if(room === undefined || room === null || room === '') { return; } if(room.indexOf("@") === -1) { room += self.defaultConferenceDomain; } if (password === undefined || password === null || password === '') { Candy.Core.Action.Jabber.Room.Join(room); } Candy.Core.Action.Jabber.Room.Join(room, password); }; /** Function: nick * Sets Nickname * * Parameters: * (String) args The name of the room and the optional password, separated by a space */ self.nick = function(args) { if(args === undefined || args === null || args === '') { Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "usage: /nick newNickname"); return; } Candy.Core.Action.Jabber.SetNickname(args); }; /** Function: part * Exits the current chat room * */ self.part = function() { Candy.Core.Action.Jabber.Room.Leave(self.currentRoom()); }; /** Function: leave * /part alias * */ self.leave = function() { self.part(); }; /** Function: topic * Sets the topic (subject) for the current chat room * * Parameters: * (String) topic The new topic for the room */ self.topic = function(topic) { // this may not actually set the topic. it's up to the server to notify if that is the case. Candy.Core.Action.Jabber.Room.Admin.SetSubject(self.currentRoom(), topic); }; /** Function: clear * Clear the current room's scrollback */ self.clear = function() { $('.room-pane:visible').find('.message-pane').empty(); }; /** Function: available * Change the current user's XMPP status to "available" with an optional message * Parameters: * (String) message Optional message to set with availability */ self.available = function() { // TODO: The message field is currently unsupported by Candy.Core.Action.Jabber.Presence Candy.Core.Action.Jabber.Presence(); }; /** Function: away * Change the current user's XMPP status to "away" with an optional message * Parameters: * (String) message Optional message to set with availability */ self.away = function() { // TODO: The message field is currently unsupported by Candy.Core.Action.Jabber.Presence Candy.Core.Action.Jabber.Presence(null, $build('show', 'away')); }; /** Function: dnd * Change the current user's XMPP status to "dnd" with an optional message * Parameters: * (String) message Optional message to set with availability */ self.dnd = function() { // TODO: The message field is currently unsupported by Candy.Core.Action.Jabber.Presence Candy.Core.Action.Jabber.Presence(null, $build('show', 'dnd')); }; /** Function: invite * invite another user to the current chat room, with lookups for real room & user jids * *Parameters: * (String) user Nickname of user, or JID - all currently connected rooms will be checked * (String) room Optional room name, must already exist * (String) password Optional room password, if room requires one */ self.invite = function(args) { if(args === undefined || args === null || args === ''){ Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "usage: /invite user (from the room) OR /invite &lt;user&gt; room roomPassword"); return false; } argsRegex = args.match(/\<(.+)\>(.*)/); var userJid = null; if(argsRegex === null){ var userText = args; var user = new RegExp("^" + userText + "$", "i"); var room = null; var password = null; var roomJid = self.currentRoom(); } else { var userText = argsRegex[1]; var user = new RegExp("^" + userText + "$", "i"); var roomText = argsRegex[2].trim().split(' ')[0]; var room = new RegExp("^" + roomText + "$", "i"); var password = argsRegex[2].trim().split(' ')[1]; var roomJid = null; } // loop through all rooms with current connections $.each(Candy.Core.getRooms(), function(roomName, roomData) { if( !roomJid && roomData && roomData.room.name.match(room) ) { roomJid = roomName; } if( !roomJid && roomName.match(room) ) { roomJid = roomName; } // loop through all users in a room // compare jids, nicks and previous nicks $.each(roomData.roster.getAll(), function(userName, userData) { if( !userJid && userData.getJid().match(user) ) { userJid = userData.data.jid; } if( !userJid && userData.getNick().match(user) ){ userJid = userData.data.jid; } if( !userJid && userData.getPreviousNick() !== undefined && userData.getPreviousNick().match(user) ) { userJid = userData.data.jid; } }); }); // ok, that's all the checks. if(userJid === undefined || userJid === null || userJid === '') { Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "Could not find " + userText + " to invite"); return; } if(roomJid === undefined || roomJid === null || roomJid === '') { Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "Could not find room " + roomText); return; } if(roomJid === self.currentRoom() && (password=== undefined || password === null || password === '')) { Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "Invited " + userJid + " to " + self.currentRoom()); var stanza = $msg({'from': Candy.Core.getUser().data.jid, 'to': userJid, 'xmlns': 'jabber:client'}).c('x', {'xmlns': 'jabber:x:conference', 'jid': self.currentRoom()}); Candy.Core.getConnection().send(stanza.tree()); return; } if(password=== undefined || password === null || password === '') { Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "Invited " + userJid + " to " + roomJid); var stanza = $msg({'from': Candy.Core.getUser().data.jid, 'to': userJid, 'xmlns': 'jabber:client'}).c('x', {'xmlns': 'jabber:x:conference', 'jid': roomJid}); Candy.Core.getConnection().send(stanza.tree()); return; } Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "Invited " + userJid + " to " + roomJid + " (with password)"); var stanza = $msg({'from': Candy.Core.getUser().data.jid, 'to': userJid, 'xmlns': 'jabber:client'}).c('x', {'xmlns': 'jabber:x:conference', 'jid': roomJid}); stanza.c("password").t(password); Candy.Core.getConnection().send(stanza.tree()); }; /** Function: kick * Kick user from current room. Admins only. * * Parameters: * (String) user Nickname of user, or JID - all currently connected rooms will be checked * (String) comment Optional comment as to why they were kicked */ self.kick = function(args) { if(args === undefined || args === null || args === ''){ Candy.View.Pane.Chat.onInfoMessage(self.currentRoom(), '', "usage: /kick nickname OR /kick &lt;nickname&gt; comment"); return false; } argsRegex = args.match(/\<(.+)\>(.*)/); var userJid = null; if(argsRegex === null){ var user = new RegExp("^" + args + "$", "i"); var comment = null; } else { var user = new RegExp("^" + argsRegex[1] + "$", "i"); var comment = argsRegex[2].trim(); } $.each(Candy.Core.getRooms()[self.currentRoom()].roster.getAll(), function(userName, userData) { if( !userJid && userData.getJid().match(user) ) { userJid = userData.data.jid; } if( !userJid && userData.getNick().match(user) ){ userJid = userData.data.jid; } if( !userJid && userData.getPreviousNick() !== undefined && userData.getPreviousNick().match(user) ) { userJid = userData.data.jid; } }); if(userJid === undefined || userJid === null || userJid === '') { return; } if(comment === null || comment === '') { Candy.Core.Action.Jabber.Room.Admin.UserAction(self.currentRoom(), userJid, "kick"); } Candy.Core.Action.Jabber.Room.Admin.UserAction(self.currentRoom(), userJid, "kick", comment); }; /** Function: currentRoom * Helper function to get the current room */ self.currentRoom = function() { return Candy.View.getCurrent().roomJid; }; self.setDefaultConferenceDomain = function() { // When connected to the server, default the conference domain if unspecified if (!self.defaultConferenceDomain) { self.defaultConferenceDomain = "@conference." + Candy.Core.getConnection().domain; } // Ensure we have a leading "@" if (self.defaultConferenceDomain.indexOf('@') === -1) { self.defaultConferenceDomain = "@" + self.defaultConferenceDomain; } }; return self; }(CandyShop.SlashCommands || {}, Candy, jQuery));
{ "pile_set_name": "Github" }
var timeParsePatterns = [ // 9 { re: /^\d{1,2}$/i, handler: function(bits) { if (bits[0].length == 1) { return '0' + bits[0] + ':00'; } else { return bits[0] + ':00'; } } }, // 13:00 { re: /^\d{2}[:.]\d{2}$/i, handler: function(bits) { return bits[0].replace('.', ':'); } }, // 9:00 { re: /^\d[:.]\d{2}$/i, handler: function(bits) { return '0' + bits[0].replace('.', ':'); } }, // 3 am / 3 a.m. / 3am { re: /^(\d+)\s*([ap])(?:.?m.?)?$/i, handler: function(bits) { var hour = parseInt(bits[1]); if (hour == 12) { hour = 0; } if (bits[2].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':00'; } else { if (hour < 10) { return '0' + hour + ':00'; } else { return hour + ':00'; } } } }, // 3.30 am / 3:15 a.m. / 3.00am { re: /^(\d+)[.:](\d{2})\s*([ap]).?m.?$/i, handler: function(bits) { var hour = parseInt(bits[1]); var mins = parseInt(bits[2]); if (mins < 10) { mins = '0' + mins; } if (hour == 12) { hour = 0; } if (bits[3].toLowerCase() == 'p') { if (hour == 12) { hour = 0; } return (hour + 12) + ':' + mins; } else { if (hour < 10) { return '0' + hour + ':' + mins; } else { return hour + ':' + mins; } } } }, // noon { re: /^no/i, handler: function(bits) { return '12:00'; } }, // midnight { re: /^mid/i, handler: function(bits) { return '00:00'; } } ]; function parseTimeString(s) { for (var i = 0; i < timeParsePatterns.length; i++) { var re = timeParsePatterns[i].re; var handler = timeParsePatterns[i].handler; var bits = re.exec(s); if (bits) { return handler(bits); } } return s; }
{ "pile_set_name": "Github" }
<?php namespace Guzzle\Tests\Plugin\Mock; use Guzzle\Common\Event; use Guzzle\Http\EntityBody; use Guzzle\Http\Message\Response; use Guzzle\Plugin\Mock\MockPlugin; use Guzzle\Http\Client; use Guzzle\Http\Exception\CurlException; /** * @covers Guzzle\Plugin\Mock\MockPlugin */ class MockPluginTest extends \Guzzle\Tests\GuzzleTestCase { public function testDescribesSubscribedEvents() { $this->assertInternalType('array', MockPlugin::getSubscribedEvents()); } public function testDescribesEvents() { $this->assertInternalType('array', MockPlugin::getAllEvents()); } public function testCanBeTemporary() { $plugin = new MockPlugin(); $this->assertFalse($plugin->isTemporary()); $plugin = new MockPlugin(null, true); $this->assertTrue($plugin->isTemporary()); } public function testIsCountable() { $plugin = new MockPlugin(); $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); $this->assertEquals(1, count($plugin)); } /** * @depends testIsCountable */ public function testCanClearQueue() { $plugin = new MockPlugin(); $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); $plugin->clearQueue(); $this->assertEquals(0, count($plugin)); } public function testCanInspectQueue() { $plugin = new MockPlugin(); $this->assertInternalType('array', $plugin->getQueue()); $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); $queue = $plugin->getQueue(); $this->assertInternalType('array', $queue); $this->assertEquals(1, count($queue)); } public function testRetrievesResponsesFromFiles() { $response = MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response'); $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response); $this->assertEquals(200, $response->getStatusCode()); } /** * @expectedException InvalidArgumentException */ public function testThrowsExceptionWhenResponseFileIsNotFound() { MockPlugin::getMockFile('missing/filename'); } /** * @expectedException InvalidArgumentException */ public function testInvalidResponsesThrowAnException() { $p = new MockPlugin(); $p->addResponse($this); } public function testAddsResponseObjectsToQueue() { $p = new MockPlugin(); $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); $p->addResponse($response); $this->assertEquals(array($response), $p->getQueue()); } public function testAddsResponseFilesToQueue() { $p = new MockPlugin(); $p->addResponse(__DIR__ . '/../../TestData/mock_response'); $this->assertEquals(1, count($p)); } /** * @depends testAddsResponseFilesToQueue */ public function testAddsMockResponseToRequestFromClient() { $p = new MockPlugin(); $response = MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response'); $p->addResponse($response); $client = new Client('http://127.0.0.1:123/'); $client->getEventDispatcher()->addSubscriber($p, 9999); $request = $client->get(); $request->send(); $this->assertSame($response, $request->getResponse()); $this->assertEquals(0, count($p)); } /** * @depends testAddsResponseFilesToQueue * @expectedException \OutOfBoundsException */ public function testUpdateThrowsExceptionWhenEmpty() { $p = new MockPlugin(); $p->onRequestBeforeSend(new Event()); } /** * @depends testAddsMockResponseToRequestFromClient */ public function testDetachesTemporaryWhenEmpty() { $p = new MockPlugin(null, true); $p->addResponse(MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response')); $client = new Client('http://127.0.0.1:123/'); $client->getEventDispatcher()->addSubscriber($p, 9999); $request = $client->get(); $request->send(); $this->assertFalse($this->hasSubscriber($client, $p)); } public function testLoadsResponsesFromConstructor() { $p = new MockPlugin(array(new Response(200))); $this->assertEquals(1, $p->count()); } public function testStoresMockedRequests() { $p = new MockPlugin(array(new Response(200), new Response(200))); $client = new Client('http://127.0.0.1:123/'); $client->getEventDispatcher()->addSubscriber($p, 9999); $request1 = $client->get(); $request1->send(); $this->assertEquals(array($request1), $p->getReceivedRequests()); $request2 = $client->get(); $request2->send(); $this->assertEquals(array($request1, $request2), $p->getReceivedRequests()); $p->flush(); $this->assertEquals(array(), $p->getReceivedRequests()); } public function testReadsBodiesFromMockedRequests() { $p = new MockPlugin(array(new Response(200))); $p->readBodies(true); $client = new Client('http://127.0.0.1:123/'); $client->getEventDispatcher()->addSubscriber($p, 9999); $body = EntityBody::factory('foo'); $request = $client->put(); $request->setBody($body); $request->send(); $this->assertEquals(3, $body->ftell()); } public function testCanMockBadRequestExceptions() { $client = new Client('http://127.0.0.1:123/'); $ex = new CurlException('Foo'); $mock = new MockPlugin(array($ex)); $client->addSubscriber($mock); $request = $client->get('foo'); try { $request->send(); $this->fail('Did not dequeue an exception'); } catch (CurlException $e) { $this->assertSame($e, $ex); $this->assertSame($request, $ex->getRequest()); } } }
{ "pile_set_name": "Github" }