content
stringlengths 3
806k
| option
stringclasses 3
values | score
float64 0.01
1
| __index_level_0__
int64 0
100k
|
---|---|---|---|
namespace SqlConnectionTest
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.elementHost1 = new System.Windows.Forms.Integration.ElementHost();
this.sqlConnectionDialog1 = new SSDTDevPack.Common.ConnectionDialog.SqlConnectionDialog();
this.SuspendLayout();
//
// elementHost1
//
this.elementHost1.Dock = System.Windows.Forms.DockStyle.Fill;
this.elementHost1.Location = new System.Drawing.Point(0, 0);
this.elementHost1.Name = "elementHost1";
this.elementHost1.Size = new System.Drawing.Size(412, 281);
this.elementHost1.TabIndex = 0;
this.elementHost1.Text = "elementHost1";
this.elementHost1.Child = this.sqlConnectionDialog1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(412, 281);
this.Controls.Add(this.elementHost1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Integration.ElementHost elementHost1;
private SSDTDevPack.Common.ConnectionDialog.SqlConnectionDialog sqlConnectionDialog1;
}
}
| medium | 0.487778 | 304 |
/*
* 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 com.facebook.presto.type;
import com.facebook.presto.operator.scalar.AbstractTestFunctions;
import com.facebook.presto.spi.type.SqlDate;
import com.facebook.presto.spi.type.SqlTimeWithTimeZone;
import com.facebook.presto.spi.type.SqlTimestampWithTimeZone;
import com.facebook.presto.spi.type.TimeZoneKey;
import com.facebook.presto.sql.analyzer.SemanticErrorCode;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import static com.facebook.presto.spi.function.OperatorType.INDETERMINATE;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.DateType.DATE;
import static com.facebook.presto.spi.type.TimeType.TIME;
import static com.facebook.presto.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE;
import static com.facebook.presto.spi.type.TimeZoneKey.getTimeZoneKey;
import static com.facebook.presto.spi.type.TimeZoneKey.getTimeZoneKeyForOffset;
import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP;
import static com.facebook.presto.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.testing.DateTimeTestingUtils.sqlTimeOf;
import static com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static com.facebook.presto.type.IntervalDayTimeType.INTERVAL_DAY_TIME;
import static com.facebook.presto.util.DateTimeZoneIndex.getDateTimeZone;
import static org.joda.time.DateTimeZone.UTC;
public abstract class TestTimestampBase
extends AbstractTestFunctions
{
protected static final TimeZoneKey TIME_ZONE_KEY = getTimeZoneKey("Europe/Berlin");
protected static final DateTimeZone DATE_TIME_ZONE = getDateTimeZone(TIME_ZONE_KEY);
protected static final TimeZoneKey WEIRD_TIME_ZONE_KEY = getTimeZoneKeyForOffset(7 * 60 + 9);
protected static final DateTimeZone WEIRD_ZONE = getDateTimeZone(WEIRD_TIME_ZONE_KEY);
protected static final TimeZoneKey ORAL_TIME_ZONE_KEY = getTimeZoneKey("Asia/Oral");
protected static final DateTimeZone ORAL_ZONE = getDateTimeZone(ORAL_TIME_ZONE_KEY);
protected TestTimestampBase(boolean legacyTimestamp)
{
super(testSessionBuilder()
.setSystemProperty("legacy_timestamp", String.valueOf(legacyTimestamp))
.setTimeZoneKey(TIME_ZONE_KEY)
.build());
}
@Test
public void testSubtract()
{
functionAssertions.assertFunctionString("TIMESTAMP '2017-03-30 14:15:16.432' - TIMESTAMP '2016-03-29 03:04:05.321'",
INTERVAL_DAY_TIME,
"366 11:11:11.111");
functionAssertions.assertFunctionString("TIMESTAMP '2016-03-29 03:04:05.321' - TIMESTAMP '2017-03-30 14:15:16.432'",
INTERVAL_DAY_TIME,
"-366 11:11:11.111");
}
@Test
public void testLiteral()
{
assertFunction("TIMESTAMP '2013-03-30 01:05'", TIMESTAMP, sqlTimestampOf(2013, 3, 30, 1, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2013-03-30 02:05'", TIMESTAMP, sqlTimestampOf(2013, 3, 30, 2, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2013-03-30 03:05'", TIMESTAMP, sqlTimestampOf(2013, 3, 30, 3, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-01-22 03:04:05.321'", TIMESTAMP, sqlTimestampOf(2001, 1, 22, 3, 4, 5, 321, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-01-22 03:04:05'", TIMESTAMP, sqlTimestampOf(2001, 1, 22, 3, 4, 5, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-01-22 03:04'", TIMESTAMP, sqlTimestampOf(2001, 1, 22, 3, 4, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-01-22'", TIMESTAMP, sqlTimestampOf(2001, 1, 22, 0, 0, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-1-2 3:4:5.321'", TIMESTAMP, sqlTimestampOf(2001, 1, 2, 3, 4, 5, 321, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-1-2 3:4:5'", TIMESTAMP, sqlTimestampOf(2001, 1, 2, 3, 4, 5, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-1-2 3:4'", TIMESTAMP, sqlTimestampOf(2001, 1, 2, 3, 4, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("TIMESTAMP '2001-1-2'", TIMESTAMP, sqlTimestampOf(2001, 1, 2, 0, 0, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertInvalidFunction("TIMESTAMP 'text'", SemanticErrorCode.INVALID_LITERAL, "line 1:1: 'text' is not a valid timestamp literal");
}
@Test
public void testEqual()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' = TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' = TIMESTAMP '2001-1-22'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' = TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' = TIMESTAMP '2001-1-11'", BOOLEAN, false);
}
@Test
public void testNotEqual()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' <> TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' <> TIMESTAMP '2001-1-11'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' <> TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' <> TIMESTAMP '2001-1-22'", BOOLEAN, false);
}
@Test
public void testLessThan()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' < TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' < TIMESTAMP '2001-1-23'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' < TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' < TIMESTAMP '2001-1-22 03:04:05'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' < TIMESTAMP '2001-1-22'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' < TIMESTAMP '2001-1-20'", BOOLEAN, false);
}
@Test
public void testLessThanOrEqual()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' <= TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' <= TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' <= TIMESTAMP '2001-1-23'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' <= TIMESTAMP '2001-1-22'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' <= TIMESTAMP '2001-1-22 03:04:05'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' <= TIMESTAMP '2001-1-20'", BOOLEAN, false);
}
@Test
public void testGreaterThan()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' > TIMESTAMP '2001-1-22 03:04:05.111'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' > TIMESTAMP '2001-1-11'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' > TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' > TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' > TIMESTAMP '2001-1-22'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' > TIMESTAMP '2001-1-23'", BOOLEAN, false);
}
@Test
public void testGreaterThanOrEqual()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' >= TIMESTAMP '2001-1-22 03:04:05.111'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' >= TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' >= TIMESTAMP '2001-1-11'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22' >= TIMESTAMP '2001-1-22'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' >= TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22' >= TIMESTAMP '2001-1-23'", BOOLEAN, false);
}
@Test
public void testBetween()
{
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.111' and TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.321' and TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.111' and TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.321' and TIMESTAMP '2001-1-22 03:04:05.321'", BOOLEAN, true);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.322' and TIMESTAMP '2001-1-22 03:04:05.333'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.311' and TIMESTAMP '2001-1-22 03:04:05.312'", BOOLEAN, false);
assertFunction("TIMESTAMP '2001-1-22 03:04:05.321' between TIMESTAMP '2001-1-22 03:04:05.333' and TIMESTAMP '2001-1-22 03:04:05.111'", BOOLEAN, false);
}
@Test
public void testCastToDate()
{
long millis = new DateTime(2001, 1, 22, 0, 0, UTC).getMillis();
assertFunction("cast(TIMESTAMP '2001-1-22 03:04:05.321' as date)", DATE, new SqlDate((int) TimeUnit.MILLISECONDS.toDays(millis)));
}
@Test
public void testCastToTime()
{
assertFunction("cast(TIMESTAMP '2001-1-22 03:04:05.321' as time)", TIME, sqlTimeOf(3, 4, 5, 321, session));
}
@Test
public void testCastToTimeWithTimeZone()
{
assertFunction("cast(TIMESTAMP '2001-1-22 03:04:05.321' as time with time zone)",
TIME_WITH_TIME_ZONE,
new SqlTimeWithTimeZone(new DateTime(1970, 1, 1, 3, 4, 5, 321, DATE_TIME_ZONE).getMillis(), TIME_ZONE_KEY));
functionAssertions.assertFunctionString("cast(TIMESTAMP '2001-1-22 03:04:05.321' as time with time zone)",
TIME_WITH_TIME_ZONE,
"03:04:05.321 Europe/Berlin");
}
@Test
public void testCastToTimestampWithTimeZone()
{
assertFunction("cast(TIMESTAMP '2001-1-22 03:04:05.321' as timestamp with time zone)",
TIMESTAMP_WITH_TIME_ZONE,
new SqlTimestampWithTimeZone(new DateTime(2001, 1, 22, 3, 4, 5, 321, DATE_TIME_ZONE).getMillis(), DATE_TIME_ZONE.toTimeZone()));
functionAssertions.assertFunctionString("cast(TIMESTAMP '2001-1-22 03:04:05.321' as timestamp with time zone)",
TIMESTAMP_WITH_TIME_ZONE,
"2001-01-22 03:04:05.321 Europe/Berlin");
}
@Test
public void testCastToSlice()
{
assertFunction("cast(TIMESTAMP '2001-1-22 03:04:05.321' as varchar)", VARCHAR, "2001-01-22 03:04:05.321");
assertFunction("cast(TIMESTAMP '2001-1-22 03:04:05' as varchar)", VARCHAR, "2001-01-22 03:04:05.000");
assertFunction("cast(TIMESTAMP '2001-1-22 03:04' as varchar)", VARCHAR, "2001-01-22 03:04:00.000");
assertFunction("cast(TIMESTAMP '2001-1-22' as varchar)", VARCHAR, "2001-01-22 00:00:00.000");
}
@Test
public void testCastFromSlice()
{
assertFunction("cast('2001-1-22 03:04:05.321' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 3, 4, 5, 321, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("cast('2001-1-22 03:04:05' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 3, 4, 5, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("cast('2001-1-22 03:04' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 3, 4, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("cast('2001-1-22' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 0, 0, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("cast('\n\t 2001-1-22 03:04:05.321' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 3, 4, 5, 321, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("cast('2001-1-22 03:04:05.321 \t\n' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 3, 4, 5, 321, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("cast('\n\t 2001-1-22 03:04:05.321 \t\n' as timestamp)",
TIMESTAMP,
sqlTimestampOf(2001, 1, 22, 3, 4, 5, 321, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
}
@Test
public void testGreatest()
{
assertFunction("greatest(TIMESTAMP '2013-03-30 01:05', TIMESTAMP '2012-03-30 01:05')",
TIMESTAMP,
sqlTimestampOf(2013, 3, 30, 1, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("greatest(TIMESTAMP '2013-03-30 01:05', TIMESTAMP '2012-03-30 01:05', TIMESTAMP '2012-05-01 01:05')",
TIMESTAMP,
sqlTimestampOf(2013, 3, 30, 1, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
}
@Test
public void testLeast()
{
assertFunction("least(TIMESTAMP '2013-03-30 01:05', TIMESTAMP '2012-03-30 01:05')",
TIMESTAMP,
sqlTimestampOf(2012, 3, 30, 1, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
assertFunction("least(TIMESTAMP '2013-03-30 01:05', TIMESTAMP '2012-03-30 01:05', TIMESTAMP '2012-05-01 01:05')",
TIMESTAMP,
sqlTimestampOf(2012, 3, 30, 1, 5, 0, 0, DATE_TIME_ZONE, TIME_ZONE_KEY, session));
}
@Test
public void testIndeterminate()
{
assertOperator(INDETERMINATE, "cast(null as TIMESTAMP)", BOOLEAN, true);
assertOperator(INDETERMINATE, "TIMESTAMP '2012-03-30 01:05'", BOOLEAN, false);
}
}
| high | 0.516688 | 305 |
// Copyright (c) 2017 Massachusetts Institute of Technology
//
// 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.
`include "ProcConfig.bsv"
import Types::*;
import ProcTypes::*;
import Vector::*;
import ConfigReg::*;
import HasSpecBits::*;
import Ehr::*;
import GetPut::*;
import Assert::*;
typedef struct{
a data;
PhyRegs regs;
InstTag tag;
// speculation
SpecBits spec_bits;
Maybe#(SpecTag) spec_tag;
// scheduling
RegsReady regs_ready;
} ToReservationStation#(type a) deriving(Bits, Eq, FShow);
interface ReservationStation#(
numeric type size, numeric type setRegReadyNum, type a
);
method Action enq(ToReservationStation#(a) x);
method Bool canEnq;
method Action setRobEnqTime(InstTime t);
method ToReservationStation#(a) dispatchData;
method Action doDispatch;
interface Vector#(setRegReadyNum, Put#(Maybe#(PhyRIndx))) setRegReady;
// For count-based scheduling when there are multiple reservation stations
// for the same inst type. This method only takes effect when module
// parameter countValid is true.
method Bit#(TLog#(TAdd#(size, 1))) approximateCount;
// performance: count full cycles
method Bool isFull_ehrPort0;
interface SpeculationUpdate specUpdate;
endinterface
typedef Bit#(TAdd#(1, TLog#(NumInstTags))) VirtualInstTime;
module mkReservationStation#(Bool lazySched, Bool lazyEnq, Bool countValid)(
ReservationStation#(size, setRegReadyNum, a)
) provisos (
NumAlias#(regsReadyPortNum, TAdd#(1, setRegReadyNum)),
Alias#(idxT, Bit#(TLog#(size))),
Alias#(countT, Bit#(TLog#(TAdd#(size, 1)))),
Log#(TAdd#(1, size), TLog#(TAdd#(size, 1))),
Bits#(a, aSz), FShow#(a),
Add#(1, b__, size)
);
Integer valid_wrongSpec_port = 0;
Integer valid_dispatch_port = 0; // write valid
Integer valid_enq_port = 1; // write valid
Integer sb_wrongSpec_port = 0;
Integer sb_dispatch_port = 0;
Integer sb_enq_port = 0; // write spec_bits
Integer sb_correctSpec_port = 1; // write spec_bits
function Integer ready_set_port(Integer i) = i; // write regs_ready by each setRegReady ifc
Integer ready_enq_port = valueof(setRegReadyNum); // write regs_ready
Vector#(size, Ehr#(2,Bool)) valid <- replicateM(mkEhr(False));
Vector#(size, Reg#(a)) data <- replicateM(mkRegU);
Vector#(size, Reg#(PhyRegs)) regs <- replicateM(mkRegU);
Vector#(size, Reg#(InstTag)) tag <- replicateM(mkRegU);
Vector#(size, Reg#(Maybe#(SpecTag))) spec_tag <- replicateM(mkRegU);
Vector#(size, Ehr#(2, SpecBits)) spec_bits <- replicateM(mkEhr(?));
Vector#(size, Ehr#(regsReadyPortNum, RegsReady)) regs_ready <- replicateM(mkEhr(?));
// wrong spec conflict with enq and dispatch
RWire#(void) wrongSpec_enq_conflict <- mkRWire;
RWire#(void) wrongSpec_dispatch_conflict <- mkRWire;
// approximate count of valid entries
Reg#(countT) validEntryCount <- mkConfigReg(0);
if(countValid) begin
(* fire_when_enabled, no_implicit_conditions *)
rule countValidEntries;
validEntryCount <= pack(countElem(True, readVEhr(0, valid)));
endrule
end
// enq time in ROB, used as pivot to get virtual inst time (dispatch happens before ROB enq)
Wire#(InstTime) robEnqTime <- mkDWire(0);
// mapping to virtual inst time as follow:
// valid entry time t --> t < robEnqTime ? t + 2^log(NumInstTags) : t
function VirtualInstTime getVTime(InstTag instTag);
InstTime t = instTag.t;
return t < robEnqTime ? zeroExtend(t) + fromInteger(valueof(TExp#(TLog#(NumInstTags)))) : zeroExtend(t);
endfunction
Vector#(size, VirtualInstTime) vTime = map(getVTime, readVReg(tag));
// function to find the oldest entry (smaller virtual time) which satisfy certain constraint
function Maybe#(idxT) findOldest(Vector#(size, Bool) pred);
function idxT getOlder(idxT a, idxT b);
if(!pred[a]) begin
return b;
end
else if(!pred[b]) begin
return a;
end
else begin
return vTime[a] < vTime[b] ? a : b;
end
endfunction
Vector#(size, idxT) idxVec = genWith(fromInteger);
idxT idx = fold(getOlder, idxVec);
return pred[idx] ? Valid (idx) : Invalid;
endfunction
// search for row to dispatch, we do it lazily
// i.e. look at the EHR port 0 of ready bits, so there is no bypassing
staticAssert(lazySched, "Only support lazy schedule now");
Vector#(size, Wire#(Bool)) ready_wire <- replicateM(mkBypassWire);
(* fire_when_enabled, no_implicit_conditions *)
rule setReadyWire;
function Action setReady(Integer i);
action
ready_wire[i] <= allRegsReady(regs_ready[i][0]);
endaction
endfunction
Vector#(size, Integer) idxVec = genVector;
joinActions(map(setReady, idxVec));
endrule
function Bool get_ready(Wire#(Bool) r);
return r;
endfunction
Vector#(size, Bool) can_schedule = zipWith( \&& , readVEhr(valid_dispatch_port, valid), map(get_ready, ready_wire) );
// oldest index to dispatch
let can_schedule_index = findOldest(can_schedule);
// ifc to set reg ready
Vector#(setRegReadyNum, Put#(Maybe#(PhyRIndx))) setRegReadyIfc = ?;
for(Integer k = 0; k < valueof(setRegReadyNum); k = k+1) begin
setRegReadyIfc[k] = (interface Put;
method Action put(Maybe#(PhyRIndx) x);
Integer ehrPort = ready_set_port(k);
function Action setReady(Integer i);
action
// function to set ready for element i
// This compares Maybe types.
// If both are invalid, regs_ready.srcX must be True.
RegsReady new_regs_ready = regs_ready[i][ehrPort];
if (x == regs[i].src1) begin
new_regs_ready.src1 = True;
end
if (x == regs[i].src2) begin
new_regs_ready.src2 = True;
end
if (x == regs[i].src3) begin
new_regs_ready.src3 = True;
end
regs_ready[i][ehrPort] <= new_regs_ready;
endaction
endfunction
Vector#(size, Integer) idxVec = genVector;
joinActions(map(setReady, idxVec));
endmethod
endinterface);
end
// search to find enq slot
Maybe#(UInt#(TLog#(size))) enqP = ?;
function Bool entryInvalid(Bool v) = !v;
if(lazyEnq) begin
Wire#(Maybe#(UInt#(TLog#(size)))) enqP_wire <- mkBypassWire;
(* fire_when_enabled, no_implicit_conditions *)
rule setWireForEnq;
enqP_wire <= findIndex(entryInvalid, readVEhr(0, valid));
endrule
enqP = enqP_wire;
end
else begin
enqP = findIndex(entryInvalid, readVEhr(valid_enq_port, valid));
end
//rule debugRes(!isValid(enqP));
// $fdisplay(stdout, "cannot enqueue in the reservation station this cycle");
//endrule
method Action enq(ToReservationStation#(a) x) if (enqP matches tagged Valid .idx);
$display(" [mkReservationStationRow::_write] ", fshow(x));
valid[idx][valid_enq_port] <= True;
data[idx] <= x.data;
regs[idx] <= x.regs;
tag[idx] <= x.tag;
spec_tag[idx] <= x.spec_tag;
spec_bits[idx][sb_enq_port] <= x.spec_bits;
regs_ready[idx][ready_enq_port] <= x.regs_ready;
// conflict with wrong spec
wrongSpec_enq_conflict.wset(?);
endmethod
method Bool canEnq = isValid(enqP);
method Action setRobEnqTime(InstTime t);
robEnqTime <= t;
endmethod
method ToReservationStation#(a) dispatchData if (can_schedule_index matches tagged Valid .i);
return ToReservationStation{
data: data[i],
regs: regs[i],
tag: tag[i],
spec_bits: spec_bits[i][sb_dispatch_port],
spec_tag: spec_tag[i],
regs_ready: RegsReady { // must be all true
src1: True,
src2: True,
src3: True,
dst: True
}
};
endmethod
method Action doDispatch if (can_schedule_index matches tagged Valid .i);
valid[i][valid_dispatch_port] <= False;
// conflict with wrong spec
wrongSpec_dispatch_conflict.wset(?);
endmethod
method countT approximateCount;
return validEntryCount;
endmethod
interface setRegReady = setRegReadyIfc;
method Bool isFull_ehrPort0;
return readVEhr(0, valid) == replicate(True);
endmethod
interface SpeculationUpdate specUpdate;
method Action incorrectSpeculation(Bool kill_all, SpecTag x);
function Action wrongSpec(Integer i);
action
if(kill_all || spec_bits[i][sb_wrongSpec_port][x] == 1) begin
valid[i][valid_wrongSpec_port] <= False;
end
endaction
endfunction
Vector#(size, Integer) idxVec = genVector;
joinActions(map(wrongSpec, idxVec));
// conflict with enq, dispatch
wrongSpec_enq_conflict.wset(?);
wrongSpec_dispatch_conflict.wset(?);
endmethod
method Action correctSpeculation(SpecBits mask);
function Action correctSpec(Integer i);
action
spec_bits[i][sb_correctSpec_port] <= spec_bits[i][sb_correctSpec_port] & mask;
endaction
endfunction
Vector#(size, Integer) idxVec = genVector;
joinActions(map(correctSpec, idxVec));
endmethod
endinterface
endmodule
| high | 0.525781 | 306 |
--liquibase formatted sql
--changeset jhr:4
CREATE TABLE SITD.PLAYER_FEATURE
(
PLAYER CHAR(36) NOT NULL,
FEATURE VARCHAR(32) NOT NULL,
CONSTRAINT PLAYER_FEATURE_PK PRIMARY KEY (PLAYER, FEATURE)
); | high | 0.62789 | 307 |
-module(about_maps).
-export([reading_a_key/0,
adding_a_new_key/0,
updating_an_existing_key/0,
matching_the_interesting_bits/0
]).
reading_a_key() ->
Map = #{key => val},
val =:= maps:get(key, Map).
adding_a_new_key() ->
Map = #{key1 => val1},
NextMap = Map#{key2 => val2},
val2 =:= maps:get(key2, NextMap).
updating_an_existing_key() ->
Map = #{key => val1},
NextMap = Map#{key := val2},
val2 =:= maps:get(key, NextMap).
matching_the_interesting_bits() ->
Map = #{apple => 0.79, banana => 0.59},
#{apple := ApplePrice} = Map,
0.79 =:= ApplePrice.
| high | 0.413514 | 308 |
('/home/sam-sepiol/OS/OS PROJECT/dist/sudoku',
True,
False,
False,
'sudoku.ico',
None,
False,
False,
None,
True,
'sudoku.pkg',
[('PYZ-00.pyz',
'/home/sam-sepiol/OS/OS PROJECT/build/sudoku/PYZ-00.pyz',
'PYZ'),
('struct',
'/home/sam-sepiol/OS/OS PROJECT/build/sudoku/localpycos/struct.pyo',
'PYMODULE'),
('pyimod01_os_path',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/loader/pyimod01_os_path.pyc',
'PYMODULE'),
('pyimod02_archive',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/loader/pyimod02_archive.pyc',
'PYMODULE'),
('pyimod03_importers',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/loader/pyimod03_importers.pyc',
'PYMODULE'),
('pyiboot01_bootstrap',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/loader/pyiboot01_bootstrap.py',
'PYSOURCE'),
('pyi_rth_multiprocessing',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py',
'PYSOURCE'),
('pyi_rth_pkgres',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgres.py',
'PYSOURCE'),
('gui', '/home/sam-sepiol/OS/OS PROJECT/gui.py', 'PYSOURCE'),
('libexpat.so.1', '/lib/x86_64-linux-gnu/libexpat.so.1', 'BINARY'),
('libz.so.1', '/lib/x86_64-linux-gnu/libz.so.1', 'BINARY'),
('_ctypes',
'/usr/lib/python3.8/lib-dynload/_ctypes.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_ssl',
'/usr/lib/python3.8/lib-dynload/_ssl.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_asyncio',
'/usr/lib/python3.8/lib-dynload/_asyncio.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_contextvars',
'/usr/lib/python3.8/lib-dynload/_contextvars.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_queue',
'/usr/lib/python3.8/lib-dynload/_queue.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('mmap',
'/usr/lib/python3.8/lib-dynload/mmap.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_posixshmem',
'/usr/lib/python3.8/lib-dynload/_posixshmem.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_multiprocessing',
'/usr/lib/python3.8/lib-dynload/_multiprocessing.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('termios',
'/usr/lib/python3.8/lib-dynload/termios.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_decimal',
'/usr/lib/python3.8/lib-dynload/_decimal.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_hashlib',
'/usr/lib/python3.8/lib-dynload/_hashlib.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_uuid',
'/usr/lib/python3.8/lib-dynload/_uuid.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('resource',
'/usr/lib/python3.8/lib-dynload/resource.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_lzma',
'/usr/lib/python3.8/lib-dynload/_lzma.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_bz2',
'/usr/lib/python3.8/lib-dynload/_bz2.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('readline',
'/usr/lib/python3.8/lib-dynload/readline.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_opcode',
'/usr/lib/python3.8/lib-dynload/_opcode.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_multibytecodec',
'/usr/lib/python3.8/lib-dynload/_multibytecodec.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_codecs_kr',
'/usr/lib/python3.8/lib-dynload/_codecs_kr.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_codecs_jp',
'/usr/lib/python3.8/lib-dynload/_codecs_jp.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_codecs_cn',
'/usr/lib/python3.8/lib-dynload/_codecs_cn.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_codecs_iso2022',
'/usr/lib/python3.8/lib-dynload/_codecs_iso2022.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_codecs_tw',
'/usr/lib/python3.8/lib-dynload/_codecs_tw.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_codecs_hk',
'/usr/lib/python3.8/lib-dynload/_codecs_hk.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_json',
'/usr/lib/python3.8/lib-dynload/_json.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('_curses',
'/usr/lib/python3.8/lib-dynload/_curses.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.core._multiarray_tests',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/core/_multiarray_tests.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.core._multiarray_umath',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/core/_multiarray_umath.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.linalg.lapack_lite',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/linalg/lapack_lite.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random.mtrand',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/mtrand.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._sfc64',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_sfc64.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._philox',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_philox.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._pcg64',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_pcg64.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._mt19937',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_mt19937.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random.bit_generator',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/bit_generator.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._generator',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_generator.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._bounded_integers',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_bounded_integers.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.random._common',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/random/_common.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.fft._pocketfft_internal',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/fft/_pocketfft_internal.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('numpy.linalg._umath_linalg',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/linalg/_umath_linalg.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.imageext',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/imageext.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.fastevent',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/fastevent.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.scrap',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/scrap.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.mixer',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/mixer.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.mixer_music',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/mixer_music.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.font',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/font.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame._freetype',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/_freetype.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.transform',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/transform.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.time',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/time.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.pixelarray',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/pixelarray.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.mask',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/mask.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.surface',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/surface.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.pixelcopy',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/pixelcopy.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.mouse',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/mouse.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.key',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/key.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.joystick',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/joystick.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.image',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/image.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.event',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/event.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.draw',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/draw.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.display',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/display.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.math',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/math.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.bufferproxy',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/bufferproxy.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.color',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/color.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.surflock',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/surflock.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.rwobject',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/rwobject.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.rect',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/rect.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.constants',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/constants.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('pygame.base',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/base.cpython-38-x86_64-linux-gnu.so',
'EXTENSION'),
('libffi.so.7', '/lib/x86_64-linux-gnu/libffi.so.7', 'BINARY'),
('libcrypto.so.1.1', '/lib/x86_64-linux-gnu/libcrypto.so.1.1', 'BINARY'),
('libssl.so.1.1', '/lib/x86_64-linux-gnu/libssl.so.1.1', 'BINARY'),
('libmpdec.so.2', '/lib/x86_64-linux-gnu/libmpdec.so.2', 'BINARY'),
('libuuid.so.1', '/lib/x86_64-linux-gnu/libuuid.so.1', 'BINARY'),
('liblzma.so.5', '/lib/x86_64-linux-gnu/liblzma.so.5', 'BINARY'),
('libbz2.so.1.0', '/lib/x86_64-linux-gnu/libbz2.so.1.0', 'BINARY'),
('libtinfo.so.6', '/lib/x86_64-linux-gnu/libtinfo.so.6', 'BINARY'),
('libreadline.so.8', '/lib/x86_64-linux-gnu/libreadline.so.8', 'BINARY'),
('libncursesw.so.6', '/lib/x86_64-linux-gnu/libncursesw.so.6', 'BINARY'),
('libgfortran-2e0d59d6.so.5.0.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/core/../../numpy.libs/libgfortran-2e0d59d6.so.5.0.0',
'BINARY'),
('libz-eb09ad1d.so.1.2.3',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/core/../../numpy.libs/libz-eb09ad1d.so.1.2.3',
'BINARY'),
('libquadmath-2d0c479f.so.0.0.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/core/../../numpy.libs/libquadmath-2d0c479f.so.0.0.0',
'BINARY'),
('libgcc_s.so.1', '/lib/x86_64-linux-gnu/libgcc_s.so.1', 'BINARY'),
('libopenblasp-r0-ae94cfde.3.9.dev.so',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/numpy/core/../../numpy.libs/libopenblasp-r0-ae94cfde.3.9.dev.so',
'BINARY'),
('libz-a147dcb0.so.1.2.3',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libz-a147dcb0.so.1.2.3',
'BINARY'),
('libSDL2_image-2-4bd2d50c.0.so.0.2.3',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libSDL2_image-2-4bd2d50c.0.so.0.2.3',
'BINARY'),
('libSDL2-2-a810f3c1.0.so.0.12.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libSDL2-2-a810f3c1.0.so.0.12.0',
'BINARY'),
('libjpeg-bd53fca1.so.62.0.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libjpeg-bd53fca1.so.62.0.0',
'BINARY'),
('libtiff-97e44e95.so.3.8.2',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libtiff-97e44e95.so.3.8.2',
'BINARY'),
('libpng16-b14e7f97.so.16.37.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libpng16-b14e7f97.so.16.37.0',
'BINARY'),
('libwebp-582c46b3.so.7.1.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libwebp-582c46b3.so.7.1.0',
'BINARY'),
('libXau.so.6', '/lib/x86_64-linux-gnu/libXau.so.6', 'BINARY'),
('libXdmcp.so.6', '/lib/x86_64-linux-gnu/libXdmcp.so.6', 'BINARY'),
('libX11.so.6', '/lib/x86_64-linux-gnu/libX11.so.6', 'BINARY'),
('libbsd.so.0', '/lib/x86_64-linux-gnu/libbsd.so.0', 'BINARY'),
('libvorbis-205f0f59.so.0.4.8',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libvorbis-205f0f59.so.0.4.8',
'BINARY'),
('libSDL2_mixer-2-ee256d43.0.so.0.2.2',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libSDL2_mixer-2-ee256d43.0.so.0.2.2',
'BINARY'),
('libvorbisfile-f207f3a6.so.3.3.7',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libvorbisfile-f207f3a6.so.3.3.7',
'BINARY'),
('libogg-b51fbe74.so.0.8.4',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libogg-b51fbe74.so.0.8.4',
'BINARY'),
('libmikmod-fabcac29.so.2.0.4',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libmikmod-fabcac29.so.2.0.4',
'BINARY'),
('libFLAC-bf6d1292.so.8.3.0',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libFLAC-bf6d1292.so.8.3.0',
'BINARY'),
('libSDL2_ttf-2-9c5a5e5f.0.so.0.14.1',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libSDL2_ttf-2-9c5a5e5f.0.so.0.14.1',
'BINARY'),
('libfreetype-2d39c124.so.6.17.1',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/../pygame.libs/libfreetype-2d39c124.so.6.17.1',
'BINARY'),
('libpython3.8.so.1.0',
'/lib/x86_64-linux-gnu/libpython3.8.so.1.0',
'BINARY'),
('base_library.zip',
'/home/sam-sepiol/OS/OS PROJECT/build/sudoku/base_library.zip',
'DATA'),
('lib/python3.8/config-3.8-x86_64-linux-gnu/Makefile',
'/usr/lib/python3.8/config-3.8-x86_64-linux-gnu/Makefile',
'DATA'),
('pygame/freesansbold.ttf',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/freesansbold.ttf',
'DATA'),
('include/python3.8/pyconfig.h', '/usr/include/python3.8/pyconfig.h', 'DATA'),
('pygame/pygame_icon.bmp',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/pygame/pygame_icon.bmp',
'DATA')],
[],
False,
False,
1607265551,
[('run',
'/home/sam-sepiol/OS/OS '
'PROJECT/pygame/lib/python3.8/site-packages/PyInstaller/bootloader/Linux-64bit/run',
'EXECUTABLE')])
| low | 0.801828 | 309 |
Assuming your age is 10 and you name is Bart, the greeting could be constructed as follows:
age = 10
name = 'Bart'
greeting = "Hello! My name is #{name} and I am #{age} years old."
| low | 0.346635 | 310 |
(ns overtone.studio.inst
(:refer-clojure :exclude [Inst])
(:use [overtone.sc defaults bindings server synth ugens envelope node bus dyn-vars]
[overtone.sc.machinery synthdef]
[overtone.studio core mixer fx]
[overtone.helpers lib]
[overtone.libs event])
(:require [clojure.pprint]
[overtone.sc.protocols :as protocols]
[overtone.sc.util :refer [id-mapper]]
[overtone.sc.machinery.server.comms :refer [with-server-sync]] ))
(defonce ^{:private true} __RECORDS__
(do
(defrecord-ifn Inst [name params args sdef
group instance-group fx-group
mixer bus fx-chain
volume pan
n-chans]
(fn [this & args]
(apply synth-player sdef params this [:tail instance-group] args))
to-sc-id*
(to-sc-id [_] (to-sc-id instance-group)))))
(derive Inst :overtone.sc.node/node)
(def DEFAULT-VOLUME 1.0)
(def DEFAULT-PAN 0.0)
(defonce __MIXER-SYNTHS__
(do
(defsynth mono-inst-mixer
[in-bus 10
out-bus 0
volume DEFAULT-VOLUME
pan DEFAULT-PAN]
(let [snd (in in-bus)]
(out out-bus (pan2 snd pan volume))))
(defsynth stereo-inst-mixer
[in-bus 10
out-bus 0
volume DEFAULT-VOLUME
pan DEFAULT-PAN]
(let [snd (in in-bus 2)
sndl (select 0 snd)
sndr (select 1 snd)]
(out out-bus (balance2 sndl sndr pan volume))))))
(defn inst-mixer
"Instantiate a mono or stereo inst-mixer synth."
[n-chans & args]
(if (> n-chans 1)
(apply stereo-inst-mixer args)
(apply mono-inst-mixer args)))
(defn inst-channels
"Internal fn used for multimethod dispatch on Insts."
[inst & args]
(let [n-chans (:n-chans inst)]
(if (> n-chans 1) :stereo :mono)))
(defn inst-volume!
"Control the volume of a single instrument."
[inst vol]
(ensure-node-active! inst)
(ctl (:mixer inst) :volume vol)
(reset! (:volume inst) vol))
(defn inst-pan!
"Control the pan setting of a single instrument."
[inst pan]
(ensure-node-active! inst)
(ctl (:mixer inst) :pan pan)
(reset! (:pan inst) pan))
(defmulti inst-fx!
"Append an effect to an instrument channel. Returns a SynthNode or a
vector of SynthNodes representing the effect instance."
inst-channels)
(defmethod inst-fx! :mono
[inst fx]
(ensure-node-active! inst)
(let [fx-group (:fx-group inst)
bus (:bus inst)
fx-id (fx [:tail fx-group] :bus bus)]
fx-id))
(defmethod inst-fx! :stereo
[inst fx]
(ensure-node-active! inst)
(let [fx-group (:fx-group inst)
bus-l (to-sc-id (:bus inst))
bus-r (inc bus-l)
fx-ids [(fx [:tail fx-group] :bus bus-l)
(fx [:tail fx-group] :bus bus-r)]]
fx-ids))
(defn clear-fx
[inst]
(ensure-node-active! inst)
(group-clear (:fx-group inst))
:clear)
(defmacro pre-inst
[& args]
(let [[sname params param-proxies ugen-form] (normalize-synth-args args)]
`(let [~@param-proxies]
(binding [*ugens* []
*constants* #{}]
(with-overloaded-ugens
(let [form# ~@ugen-form
;; form# can be a map, or a sequence of maps. We use
;; `sequence?` because `coll?` applies to maps (which
;; are not sequential) and `seq?` does not apply to
;; vectors (which are sequential).
n-chans# (if (sequential? form#) (count form#) 1)
inst-bus# (or (:bus (get (:instruments @studio*) ~sname))
(audio-bus n-chans#))
[ugens# constants#] (gather-ugens-and-constants (out inst-bus# form#))
ugens# (topological-sort-ugens ugens#)
main-tree# (set ugens#)
side-tree# (filter #(not (main-tree# %)) *ugens*)
ugens# (concat ugens# side-tree#)
constants# (into [] (set (concat constants# *constants*)))]
[~sname
~params
ugens#
constants#
n-chans#
inst-bus#]))))))
(defn instrument?
"Returns true if o is an instrument, false otherwise"
[o]
(= overtone.studio.inst.Inst (type o)))
(defmacro inst
[sname & args]
(ensure-connected!)
`(let [[sname# params# ugens# constants# n-chans# inst-bus#] (pre-inst ~sname ~@args)
new-inst# (get (:instruments @studio*) sname#)
container-group# (or (:group new-inst#)
(with-server-sync
#(group (str "Inst " sname# " Container")
:tail (:instrument-group @studio*))
"whilst creating an inst container group"))
instance-group# (or (:instance-group new-inst#)
(with-server-sync
#(group (str "Inst " sname#)
:head container-group#)
"whilst creating an inst instance group"))
fx-group# (or (:fx-group new-inst#)
(with-server-sync
#(group (str "Inst " sname# " FX")
:tail container-group#)
"whilst creating an inst fx group"))
imixer# (or (:mixer new-inst#)
(inst-mixer n-chans#
[:tail container-group#]
:in-bus inst-bus#))
sdef# (synthdef sname# params# ugens# constants#)
arg-names# (map :name params#)
params-with-vals# (map #(assoc % :value (atom (:default %))) params#)
fx-chain# []
volume# (atom DEFAULT-VOLUME)
pan# (atom DEFAULT-PAN)
inst# (with-meta
(Inst. sname# params-with-vals# arg-names# sdef#
container-group# instance-group# fx-group#
imixer# inst-bus# fx-chain#
volume# pan#
n-chans#
)
{:overtone.helpers.lib/to-string #(str (name (:type %)) ":" (:name %))})]
(load-synthdef sdef#)
(add-instrument inst#)
(event :new-inst :inst inst#)
inst#))
(defmacro definst
"Define an instrument and return a player function. The instrument
definition will be loaded immediately, and a :new-inst event will be
emitted. Expects a name, an optional doc-string, a vector of
instrument params, and a ugen-form as its arguments.
Instrument parameters are a vector of name/value pairs, for example:
(definst inst-name [param0 value0 param1 value1 param2 value2] ...)
The returned player function takes any number of positional
arguments, followed by any number of keyword arguments. For example,
all of the following are equivalent:
(inst-name 0 1 2)
(inst-name 0 1 :param2 2)
(inst-name :param1 1 :param0 0 :param2 2)
Omitted parameters are given their default value from the
instrument's parameter list.
A doc string may also be included between the instrument's name and
parameter list:
(definst lucille
\"What's that Lucille?\"
[] ...)
Instruments are similar to basic synths but still differ in a number
of notable ways:
* Instruments will automatically wrap the body of code given in an
out ugen. You do not need to include an out ugen yourself. For
example:
(definst foo [freq 440]
(sin-osc freq))
is similar to:
(defsynth foo [freq 440]
(out 0 (sin-osc freq)))
* Instruments are limited to 1 or 2 channels. Instruments with more
than 2 channels are allowed, but additional channels will not be
audible. Use the mix and pan2 ugens to combine multiple channels
within your inst if needed. For example:
(definst bar
[f1 100 f2 200 f3 300 f4 400]
(mix (pan2 (sin-osc [f1 f2 f3 f4]) [-1 1 -1 1])))
* Each instrument is assigned its own group which all instances will
automatically be placed in. This allows you to control all of an
instrument's running synths with one command:
(ctl inst-name :param0 val0 :param1 val1)
You may also kill all of an instrument's running synths:
(kill inst-name)
* A bus and bus-mixer are created for each instrument. This allows
you to control the volume or pan of the instrument group with one
command:
(inst-pan! bar -1) ;pan hard left.
(inst-volume! bar 0.5) ;half the volume.
For a stereo inst, you can control left and right pan or volume
separately by passing an additional arg:
(inst-pan! bar 1 -1) ;ch1 right, ch2 left.
(inst-volume! bar 0 1) ;mute ch1.
* Each instrument has an fx-chain to which you can add any number of
'fx synths' using the inst-fx function.
"
{:arglists '([name doc-string? params ugen-form])}
[i-name & inst-form]
(let [[i-name params ugen-form] (synth-form i-name inst-form)
i-name (with-meta i-name (merge (meta i-name) {:type ::instrument}))]
`(def ~i-name (inst ~i-name ~params ~ugen-form))))
(defmethod clojure.pprint/simple-dispatch Inst [ins]
(println (format "#<instrument: %s>" (:name ins))))
(defmethod print-method Inst [ins ^java.io.Writer w]
(.write w (format "#<instrument: %s>" (:name ins))))
(defmethod print-method ::instrument [ins ^java.io.Writer w]
(let [info (meta ins)]
(.write w (format "#<instrument: %s>" (:name info)))))
(defn load-instruments []
(doseq [synth (filter #(synthdef? %1)
(map #(var-get %1)
(vals (ns-publics 'overtone.instrument))))]
(load-synthdef synth)))
(defn- inst-block-until-ready*
[inst]
(when (block-node-until-ready?)
(doseq [sub-node [(:fx-group inst)
(:group inst)
(:instance-group inst)
(:mixer inst)]]
(node-block-until-ready sub-node))))
(defn- inst-status*
[inst]
(let [sub-nodes [(:fx-group inst)
(:group inst)
(:instance-group inst)
(:mixer inst)]]
(cond
(some #(= :loading @(:status %)) sub-nodes) :loading
(some #(= :destroyed @(:status %)) sub-nodes) :destroyed
(some #(= :paused @(:status %)) sub-nodes) :paused
(every? #(= :live @(:status %)) sub-nodes) :live
:else (throw (Exception. "Unknown instrument sub-node state: "
(with-out-str (doseq [n sub-nodes] (pr n))))))))
(extend Inst
ISynthNode
{:node-free node-free*
:node-pause node-pause*
:node-start node-start*
:node-place node-place*}
IControllableNode
{:node-control node-control*
:node-control-range node-control-range*
:node-map-controls node-map-controls*
:node-map-n-controls node-map-n-controls*}
protocols/IKillable
{:kill* (fn [this] (group-deep-clear (:instance-group this)))}
ISynthNodeStatus
{:node-status inst-status*
:node-block-until-ready inst-block-until-ready*})
| high | 0.721275 | 312 |
ARG BUILD_ARCH
FROM blakeblackshear/frigate:0.8.1-${BUILD_ARCH}
| low | 0.859169 | 313 |
(ns devtools.format
(:require-macros [devtools.oops :refer [oget]])
(:require [devtools.context :as context]))
; WARNING this namespace is here for legacy reasons, it will be removed in future!
; ---------------------------------------------------------------------------------------------------------------------------
; PROTOCOL SUPPORT
(defprotocol ^:deprecated IDevtoolsFormat ; use IFormat instead
(-header [value])
(-has-body [value])
(-body [value]))
; -- helpers ----------------------------------------------------------------------------------------------------------------
(def ^:dynamic *setup-done*)
(defn setup! []
(when-not *setup-done*
(set! *setup-done* true)
; note: we cannote require devtools.formatters.templating or .markup because that would lead to circular requires
(def make-template-fn (oget (context/get-root) "devtools" "formatters" "templating" "make_template"))
(def make-group-fn (oget (context/get-root) "devtools" "formatters" "templating" "make_group"))
(def make-reference-fn (oget (context/get-root) "devtools" "formatters" "templating" "make_reference"))
(def make-surrogate-fn (oget (context/get-root) "devtools" "formatters" "templating" "make_surrogate"))
(def render-markup-fn (oget (context/get-root) "devtools" "formatters" "templating" "render_markup"))
(def <header>-fn (oget (context/get-root) "devtools" "formatters" "markup" "_LT_header_GT_"))
(def <standard-body>-fn (oget (context/get-root) "devtools" "formatters" "markup" "_LT_standard_body_GT_"))
(assert make-template-fn)
(assert make-group-fn)
(assert make-reference-fn)
(assert make-surrogate-fn)
(assert render-markup-fn)
(assert <header>-fn)
(assert <standard-body>-fn)))
(defn- render-markup [& args]
(setup!)
(apply render-markup-fn args))
; ---------------------------------------------------------------------------------------------------------------------------
; deprecated functionality, implemented for easier transition from v0.7.x to v0.8
(defn ^:deprecated make-template [& args]
(setup!)
(apply make-template-fn args))
(defn ^:deprecated make-group [& args]
(setup!)
(apply make-group-fn args))
(defn ^:deprecated make-surrogate [& args]
(setup!)
(apply make-surrogate-fn args))
(defn ^:deprecated template [& args]
(setup!)
(apply make-template-fn args))
(defn ^:deprecated group [& args]
(setup!)
(apply make-group-fn args))
(defn ^:deprecated surrogate [& args]
(setup!)
(apply make-surrogate-fn args))
(defn ^:deprecated reference [object & [state-override]]
(setup!)
(apply make-reference-fn [object #(merge % state-override)]))
(defn ^:deprecated standard-reference [target]
(setup!)
(make-template-fn :ol :standard-ol-style (make-template-fn :li :standard-li-style (make-reference-fn target))))
(defn ^:deprecated build-header [& args]
(setup!)
(render-markup (apply <header>-fn args)))
(defn ^:deprecated standard-body-template [lines & rest]
(setup!)
(let [args (concat [(map (fn [x] [x]) lines)] rest)]
(render-markup (apply <standard-body>-fn args))))
| high | 0.65567 | 314 |
# Base class definitions used by the actual Adapter modules
$global:BaseClassDefinitions = @"
using System;
namespace ODataUtils
{
public class TypeProperty
{
public String Name;
// OData Type Name, e.g. Edm.Int32
public String TypeName;
public bool IsKey;
public bool IsMandatory;
public bool? IsNullable;
}
public class NavigationProperty
{
public String Name;
public String FromRole;
public String ToRole;
public String AssociationNamespace;
public String AssociationName;
}
public class EntityTypeBase
{
public String Namespace;
public String Name;
public TypeProperty[] EntityProperties;
public bool IsEntity;
public EntityTypeBase BaseType;
}
public class AssociationType
{
public String Namespace;
public EntityTypeBase EndType1;
public String Multiplicity1;
public String NavPropertyName1;
public EntityTypeBase EndType2;
public String Multiplicity2;
public String NavPropertyName2;
}
public class EntitySet
{
public String Namespace;
public String Name;
public EntityTypeBase Type;
}
public class AssociationSet
{
public String Namespace;
public String Name;
public AssociationType Type;
}
public class Action
{
public String Namespace;
public String Verb;
public EntitySet EntitySet;
public Boolean IsSideEffecting;
public Boolean IsBindable;
public Boolean IsSingleInstance;
public TypeProperty[] Parameters;
}
public class MetadataBase
{
// Desired destination namespace
public String Namespace;
}
public class CmdletParameter
{
public CmdletParameter()
{
}
public CmdletParameter(String type, String name)
{
this.Type = type;
this.Name = name;
this.Qualifiers = new String[] { "Parameter(ValueFromPipelineByPropertyName=`$true)" };
}
public String[] Qualifiers;
public String Type;
public String Name;
}
public class CmdletParameters
{
public CmdletParameter[] Parameters;
}
public class ReferentialConstraint
{
public String Property;
public String ReferencedProperty;
}
public class OnDelete
{
public String Action;
}
public class NavigationPropertyV4
{
public String Name;
public String Type;
public bool Nullable;
public String Partner;
public bool ContainsTarget;
public ReferentialConstraint[] ReferentialConstraints;
public OnDelete OnDelete;
}
public class NavigationPropertyBinding
{
public String Path;
public String Target;
}
public class EntityTypeV4 : EntityTypeBase
{
public String Alias;
public NavigationPropertyV4[] NavigationProperties;
public String BaseTypeStr;
}
public class SingletonType
{
public String Namespace;
public String Alias;
public String Name;
public String Type;
public NavigationPropertyBinding[] NavigationPropertyBindings;
}
public class EntitySetV4
{
public String Namespace;
public String Alias;
public String Name;
public EntityTypeV4 Type;
}
public class EnumMember
{
public String Name;
public String Value;
}
public class EnumType
{
public String Namespace;
public String Alias;
public String Name;
public String UnderlyingType;
public bool IsFlags;
public EnumMember[] Members;
}
public class ActionV4
{
public String Namespace;
public String Alias;
public String Name;
public String Action;
public EntitySetV4 EntitySet;
public TypeProperty[] Parameters;
}
public class FunctionV4
{
public String Namespace;
public String Alias;
public String Name;
public bool Function;
public String EntitySet;
public String ReturnType;
public Parameter[] Parameters;
}
public class Parameter
{
public String Name;
public String Type;
public bool Nullable;
}
public class ReferenceInclude
{
public String Namespace;
public String Alias;
}
public class Reference
{
public String Uri;
}
public class MetadataV4 : MetadataBase
{
public string ODataVersion;
public string Uri;
public string MetadataUri;
public string Alias;
public Reference[] References;
public string DefaultEntityContainerName;
public EntitySetV4[] EntitySets;
public EntityTypeV4[] EntityTypes;
public SingletonType[] SingletonTypes;
public EntityTypeV4[] ComplexTypes;
public EntityTypeV4[] TypeDefinitions;
public EnumType[] EnumTypes;
public ActionV4[] Actions;
public FunctionV4[] Functions;
}
public class ReferencedMetadata
{
public System.Collections.ArrayList References;
}
public class ODataEndpointProxyParameters
{
public String Uri;
public String MetadataUri;
public System.Management.Automation.PSCredential Credential;
public String OutputModule;
public bool Force;
public bool AllowClobber;
public bool AllowUnsecureConnection;
}
public class EntityType : EntityTypeBase
{
public NavigationProperty[] NavigationProperties;
}
public class Metadata : MetadataBase
{
public String DefaultEntityContainerName;
public EntitySet[] EntitySets;
public EntityType[] EntityTypes;
public EntityType[] ComplexTypes;
public AssociationSet[] Associations;
public Action[] Actions;
}
}
"@
#########################################################
# GetMetaData is a helper function used to fetch metadata
# from the specified file or web URL.
#########################################################
function GetMetaData
{
param
(
[string] $metaDataUri,
[System.Management.Automation.PSCmdlet] $callerPSCmdlet,
[PSCredential] $credential,
[Hashtable] $headers
)
# $metaDataUri is already validated at the cmdlet layer.
if($null -eq $callerPSCmdletl) { throw ($LocalizedData.ArguementNullError -f "PSCmdlet", "GetMetaData") }
Write-Verbose ($LocalizedData.VerboseReadingMetadata -f $metaDataUri)
try
{
$uri = [System.Uri]::new($metadataUri)
# By default, proxy generation is supported on secured Uri (i.e., https).
# However if the user trusts the unsecure http uri, then they can override
# the security check by specifying -AllowSecureConnection parameter during
# proxy generation.
if($uri.Scheme -eq "http" -and !$AllowUnsecureConnection.IsPresent)
{
$errorMessage = ($LocalizedData.AllowUnsecureConnectionMessage -f $callerPSCmdlet.MyInvocation.MyCommand.Name, $uri, "MetaDataUri")
$exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyUnSecureConnection" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $uri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
}
catch
{
$errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri)
$exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadataUriFormat" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $MetadataUri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
if($uri.IsFile)
{
if ($null -ne $credential)
{
$fileExists = Test-Path -Path $metaDataUri -PathType Leaf -Credential $credential -ErrorAction Stop
}
else
{
$fileExists = Test-Path -Path $metaDataUri -PathType Leaf -ErrorAction Stop
}
if($fileExists)
{
$metaData = Get-Content -Path $metaDataUri -ErrorAction Stop
}
else
{
$errorMessage = ($LocalizedData.MetadataUriDoesNotExist -f $MetadataUri)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataFileDoesNotExist" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
}
else
{
try
{
$cmdParams = @{'Uri'= $metaDataUri ; 'UseBasicParsing'=$true; 'ErrorAction'= 'Stop'}
if ($null -ne $credential)
{
$cmdParams.Add('Credential', $credential)
}
if ($null -ne $headers)
{
$cmdParams.Add('Headers', $headers)
}
$webResponse = Invoke-WebRequest @cmdParams
}
catch
{
$errorMessage = ($LocalizedData.MetadataUriDoesNotExist -f $MetadataUri)
$exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataUriDoesNotExist" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $MetadataUri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
if($null -ne $webResponse)
{
if ($webResponse.StatusCode -eq 200)
{
$metaData = $webResponse.Content
if ($null -eq $metadata)
{
$errorMessage = ($LocalizedData.EmptyMetadata -f $MetadataUri)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyMetadataIsEmpty" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
}
else
{
$errorMessage = ($LocalizedData.InvalidEndpointAddress -f $MetadataUri, $webResponse.StatusCode)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidEndpointAddress" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $null $MetadataUri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
}
}
if($null -ne $metaData)
{
try
{
[xml] $metadataXML = $metaData
}
catch
{
$errorMessage = ($LocalizedData.InValidMetadata -f $MetadataUri)
$exception = [System.InvalidOperationException]::new($errorMessage, $_.Exception)
$errorRecord = CreateErrorRecordHelper "ODataEndpointProxyInvalidMetadata" $null ([System.Management.Automation.ErrorCategory]::InvalidData) $exception $MetadataUri
$callerPSCmdlet.ThrowTerminatingError($errorRecord)
}
}
return $metadataXML
}
#########################################################
# VerifyMetadataHelper is a helper function used to
# validate if Error/Warning message has to be displayed
# during command collision.
#########################################################
function VerifyMetadataHelper
{
param
(
[string] $localizedDataErrorString,
[string] $localizedDataWarningString,
[string] $entitySetName,
[string] $currentCommandName,
[string] $metaDataUri,
[boolean] $allowClobber,
[System.Management.Automation.PSCmdlet] $callerPSCmdlet
)
if($null -eq $localizedDataErrorString) { throw ($LocalizedData.ArguementNullError -f "localizedDataErrorString", "VerifyMetadataHelper") }
if($null -eq $localizedDataWarningString) { throw ($LocalizedData.ArguementNullError -f "localizedDataWarningString", "VerifyMetadataHelper") }
if(!$allowClobber)
{
# Write Error message and skip current Entity Set.
$errorMessage = ($localizedDataErrorString -f $entitySetName, $currentCommandName)
$exception = [System.InvalidOperationException]::new($errorMessage)
$errorRecord = CreateErrorRecordHelper "ODataEndpointDefaultPropertyCollision" $null ([System.Management.Automation.ErrorCategory]::InvalidOperation) $exception $metaDataUri
$callerPSCmdlet.WriteError($errorRecord)
}
else
{
$warningMessage = ($localizedDataWarningString -f $entitySetName, $currentCommandName)
$callerPSCmdlet.WriteWarning($warningMessage)
}
}
#########################################################
# CreateErrorRecordHelper is a helper function used to
# create an error record.
#########################################################
function CreateErrorRecordHelper
{
param
(
[string] $errorId,
[string] $errorMessage,
[System.Management.Automation.ErrorCategory] $errorCategory,
[Exception] $exception,
[object] $targetObject
)
if($null -eq $exception)
{
$exception = New-Object System.IO.IOException $errorMessage
}
$errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject
return $errorRecord
}
#########################################################
# ProgressBarHelper is a helper function used to
# used to display progress message.
#########################################################
function ProgressBarHelper
{
param
(
[string] $cmdletName,
[string] $status,
[double] $previousSegmentWeight,
[double] $currentSegmentWeight,
[int] $totalNumberofEntries,
[int] $currentEntryCount
)
if($null -eq $cmdletName) { throw ($LocalizedData.ArguementNullError -f "CmdletName", "ProgressBarHelper") }
if($null -eq $status) { throw ($LocalizedData.ArguementNullError -f "Status", "ProgressBarHelper") }
if($currentEntryCount -gt 0 -and
$totalNumberofEntries -gt 0 -and
$previousSegmentWeight -ge 0 -and
$currentSegmentWeight -gt 0)
{
$entryDefaultWeight = $currentSegmentWeight/[double]$totalNumberofEntries
$percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount)
Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete
}
}
#########################################################
# Convert-ODataTypeToCLRType is a helper function used to
# Convert OData type to its CLR equivalent.
#########################################################
function Convert-ODataTypeToCLRType
{
param
(
[string] $typeName,
[Hashtable] $complexTypeMapping
)
if($null -eq $typeName) { throw ($LocalizedData.ArguementNullError -f "TypeName", "Convert-ODataTypeToCLRType ") }
switch ($typeName)
{
"Edm.Binary" {"Byte[]"}
"Edm.Boolean" {"Boolean"}
"Edm.Byte" {"Byte"}
"Edm.DateTime" {"DateTime"}
"Edm.Decimal" {"Decimal"}
"Edm.Double" {"Double"}
"Edm.Single" {"Single"}
"Edm.Guid" {"Guid"}
"Edm.Int16" {"Int16"}
"Edm.Int32" {"Int32"}
"Edm.Int64" {"Int64"}
"Edm.SByte" {"SByte"}
"Edm.String" {"String"}
"Edm.PropertyPath" {"String"}
"switch" {"switch"}
"Edm.DateTimeOffset" {"DateTimeOffset"}
default
{
if($null -ne $complexTypeMapping -and
$complexTypeMapping.Count -gt 0 -and
$complexTypeMapping.ContainsKey($typeName))
{
$typeName
}
else
{
$regex = "Collection\((.+)\)"
if ($typeName -match $regex)
{
$insideTypeName = Convert-ODataTypeToCLRType $Matches[1] $complexTypeMapping
"$insideTypeName[]"
}
else
{
"PSObject"
}
}
}
}
}
#########################################################
# SaveCDXMLHeader is a helper function used
# to save CDXML headers common to all
# PSODataUtils modules.
#########################################################
function SaveCDXMLHeader
{
param
(
[System.Xml.XmlWriter] $xmlWriter,
[string] $uri,
[string] $className,
[string] $defaultNoun,
[string] $cmdletAdapter
)
# $uri & $cmdletAdapter are already validated at the cmdlet layer.
if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLHeader") }
if($null -eq $defaultNoun) { throw ($LocalizedData.ArguementNullError -f "DefaultNoun", "SaveCDXMLHeader") }
if ($className -eq 'ServiceActions' -Or $cmdletAdapter -eq "NetworkControllerAdapter")
{
$entityName = ''
}
else
{
$entityName = $className
}
if ($uri[-1] -ne '/')
{
$fullName = "$uri/$entityName"
}
else
{
$fullName = "$uri$entityName"
}
$xmlWriter.Formatting = 'Indented'
$xmlWriter.Indentation = 2
$xmlWriter.IndentChar = ' '
$xmlWriter.WriteStartDocument()
$today=Get-Date
$xmlWriter.WriteComment("This module was autogenerated by PSODataUtils on $today.")
$xmlWriter.WriteStartElement('PowerShellMetadata')
$xmlWriter.WriteAttributeString('xmlns', 'http://schemas.microsoft.com/cmdlets-over-objects/2009/11')
$xmlWriter.WriteStartElement('Class')
$xmlWriter.WriteAttributeString('ClassName', $fullName)
$xmlWriter.WriteAttributeString('ClassVersion', '1.0.0')
$DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.ODataCmdletAdapter'
if ($CmdletAdapter -eq "NetworkControllerAdapter") {
$DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.NetworkControllerCmdletAdapter'
}
elseif ($CmdletAdapter -eq "ODataV4Adapter") {
$DotNetAdapter = 'Microsoft.PowerShell.Cmdletization.OData.ODataV4CmdletAdapter'
}
$xmlWriter.WriteAttributeString('CmdletAdapter', $DotNetAdapter + ', Microsoft.PowerShell.Cmdletization.OData, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
$xmlWriter.WriteElementString('Version', '1.0')
$xmlWriter.WriteElementString('DefaultNoun', $defaultNoun)
$xmlWriter
}
#########################################################
# SaveCDXMLFooter is a helper function used
# to save CDXML closing attributes corresponding
# to SaveCDXMLHeader function.
#########################################################
function SaveCDXMLFooter
{
param
(
[System.Xml.XmlWriter] $xmlWriter
)
if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "SaveCDXMLFooter") }
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()
}
#########################################################
# AddParametersNode is a helper function used
# to add parameters to the generated proxy cmdlet,
# based on mandatoryProperties and otherProperties.
# PrefixForKeys is used by associations to append a
# prefix to PowerShell parameter name.
#########################################################
function AddParametersNode
{
param
(
[Parameter(Mandatory=$true)]
[System.Xml.XmlWriter] $xmlWriter,
[ODataUtils.TypeProperty[]] $keyProperties,
[ODataUtils.TypeProperty[]] $mandatoryProperties,
[ODataUtils.TypeProperty[]] $otherProperties,
[string] $prefixForKeys,
[boolean] $addForceParameter,
[boolean] $addParametersElement,
[Hashtable] $complexTypeMapping
)
if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "AddParametersNode") }
if(($keyProperties.Length -gt 0) -or
($mandatoryProperties.Length -gt 0) -or
($otherProperties.Length -gt 0) -or
($addForceParameter))
{
if($addParametersElement)
{
$xmlWriter.WriteStartElement('Parameters')
}
$pos = 0
if ($null -ne $keyProperties)
{
$pos = AddParametersCDXML $xmlWriter $keyProperties $pos $true $prefixForKeys ":Key" $complexTypeMapping
}
if ($null -ne $mandatoryProperties)
{
$pos = AddParametersCDXML $xmlWriter $mandatoryProperties $pos $true $null $null $complexTypeMapping
}
if ($null -ne $otherProperties)
{
$pos = AddParametersCDXML $xmlWriter $otherProperties $pos $false $null $null $complexTypeMapping
}
if($addForceParameter)
{
$forceParameter = [ODataUtils.TypeProperty] @{
"Name" = "Force";
"TypeName" = "switch";
"IsNullable" = $false
}
$pos = AddParametersCDXML $xmlWriter $forceParameter $pos $false $null $null $complexTypeMapping
}
if($addParametersElement)
{
$xmlWriter.WriteEndElement()
}
}
}
#########################################################
# AddParametersCDXML is a helper function used
# to add Parameter node to CDXML based on properties.
# Prefix is appended to PS parameter names, used for
# associations. Suffix is appended to all parameter
# names, for ex. to differentiate keys. returns new $pos
#########################################################
function AddParametersCDXML
{
param
(
[Parameter(Mandatory=$true)]
[System.Xml.XmlWriter] $xmlWriter,
[ODataUtils.TypeProperty[]] $properties,
[Parameter(Mandatory=$true)]
[int] $pos,
[bool] $isMandatory,
[string] $prefix,
[string] $suffix,
[Hashtable] $complexTypeMapping
)
$properties | Where-Object { $null -ne $_ } | ForEach-Object {
$xmlWriter.WriteStartElement('Parameter')
$xmlWriter.WriteAttributeString('ParameterName', $_.Name + $suffix)
$xmlWriter.WriteStartElement('Type')
$PSTypeName = Convert-ODataTypeToCLRType $_.TypeName $complexTypeMapping
$xmlWriter.WriteAttributeString('PSType', $PSTypeName)
$xmlWriter.WriteEndElement()
$xmlWriter.WriteStartElement('CmdletParameterMetadata')
$xmlWriter.WriteAttributeString('PSName', $prefix + $_.Name)
$xmlWriter.WriteAttributeString('IsMandatory', ($isMandatory).ToString().ToLowerInvariant())
$xmlWriter.WriteAttributeString('Position', $pos)
if($isMandatory)
{
$xmlWriter.WriteAttributeString('ValueFromPipelineByPropertyName', 'true')
}
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndElement()
$pos++
}
$pos
}
#########################################################
# GenerateSetProxyCmdlet is a helper function used
# to generate Set-* proxy cmdlet. The proxy cmdlet is
# generated in the CDXML compliant format.
#########################################################
function GenerateSetProxyCmdlet
{
param
(
[System.XMl.XmlTextWriter] $xmlWriter,
[object[]] $keyProperties,
[object[]] $nonKeyProperties,
[Hashtable] $complexTypeMapping
)
# $cmdletAdapter is already validated at the cmdlet layer.
if($null -eq $xmlWriter) { throw ($LocalizedData.ArguementNullError -f "xmlWriter", "GenerateSetProxyCmdlet") }
$xmlWriter.WriteStartElement('Cmdlet')
$xmlWriter.WriteStartElement('CmdletMetadata')
$xmlWriter.WriteAttributeString('Verb', 'Set')
$xmlWriter.WriteAttributeString('DefaultCmdletParameterSet', 'Default')
$xmlWriter.WriteAttributeString('ConfirmImpact', 'Medium')
$xmlWriter.WriteEndElement()
$xmlWriter.WriteStartElement('Method')
$xmlWriter.WriteAttributeString('MethodName', 'Update')
$xmlWriter.WriteAttributeString('CmdletParameterSet', 'Default')
AddParametersNode $xmlWriter $keyProperties $null $nonKeyProperties $null $true $true $complexTypeMapping
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndElement()
}
| high | 0.459212 | 315 |
(**************************************************************************)
(* *)
(* Copyright 2012-2018 OCamlPro *)
(* Copyright 2012 INRIA *)
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
(* GNU Lesser General Public License version 2.1, with the special *)
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Process and job handling, with logs, termination status, etc. *)
(** The type of shell commands *)
type command
(** Builds a shell command for later execution.
@param env environment for the command
@param verbose force verbosity
@param name title, used to name log files, etc.
@param metadata additional info to log
@param dir CWD for the command
@param allow_stdin whether to forward stdin
@param stdout redirect stdout to the given file instead of the logs
@param text Short text that may be displayed in the status-line
@param command The command itself
@param args Command-line arguments *)
val command:
?env:string array ->
?verbose:bool ->
?name:string ->
?metadata:(string*string) list ->
?dir:string ->
?allow_stdin:bool ->
?stdout:string ->
?text:string ->
string ->
string list ->
command
val string_of_command: command -> string
val text_of_command: command -> string option
val is_verbose_command: command -> bool
(** Returns a label suitable for printing the summary of running commands. First
string is the topic (e.g. package), second the action (e.g. command name).
Optional command arguments may be used for details (e.g. make action). *)
val make_command_text:
?color:OpamConsole.text_style -> string -> ?args:string list -> string ->
string
(** The type for processes *)
type t = {
p_name : string; (** Command name *)
p_args : string list; (** Command args *)
p_pid : int; (** Process PID *)
p_cwd : string; (** Process initial working directory *)
p_time : float; (** Process start time *)
p_stdout : string option; (** stdout dump file *)
p_stderr : string option; (** stderr dump file *)
p_env : string option; (** dump environment variables *)
p_info : string option; (** dump process info *)
p_metadata: (string * string) list; (** Metadata associated to the process *)
p_verbose: bool; (** whether output of the process should be
displayed *)
p_tmp_files: string list; (** temporary files that should be cleaned up upon
completion *)
}
(** Process results *)
type result = {
r_code : int; (** Process exit code, or 256 on error *)
r_signal : int option; (** Signal received if the processed was killed *)
r_duration : float; (** Process duration *)
r_info : (string * string) list; (** Process info *)
r_stdout : string list; (** Content of stdout dump file *)
r_stderr : string list; (** Content of stderr dump file *)
r_cleanup : string list; (** List of files to clean-up *)
}
(** [run command] synchronously call the command [command.cmd] with
arguments [command.args]. It waits until the process is finished. The files
[name.info], [name.env], [name.out] and [name.err], with
[name = command.cmd_name] are
created, and contain the process main description, the environment
variables, the standard output and the standard error.
Don't forget to call [cleanup result] afterwards *)
val run : command -> result
(** Same as [run], but doesn't wait. Use wait_one to wait and collect
results;
Don't forget to call [cleanup result] afterwards *)
val run_background: command -> t
(** Similar to [run_background], except that no process is created, and a dummy
process (suitable for dry_wait_one) is returned. *)
val dry_run_background: command -> t
(** [wait p] waits for the processus [p] to end and returns its results. Be
careful to handle Sys.Break *)
val wait: t -> result
(** Like [wait], but returns None immediately if the process hasn't ended *)
val dontwait: t -> result option
(** Wait for the first of the listed processes to terminate, and return its
termination status *)
val wait_one: t list -> t * result
(** Similar to [wait_one] for simulations, to be used with
[dry_run_background] *)
val dry_wait_one: t list -> t * result
(** Send SIGINT to a process (or SIGKILL on Windows) *)
val interrupt: t -> unit
(** Is the process result a success? *)
val is_success : result -> bool
(** Is the process result a failure? *)
val is_failure : result -> bool
(** Should be called after process termination, to cleanup temporary files.
Leaves artefacts in case OpamGlobals.debug is on and on failure, unless
force has been set. *)
val cleanup : ?force:bool -> result -> unit
(** Like [is_success], with an added cleanup side-effect (as [cleanup
~force:true]). Use this when not returning 0 is not an error case: since the
default behaviour is to cleanup only when the command returned 0, which is
not what is expected in that case. *)
val check_success_and_cleanup : result -> bool
(** {2 Misc} *)
(** Reads a text file and returns a list of lines *)
val read_lines: string -> string list
(** Detailed report on process outcome *)
val string_of_result: ?color:OpamConsole.text_style -> result -> string
(** Short report on process outcome *)
val result_summary: result -> string
(** Higher-level interface to allow parallelism *)
module Job: sig
(** Open type and add combinators. Meant to be opened *)
module Op: sig
type 'a job =
| Done of 'a
| Run of command * (result -> 'a job)
(** Stage a shell command with its continuation, eg:
{[
command "ls" ["-a"] @@> fun result ->
if OpamProcess.is_success result then Done result.r_stdout
else failwith "ls"
]}
*)
val (@@>): command -> (result -> 'a job) -> 'a job
(** [job1 @@+ fun r -> job2] appends the computation of tasks in [job2] after
[job1] *)
val (@@+): 'a job -> ('a -> 'b job) -> 'b job
(** [job @@| f] maps [f] on the results of [job].
Equivalent to [job @@+ fun r -> Done (f r)] *)
val (@@|): 'a job -> ('a -> 'b) -> 'b job
end
(** Sequential run of a job *)
val run: 'a Op.job -> 'a
(** Same as [run] but doesn't actually run any shell command,
and feed a dummy result to the cont. *)
val dry_run: 'a Op.job -> 'a
(** Catch exceptions raised within a job *)
val catch: (exn -> 'a Op.job) -> (unit -> 'a Op.job) -> 'a Op.job
(** Ignore all non-fatal exceptions raised by job and return default *)
val ignore_errors: default:'a -> ?message:string ->
(unit -> 'a Op.job) -> 'a Op.job
(** Register an exception-safe finaliser in a job.
[finally job fin] is equivalent to
[catch job (fun e -> fin (); raise e) @@+ fun r -> fin (); Done r] *)
val finally: (unit -> unit) -> (unit -> 'a Op.job) -> 'a Op.job
(** Converts a list of commands into a job that returns None on success, or
the first failed command and its result.
Unless [keep_going] is true, stops on first error. *)
val of_list: ?keep_going:bool -> command list ->
(command * result) option Op.job
(** As [of_list], but takes a list of functions that return the commands. The
functions will only be evaluated when the command needs to be run. *)
val of_fun_list: ?keep_going:bool -> (unit -> command) list ->
(command * result) option Op.job
(** Returns the job made of the the given homogeneous jobs run sequentially *)
val seq: ('a -> 'a Op.job) list -> 'a -> 'a Op.job
(** Sequentially maps jobs on a list *)
val seq_map: ('a -> 'b Op.job) -> 'a list -> 'b list Op.job
(** Sets and overrides text of the underlying commands *)
val with_text: string -> 'a Op.job -> 'a Op.job
end
type 'a job = 'a Job.Op.job
(**/**)
val set_resolve_command :
(?env:string array -> ?dir:string -> string -> string option) -> unit
| high | 0.627933 | 316 |
CREATE FUNCTION udf_GetCost(@jobId INT)
RETURNS DECIMAL(6,2)
AS
BEGIN
DECLARE @result DECIMAL(6,2)
SET @result=(SELECT SUM(p.Price)
FROM Jobs j
JOIN Orders o ON o.JobId=j.JobId
JOIN OrderParts op ON op.OrderId=o.OrderId
JOIN Parts p ON p.PartId=op.PartId
WHERE j.JobId=@jobId
GROUP BY j.JobId)
IF(@result IS NULL)
BEGIN
SET @result=0
END
RETURN @result;
END
| high | 0.28852 | 317 |
## Welcome to awesome game of Tetris
A project based learning activity for people who are getting started with Git and GitHub.
You can play the game at: https://marcos687.github.io/github-games/
To play the game:
1. Go to the **Settings** tab of this repository.
1. Scroll down to the section titled _GitHub Pages_
1. Select **main** from the Source drop-down.
1. Click **Save**.
1. Navigate to the URL provided in the same section.
### Instructions for playing the game
1. Press the space bar to begin.
2. Use the up and down arrow keys to rotate the shape.
3. Use the left and right arrow keys to position the shape.
4. The goal is to create complete rows with no empty spaces.
5. When completed, the rows will disappear.
6. To pause the game, just press the space bar again.
>> _*SUPPORTED BROWSERS*: Chrome, Firefox, Safari, Opera and IE9+_
This fun open source game was cloned from: https://github.com/jakesgordon/javascript-tetris
| high | 0.330781 | 318 |
*dk,flip2to2
subroutine flip2to2(it1,it2,id,jd,npoints,ntets)
C
C ######################################################################
C
C PURPOSE -
C
C This routine flips connections on boundaries. This routine
C closely parallels the routine 'flip4to4'.
C
C INPUT ARGUMENTS -
C
C it1 - the first tet
C it2 - the second tet
C id - the 'itet' coordinates of the two new tets
C jd - the 'jtet' coordinates of the two new tets
C
C OUTPUT ARGUMENTS -
C
C None
C
C CHANGE HISTORY -
C
C $Log: flip2to2.f,v $
C Revision 2.00 2007/11/05 19:45:55 spchu
C Import to CVS
C
CPVCS
CPVCS Rev 1.5 Wed Feb 03 15:23:26 1999 dcg
CPVCS remove calls to fluxing routines and associated memory.
CPVCS
CPVCS Rev 1.4 Mon Apr 14 16:48:26 1997 pvcs
CPVCS No change.
CPVCS
CPVCS Rev 1.3 12/02/94 15:05:14 het
CPVCS Added an option for the "cmo" access functions
CPVCS
CPVCS
CPVCS Rev 1.2 12/01/94 18:47:00 het
CPVCS Added a data type to the "cmo" calles
CPVCS and added the "cmo.h" include file.
CPVCS
CPVCS Rev 1.1 11/17/94 21:51:22 het
CPVCS Added include files for chydro, neibor, cmerge, comdict. Added calles and
CPVCS pointer statements for current_mesh_object database access.
CPVCS
CPVCS Rev 1.0 11/10/94 12:12:40 pvcs
CPVCS Original version.
C
C ######################################################################
C
implicit none
C
include "cmo.h"
include "chydro.h"
include "neibor.h"
C arguments (it1,it2,id,jd,npoints,ntets)
integer it1,it2,npoints,ntets
integer id(8),jd(8)
C variables
integer i,j,k,i1,i2,i3,i4
integer ierror,length,icmotype,lenimt1,lenitet,lenjtet,
* lenxic,lenyic,lenzic,lenitetclr,ier,
* jd2,jd4,jd7,jd8
C
C DEFINE THE STATEMENT FUNCTIONS NEEDED TO CALCULATE TET VOLUMES.
C
real*8 crosx1,crosy1,crosz1,volume
crosx1(i,j,k)=(yic(j)-yic(i))*(zic(k)-zic(i))-
* (yic(k)-yic(i))*(zic(j)-zic(i))
crosy1(i,j,k)=(xic(k)-xic(i))*(zic(j)-zic(i))-
* (xic(j)-xic(i))*(zic(k)-zic(i))
crosz1(i,j,k)=(xic(j)-xic(i))*(yic(k)-yic(i))-
* (xic(k)-xic(i))*(yic(j)-yic(i))
volume(i1,i2,i3,i4)=(xic(i4)-xic(i1))*crosx1(i1,i2,i3)+
* (yic(i4)-yic(i1))*crosy1(i1,i2,i3)+
* (zic(i4)-zic(i1))*crosz1(i1,i2,i3)
C
C ######################################################################
C
C
C ******************************************************************
C FETCH MESH OBJECT NAME AND POINTER INFORMATION.
C
if(icmoget.eq.1) then
C
call cmo_get_name(cmo,ierror)
C
call cmo_get_info('mbndry',cmo,mbndry,length,icmotype,ierror)
call cmo_get_info('imt1',cmo,ipimt1,lenimt1,icmotype,ierror)
call cmo_get_info('xic',cmo,ipxic,lenxic,icmotype,ierror)
call cmo_get_info('yic',cmo,ipyic,lenyic,icmotype,ierror)
call cmo_get_info('zic',cmo,ipzic,lenzic,icmotype,ierror)
call cmo_get_info('itetclr',cmo,ipitetclr,lenitetclr,icmotype,ier)
call cmo_get_info('itet',cmo,ipitet,lenitet,icmotype,ierror)
call cmo_get_info('jtet',cmo,ipjtet,lenjtet,icmotype,ierror)
C
endif
C
C
itet(1,it1)=id(1)
jtet(1,it1)=jd(1)
itet(2,it1)=id(2)
jtet(2,it1)=jd(2)
itet(3,it1)=id(3)
jtet(3,it1)=jd(3)
itet(4,it1)=id(4)
jtet(4,it1)=jd(4)
itet(1,it2)=id(5)
jtet(1,it2)=jd(5)
itet(2,it2)=id(6)
jtet(2,it2)=jd(6)
itet(3,it2)=id(7)
jtet(3,it2)=jd(7)
itet(4,it2)=id(8)
jtet(4,it2)=jd(8)
C
C MAKE THE 'jtet' ARRAY CONSISTENT
C
if(jd(2).lt.mbndry) then
jtet1(jd(2))=4*(it1-1)+2
elseif(jd(2).gt.mbndry) then
jd2=jd(2)-mbndry
jtet1(jd2)=4*(it1-1)+2+mbndry
endif
if(jd(4).lt.mbndry) then
jtet1(jd(4))=4*(it1-1)+4
elseif(jd(4).gt.mbndry) then
jd4=jd(4)-mbndry
jtet1(jd4)=4*(it1-1)+4+mbndry
endif
if(jd(7).lt.mbndry) then
jtet1(jd(7))=4*(it2-1)+3
elseif(jd(7).gt.mbndry) then
jd7=jd(7)-mbndry
jtet1(jd7)=4*(it2-1)+3+mbndry
endif
if(jd(8).lt.mbndry) then
jtet1(jd(8))=4*(it2-1)+4
elseif(jd(8).gt.mbndry) then
jd8=jd(8)-mbndry
jtet1(jd8)=4*(it2-1)+4+mbndry
endif
C
C
goto 9999
9999 continue
return
end
| low | 0.669687 | 319 |
/* This is a CSS file */
body {
text-align: center;
}
#form-title {
/* background-color: black; */
/* height: 50px; */
}
#add {
background-color: black;
} | low | 0.834084 | 320 |
grammar Identifiers;
import LexRules;
array_identifier : identifier ;
block_identifier : identifier ;
bin_identifier : identifier ;
c_identifier : C_IDENTIFIER | LOWER_S | LOWER_MS | LOWER_US | LOWER_NS | LOWER_PS | LOWER_FS | B | F | R | P | N | HEX_DIGIT | X_DIGIT | Z_DIGIT | UNDERSCORE ;
cell_identifier : identifier ;
checker_identifier : identifier ;
class_identifier : identifier ;
class_variable_identifier : variable_identifier ;
clocking_identifier : identifier ;
config_identifier : identifier ;
const_identifier : identifier ;
constraint_identifier : identifier ;
covergroup_identifier : identifier ;
covergroup_variable_identifier : variable_identifier ;
cover_point_identifier : identifier ;
cross_identifier : identifier ;
dynamic_array_variable_identifier : variable_identifier ;
enum_identifier : identifier ;
formal_identifier : identifier ;
formal_port_identifier : identifier ;
function_identifier : identifier ;
generate_block_identifier : identifier ;
genvar_identifier : identifier ;
hierarchical_array_identifier : hierarchical_identifier ;
hierarchical_block_identifier : hierarchical_identifier ;
hierarchical_event_identifier : hierarchical_identifier ;
hierarchical_identifier : ( '$root' '.' )? ( identifier constant_bit_select '.' )* identifier ;
hierarchical_net_identifier : hierarchical_identifier ;
hierarchical_parameter_identifier : hierarchical_identifier ;
hierarchical_property_identifier : hierarchical_identifier ;
hierarchical_sequence_identifier : hierarchical_identifier ;
hierarchical_task_identifier : hierarchical_identifier ;
hierarchical_tf_identifier : hierarchical_identifier ;
hierarchical_variable_identifier : hierarchical_identifier ;
identifier : simple_identifier | ESCAPED_IDENTIFIER ;
index_variable_identifier : identifier ;
interface_identifier : identifier ;
interface_instance_identifier : identifier ;
inout_port_identifier : identifier ;
input_port_identifier : identifier ;
instance_identifier : identifier ;
library_identifier : identifier ;
member_identifier : identifier ;
method_identifier : identifier ;
modport_identifier : identifier ;
module_identifier : identifier ;
net_identifier : identifier ;
net_type_identifier : identifier ;
output_port_identifier : identifier ;
package_identifier : identifier ;
package_scope : package_identifier '::' | '$unit' '::' ;
parameter_identifier : identifier ;
port_identifier : identifier ;
production_identifier : identifier ;
program_identifier : identifier ;
property_identifier : identifier ;
ps_class_identifier : ( package_scope )? class_identifier ;
ps_covergroup_identifier : ( package_scope )? covergroup_identifier ;
ps_checker_identifier : ( package_scope )? checker_identifier ;
ps_identifier : ( package_scope )? identifier ;
ps_or_hierarchical_array_identifier : ( implicit_class_handle '.' | class_scope
| package_scope )? hierarchical_array_identifier ;
ps_or_hierarchical_net_identifier : ( package_scope )? net_identifier | hierarchical_net_identifier ;
ps_or_hierarchical_property_identifier : ( package_scope )? property_identifier
| hierarchical_property_identifier ;
ps_or_hierarchical_sequence_identifier : ( package_scope )? sequence_identifier
| hierarchical_sequence_identifier ;
ps_or_hierarchical_tf_identifier : ( package_scope )? tf_identifier
| hierarchical_tf_identifier ;
ps_parameter_identifier : ( package_scope | class_scope )? parameter_identifier
| ( generate_block_identifier ( '[' constant_expression ']' )? '.' )* parameter_identifier ;
ps_type_identifier : ( 'local' '::' | package_scope | class_scope )? type_identifier ;
sequence_identifier : identifier ;
signal_identifier : identifier ;
simple_identifier : SIMPLE_IDENTIFIER | c_identifier ;
specparam_identifier : identifier ;
task_identifier : identifier ;
tf_identifier : identifier ;
terminal_identifier : identifier ;
topmodule_identifier : identifier ;
type_identifier : identifier ;
udp_identifier : identifier ;
variable_identifier : identifier ;
| high | 0.371929 | 321 |
# encoding: utf-8
class SequenceFileUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
# include Sprockets::Helpers::RailsHelper
# include Sprockets::Helpers::IsolatedHelper
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/fasta"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :scale => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
def extension_white_list
%w(fa fasta txt)
end
def filename
"seq#{Time.now.to_i}.fasta"
end
end
| medium | 0.482472 | 322 |
# Carregando os dados
viagens = read.csv(file = 'C:/Users/Makson/Documents/GitHub/Aprendendo-R/ENAP Analise de Dados/2020_Viagem.csv', sep = ';', dec = ',')
head(viagens)
View(viagens)
dim(viagens)
summary(viagens)
summary(viagens$valor.passagens)
# Verificando o tipo de dados
library(dplyr)
glimpse(viagens)
# Converter para o tipo data
viagens$data.inicio = as.Date(viagens$Período...Data.de.início, '%d/ %m/ %y')
glimpse(viagens)
# Formatando o campo data para trabalhar apenas com mes e ano
viagens$data.inicio.formatada = format(viagens$data.inicio, '%Y-%m')
head(viagens$data.inicio.formatada)
# Explorando os dados
hist(viagens$Valor.passagens)
# Valores max, min e media .... da coluna valor
summary(viagens$Valor.passagens)
# Visualizando os valores em boxplot
boxplot(viagens$Valor.passagens)
# Desvio padrao
sd(viagens$Valor.passagens)
# Verificar valores nulos nas colunas
colSums(is.na(viagens))
# Verificando ocorrencias
str(viagens$Situação)
# Verificando a quantidade de ocorrencias a cada classe
table(viagens$Situação)
# Valor em percentual
prop.table(table(viagens$Situação)) * 100
# 1 - Quais orgaos estao gastando mais com viagens?
# Criando um dataframe com os 15 que mais gastam
p1 = viagens %>% group_by(Nome.do.órgão.superior) %>% summarise(n = sum(Valor.passagens)) %>% arrange(desc(n)) %>% top_n(15)
names(p1) = c('Orgao', 'Valor')
head(p1)
# Criando grafico de barras com ggplot
library(ggplot2)
ggplot(p1, aes(x=reorder(Orgao, Valor), y=Valor)) + geom_bar(stat='identity') + coord_flip() + labs(x='Valor', y='Orgao')
# Quantidade de gastos por cidades com viagens
p2 = viagens %>% group_by(Destinos) %>% summarise(n=sum(Valor.passagens)) %>% arrange(desc(n)) %>% top_n(15)
names(p2) = c('Destino', 'Valor')
head(p2)
ggplot(p2, aes(x=reorder(Destino, Valor), y=Valor)) + geom_bar(stat='identity', fill='#0ba791') + geom_text(aes(label=Valor),
vjust=0.3, size=3) + coord_flip() + labs(x='Valor', y='Destino')
options(scipen=999)
# Quantidades de viagens realizadas pro mes
p3 = viagens %>% group_by(data.inicio.formatada) %>% summarise(qtd=n_distinct(Identificador.do.processo.de.viagem))
head(p3)
ggplot(p3, aes(x=data.inicio.formatada, y=qtd, group=1)) + geom_line() + geom_point()
# Visualizacao dos dados com Markdown
install.packages('rmarkdown')
install.packages('tinytex')
tinytex::install_tinytex() | low | 0.207174 | 323 |
r=359.67
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7j01f/media/images/d7j01f-008/svc:tesseract/full/full/359.67/default.jpg Accept:application/hocr+xml
| low | 0.872846 | 324 |
%%%-------------------------------------------------------------------
%%% @author Administrator
%%% @copyright (C) 2019, <COMPANY>
%%% @doc
%%% TODO delay时, 可做逻辑上的优化, 有join或leave的时候直接先把旧的广播出去
%%% @end
%%% Created : 04. 11月 2019 19:20
%%%-------------------------------------------------------------------
-module(group_svr).
-author("Administrator").
-behaviour(gen_server).
-include("hrl_common.hrl").
-include("hrl_logs.hrl").
-export([
start_link/2
]).
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-record(state, {
type = ?undefined, %% group类型(名字)
groups = [],
tmp_groups = [],
loop_ref = ?undefined,
count = 0,
waits = [],
delay = 0, %% 延迟发送时间, ms
cache_cmds = [],
clear_time = 0,
to_be_clear = ?false,
strict = ?false
}).
-define(BCAST_DELAY, 0). %% 广播延迟
-define(CLEAR_EMPTY_GROUP_INTERVAL, 10). %% 清除空的group间隔
-spec start_link(GroupType, Opts) -> {ok, pid()} | {error, term()} when
Opts :: [term()],
GroupType :: term().
start_link(GroupType, Opts) ->
case proplists:get_bool(noname, Opts) of
?true ->
gen_server:start_link(?MODULE, [GroupType, Opts], []);
_ ->
Name = group_api:group_name(GroupType),
gen_server:start_link({local, Name}, ?MODULE, [GroupType, Opts], [])
end.
init([GroupType, Opts]) ->
Delay = proplists:get_value(delay, Opts, ?BCAST_DELAY),
Strict = proplists:get_value(strict, Opts, ?false),
{ok, #state{type = GroupType, delay = Delay, strict = Strict}}.
handle_call(Request, From, State) ->
try
do_call(Request, From, State)
catch
Err:Reason ->
?ERROR("ERR:~p,Reason:~p", [Err, Reason]),
{reply, error, State}
end.
handle_cast(Request, State) ->
try
do_cast(Request, State)
catch
Err:Reason ->
?ERROR("ERR:~p,Reason:~p", [Err, Reason]),
{noreply, State}
end.
handle_info(Request, State) ->
try
do_info(Request, State)
catch
Err:Reason ->
?ERROR("ERR:~p,Reason:~p", [Err, Reason]),
{noreply, State}
end.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, _State) ->
ok.
do_call(groups, _From, #state{groups = Groups} = State) ->
{reply, Groups, State};
do_call(count, _From, #state{count = Count} = State) ->
{reply, Count, State};
do_call({count, GroupID}, _From, State) ->
Count = length(members(GroupID)),
{reply, Count, State};
do_call({members, GroupID}, _From, State) ->
Members = members(GroupID),
{reply, Members, State};
do_call(wait_loop, _From, #state{loop_ref = ?undefined} = State) ->
{reply, ok, State};
do_call(wait_loop, From, #state{waits = Waits} = State) ->
State1 = State#state{waits = [From | Waits]},
{noreply, State1};
do_call(_Msg, _From, State) ->
?WARNING("unhandle call ~w", [_Msg]),
{reply, error, State}.
do_cast({bcast_to_all, GroupIDs, Msg}, #state{delay = 0} = State) ->
case erlang:iolist_to_binary(Msg) of
<<>> ->
ok;
Msg1 ->
[[net_api:send(M, Msg1) || M <- members(GroupID)] || GroupID <- GroupIDs]
end,
{noreply, State};
%% 对网络广播做优化, 缓存广播信息
do_cast({bcast_to_all, GroupIDs, Msg}, State) ->
State1 =
case erlang:iolist_to_binary(Msg) of
<<>> ->
State;
Msg1 ->
cache_bcast(GroupIDs, Msg1, State)
end,
State2 = set_timer(State1),
{noreply, State2};
%% 分批广播
do_cast({batch_bcast_to_all, GroupMsgs}, #state{delay = 0} = State) ->
F = fun({GroupIDs, Msg}) ->
case erlang:iolist_to_binary(Msg) of
<<>> ->
ok;
Msg1 ->
[[net_api:send(M, Msg1) || M <- members(GroupID)] || GroupID <- GroupIDs]
end
end,
lists:foreach(F, GroupMsgs),
{noreply, State};
do_cast({batch_bcast_to_all, GroupMsgs}, State) -> % 对网络广播做优化
F = fun({GroupIDs, Msg}, FState) when GroupIDs =/= [] ->
case erlang:iolist_to_binary(Msg) of
<<>> -> FState;
Msg1 -> cache_bcast(GroupIDs, Msg1, FState)
end;
(_, FState) ->
FState
end,
State1 = lists:foldl(F, State, GroupMsgs),
State2 = set_timer(State1),
{noreply, State2};
do_cast({to_all, {Mod, Func}, GroupID, Msg}, State) ->
Members = members(GroupID),
[Mod:Func(M, Msg) || M <- Members],
{noreply, State};
do_cast({to_mall, {Mod, Func}, GroupIDs, Msg}, State) ->
[[Mod:Func(M, Msg) || M <- members(GroupID)] || GroupID <- GroupIDs],
{noreply, State};
do_cast({to_other, {Mod, Func}, GroupID, Msg, MyPID}, State) ->
Members = members(GroupID),
[Mod:Func(M, Msg) || M <- Members, M =/= MyPID],
{noreply, State};
do_cast(close, State) ->
{stop, normal, State};
do_cast(Cmd, State) ->
cache_cmd(Cmd, State).
do_info({'DOWN', _Ref, process, Pid, _Reason}, State) ->
State1 = do_leave_all(Pid, State),
{noreply, State1};
do_info(doloop, #state{groups = Groups, tmp_groups = TmpGroups, waits = Waits} = State) ->
[send_cache(G, State) || G <- TmpGroups ++ Groups],
[gen_server:reply(W, ok) || W <- Waits],
State1 = run_cached_cmd(State),
State2 = clear_empty_groups(State1),
{noreply, State2#state{loop_ref = ?undefined, waits = [], cache_cmds = [], tmp_groups = []}};
do_info(_Msg, State) ->
?WARNING("unhandle info ~w", [_Msg]),
{noreply, State}.
set_timer(#state{loop_ref = ?undefined, delay = Delay} = State) ->
Ref = erlang:send_after(Delay, self(), doloop),
State#state{loop_ref = Ref};
set_timer(State) ->
State.
cache_cmd(Cmd, #state{cache_cmds = Cmds, strict = ?true} = State) ->
State1 = State#state{cache_cmds = [Cmd | Cmds]},
State2 = cache_bcast_cmd(Cmd, State1),
{noreply, State2};
cache_cmd(Cmd, #state{} = State) ->
State1 = run_cmd(Cmd, State),
{noreply, State1}.
run_cached_cmd(#state{cache_cmds = Cmds} = State) ->
Cmds1 = lists:reverse(Cmds),
State1 = lists:foldl(fun run_cmd/2, State, Cmds1),
State1.
run_cmd({join, GroupID, Pid}, #state{} = State) when is_pid(Pid) ->
State1 = do_join(GroupID, Pid, State),
State1;
run_cmd({join_many, GroupIDs, Pid}, #state{} = State) when is_pid(Pid) ->
F = fun(GroupID, S) -> do_join(GroupID, Pid, S) end,
State1 = lists:foldl(F, State, GroupIDs),
State1;
run_cmd({leave, GroupID, Pid}, #state{} = State) when is_pid(Pid) ->
State1 = do_leave(GroupID, Pid, State),
State1;
run_cmd({leave_all, Pid}, #state{} = State) when is_pid(Pid) ->
State1 = do_leave_all(Pid, State),
State1;
run_cmd({leave_many, GroupIDs, Pid}, #state{} = State) when is_pid(Pid) ->
F = fun(GroupID, S) -> do_leave(GroupID, Pid, S) end,
State1 = lists:foldl(F, State, GroupIDs),
State1;
run_cmd({dismiss, GroupID}, #state{groups = GIDs} = State) ->
send_cache(GroupID, State), % 解散前先把残留消息发出
Members = members(GroupID),
[del_member_groups(M, GroupID) || M <- Members],
set_members(GroupID, []),
GIDs1 = lists:delete(GroupID, GIDs),
State#state{groups = GIDs1};
run_cmd(_Msg, State) ->
?WARNING("unhandle cast ~p", [_Msg]),
State.
get_cmd_groups_ids({join, GroupID, Pid}) ->
{{join, Pid}, [GroupID]};
get_cmd_groups_ids({join_many, GroupIDs, Pid}) ->
{{join, Pid}, GroupIDs};
get_cmd_groups_ids({leave, GroupID, Pid}) ->
{{leave, Pid}, [GroupID]};
get_cmd_groups_ids({leave_all, Pid}) ->
case erlang:get({groups, Pid}) of
?undefined ->
{leave, []};
{_Ref, Groups} ->
{{leave, Pid}, Groups}
end;
get_cmd_groups_ids({leave_many, GroupIDs, Pid}) ->
{{leave, Pid}, GroupIDs};
get_cmd_groups_ids({dismiss, _GroupID}) ->
{dismiss, []}.
do_leave_all(Pid, #state{count = Count} = State) ->
case erlang:erase({groups, Pid}) of
?undefined ->
State;
{Ref, Groups} ->
erlang:demonitor(Ref),
[del_member(G, Pid) || G <- Groups],
State1 = State#state{count = Count - 1},
State2 = check_empty_groups(State1),
State2
end.
do_join(GroupID, Pid, #state{groups = GIDs, count = Count} = State) ->
Count1 =
case erlang:get({groups, Pid}) of
?undefined -> % 第一次加入此类群组
Ref = erlang:monitor(process, Pid),
set_member_groups(Pid, Ref, [GroupID]),
Count + 1;
{Ref, Groups} ->
Groups1 = store(GroupID, Groups),
set_member_groups(Pid, Ref, Groups1),
Count
end,
GIDs1 =
case add_member(GroupID, Pid) of
?undefined -> % 新群组
store(GroupID, GIDs);
_ ->
GIDs
end,
State#state{groups = GIDs1, count = Count1}.
do_leave(GroupID, Pid, #state{groups = GIDs} = State) ->
del_member_groups(Pid, GroupID),
GIDs1 =
case del_member(GroupID, Pid) of
empty ->
lists:delete(GroupID, GIDs);
_ ->
GIDs
end,
State#state{groups = GIDs1}.
cache_bcast_cmd(Cmd, #state{strict = ?true} = State) ->
{Cmd1, GroupIDs} = get_cmd_groups_ids(Cmd),
F = fun(GID, #state{tmp_groups = TmpGroups} = S) ->
case erlang:get({bcast_cache, GID}) of
?undefined ->
erlang:put({bcast_cache, GID}, [Cmd1]),
S#state{tmp_groups = [GID | TmpGroups]};
Msgs ->
erlang:put({bcast_cache, GID}, [Cmd1 | Msgs]),
S
end
end,
lists:foldl(F, State, GroupIDs);
cache_bcast_cmd(_Cmd, State) ->
State.
cache_bcast([GroupID | T], Msg, #state{tmp_groups = TmpGroups} = State) ->
case members(GroupID) =/= [] orelse lists:member(GroupID, TmpGroups) of
?true ->
case erlang:get({bcast_cache, GroupID}) of
?undefined ->
erlang:put({bcast_cache, GroupID}, [Msg]);
Msgs ->
erlang:put({bcast_cache, GroupID}, [Msg | Msgs])
end;
_ ->
pass
end,
cache_bcast(T, Msg, State);
cache_bcast([], _Msg, State) ->
State.
send_cache(GroupID, #state{strict = ?true}) ->
case erlang:erase({bcast_cache, GroupID}) of
?undefined ->
ok;
Msgs ->
Members = members(GroupID),
send_cache_strict(Msgs, Members, [])
end;
send_cache(GroupID, _) ->
case erlang:erase({bcast_cache, GroupID}) of
?undefined ->
ok;
Msgs ->
Msgs1 = lists:reverse(Msgs),
Members = members(GroupID),
bcast_msgs(fun net_api:send/2, Msgs1, Members)
end.
%% 包含其他一些cast的信息需要先处理
send_cache_strict([{join, Pid} | T], Members, MsgAcc) ->
Members1 = [Pid | lists:delete(Pid, Members)],
bcast_msgs(fun net_api:send/2, MsgAcc, Members1),
send_cache_strict(T, Members1, []);
send_cache_strict([{leave, Pid} | T], Members, MsgAcc) ->
Members1 = lists:delete(Pid, Members),
bcast_msgs(fun net_api:send/2, MsgAcc, Members1),
send_cache_strict(T, Members1, []);
send_cache_strict([Msg | T], Members, MsgAcc) ->
send_cache_strict(T, Members, [Msg | MsgAcc]);
send_cache_strict([], Members, MsgAcc) ->
bcast_msgs(fun net_api:send/2, MsgAcc, Members).
bcast_msgs(Func, Msgs, Members) ->
case iolist_to_binary(Msgs) of
<<>> ->
ok;
Msgs1 ->
[Func(M, Msgs1) || M <- Members],
ok
end.
set_member_groups(Member, Ref, Groups) ->
erlang:put({groups, Member}, {Ref, Groups}).
%% 成员所属群组去除某群
del_member_groups(Member, GroupID) ->
case erlang:get({groups, Member}) of
?undefined -> % 此人已离线
ok;
{Ref, Groups} ->
set_member_groups(Member, Ref, lists:delete(GroupID, Groups))
end.
%% 获取群组中的成员
members(GroupID) ->
case erlang:get({members, GroupID}) of
?undefined -> [];
Val -> Val
end.
set_members(GroupID, []) ->
erlang:erase({members, GroupID}),
erlang:erase({bcast_cache, GroupID}), % 清除空群组的发送缓存!
empty;
set_members(GroupID, Members) ->
erlang:put({members, GroupID}, Members).
% 如群组未创建, 返undefined
add_member(GroupID, Member) ->
Members = members(GroupID),
Members1 = store(Member, Members),
set_members(GroupID, Members1).
% 如群组被清空, 返empty
del_member(GroupID, Member) ->
Members = members(GroupID),
Members1 = lists:delete(Member, Members),
set_members(GroupID, Members1).
store(Elem, List) ->
case lists:member(Elem, List) of
?true -> List;
?false -> [Elem | List]
end.
check_empty_groups(#state{clear_time = CTime} = State) ->
Now = util_time:unixtime(),
case Now - CTime > ?CLEAR_EMPTY_GROUP_INTERVAL of
?true ->
State#state{to_be_clear = ?true};
_ ->
State
end.
clear_empty_groups(#state{groups = Groups, to_be_clear = ?true} = State) ->
Now = util_time:unixtime(),
Groups1 = clear_empty_groups_1(Groups, []),
State#state{groups = Groups1, clear_time = Now, to_be_clear = ?false};
clear_empty_groups(State) ->
State.
clear_empty_groups_1([GID | Tail], Acc) ->
Acc1 =
case members(GID) of
[] -> Acc;
_ -> [GID | Acc]
end,
clear_empty_groups_1(Tail, Acc1);
clear_empty_groups_1([], Acc) ->
Acc.
| high | 0.720969 | 325 |
/-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
import Init.Core
@[simp] theorem eqSelf (a : α) : (a = a) = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => rfl)
theorem ofEqTrue (h : p = True) : p :=
h ▸ trivial
theorem eqTrue (h : p) : p = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => h)
theorem eqFalse (h : ¬ p) : p = False :=
propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h')
theorem eqFalse' (h : p → False) : p = False :=
propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h')
theorem eqTrueOfDecide {p : Prop} {s : Decidable p} (h : decide p = true) : p = True :=
propext <| Iff.intro (fun h => trivial) (fun _ => ofDecideEqTrue h)
theorem eqFalseOfDecide {p : Prop} {s : Decidable p} (h : decide p = false) : p = False :=
propext <| Iff.intro (fun h' => absurd h' (ofDecideEqFalse h)) (fun h => False.elim h)
theorem impCongr {p₁ p₂ : Sort u} {q₁ q₂ : Sort v} (h₁ : p₁ = p₂) (h₂ : q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) :=
h₁ ▸ h₂ ▸ rfl
theorem impCongrCtx {p₁ p₂ q₁ q₂ : Prop} (h₁ : p₁ = p₂) (h₂ : p₂ → q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) :=
propext <| Iff.intro
(fun h hp₂ =>
have p₁ from h₁ ▸ hp₂
have q₁ from h this
h₂ hp₂ ▸ this)
(fun h hp₁ =>
have hp₂ : p₂ from h₁ ▸ hp₁
have q₂ from h hp₂
h₂ hp₂ ▸ this)
theorem forallCongr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a = q a)) : (∀ a, p a) = (∀ a, q a) :=
have p = q from funext h
this ▸ rfl
@[congr]
theorem iteCongr {x y u v : α} {s : Decidable b} [Decidable c] (h₁ : b = c) (h₂ : c → x = u) (h₃ : ¬ c → y = v) : ite b x y = ite c u v := by
cases Decidable.em c with
| inl h => rw [ifPos h]; subst b; rw[ifPos h]; exact h₂ h
| inr h => rw [ifNeg h]; subst b; rw[ifNeg h]; exact h₃ h
theorem Eq.mprProp {p q : Prop} (h₁ : p = q) (h₂ : q) : p :=
h₁ ▸ h₂
theorem Eq.mprNot {p q : Prop} (h₁ : p = q) (h₂ : ¬q) : ¬p :=
h₁ ▸ h₂
@[congr]
theorem diteCongr {s : Decidable b} [Decidable c]
{x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α}
(h₁ : b = c)
(h₂ : (h : c) → x (Eq.mprProp h₁ h) = u h)
(h₃ : (h : ¬c) → y (Eq.mprNot h₁ h) = v h)
: dite b x y = dite c u v := by
cases Decidable.em c with
| inl h => rw [difPos h]; subst b; rw [difPos h]; exact h₂ h
| inr h => rw [difNeg h]; subst b; rw [difNeg h]; exact h₃ h
namespace Lean.Simp
@[simp] theorem Ne_Eq (a b : α) : (a ≠ b) = Not (a = b) := rfl
@[simp] theorem ite_True (a b : α) : (if True then a else b) = a := rfl
@[simp] theorem ite_False (a b : α) : (if False then a else b) = b := rfl
@[simp] theorem And_self (p : Prop) : (p ∧ p) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, h⟩)
@[simp] theorem And_True (p : Prop) : (p ∧ True) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, trivial⟩)
@[simp] theorem True_And (p : Prop) : (True ∧ p) = p := propext <| Iff.intro (fun h => h.2) (fun h => ⟨trivial, h⟩)
@[simp] theorem And_False (p : Prop) : (p ∧ False) = False := propext <| Iff.intro (fun h => h.2) (fun h => False.elim h)
@[simp] theorem False_And (p : Prop) : (False ∧ p) = False := propext <| Iff.intro (fun h => h.1) (fun h => False.elim h)
@[simp] theorem Or_self (p : Prop) : (p ∨ p) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => h) (fun h => Or.inl h)
@[simp] theorem Or_True (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inr trivial)
@[simp] theorem True_Or (p : Prop) : (True ∨ p) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inl trivial)
@[simp] theorem Or_False (p : Prop) : (p ∨ False) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => False.elim h) (fun h => Or.inl h)
@[simp] theorem False_Or (p : Prop) : (False ∨ p) = p := propext <| Iff.intro (fun | Or.inr h => h | Or.inl h => False.elim h) (fun h => Or.inr h)
@[simp] theorem Iff_self (p : Prop) : (p ↔ p) = True := propext <| Iff.intro (fun h => trivial) (fun _ => Iff.intro id id)
end Lean.Simp
| high | 0.494015 | 326 |
#
# Report generation script generated by Vivado
#
proc create_report { reportName command } {
set status "."
append status $reportName ".fail"
if { [file exists $status] } {
eval file delete [glob $status]
}
send_msg_id runtcl-4 info "Executing : $command"
set retval [eval catch { $command } msg]
if { $retval != 0 } {
set fp [open $status w]
close $fp
send_msg_id runtcl-5 warning "$msg"
}
}
namespace eval ::optrace {
variable script "D:/Documents/230612/digital-electronics-1/labs/08-traffic_lights/traffic/traffic.runs/impl_1/top.tcl"
variable category "vivado_impl"
}
# Try to connect to running dispatch if we haven't done so already.
# This code assumes that the Tcl interpreter is not using threads,
# since the ::dispatch::connected variable isn't mutex protected.
if {![info exists ::dispatch::connected]} {
namespace eval ::dispatch {
variable connected false
if {[llength [array get env XILINX_CD_CONNECT_ID]] > 0} {
set result "true"
if {[catch {
if {[lsearch -exact [package names] DispatchTcl] < 0} {
set result [load librdi_cd_clienttcl[info sharedlibextension]]
}
if {$result eq "false"} {
puts "WARNING: Could not load dispatch client library"
}
set connect_id [ ::dispatch::init_client -mode EXISTING_SERVER ]
if { $connect_id eq "" } {
puts "WARNING: Could not initialize dispatch client"
} else {
puts "INFO: Dispatch client connection id - $connect_id"
set connected true
}
} catch_res]} {
puts "WARNING: failed to connect to dispatch server - $catch_res"
}
}
}
}
if {$::dispatch::connected} {
# Remove the dummy proc if it exists.
if { [expr {[llength [info procs ::OPTRACE]] > 0}] } {
rename ::OPTRACE ""
}
proc ::OPTRACE { task action {tags {} } } {
::vitis_log::op_trace "$task" $action -tags $tags -script $::optrace::script -category $::optrace::category
}
# dispatch is generic. We specifically want to attach logging.
::vitis_log::connect_client
} else {
# Add dummy proc if it doesn't exist.
if { [expr {[llength [info procs ::OPTRACE]] == 0}] } {
proc ::OPTRACE {{arg1 \"\" } {arg2 \"\"} {arg3 \"\" } {arg4 \"\"} {arg5 \"\" } {arg6 \"\"}} {
# Do nothing
}
}
}
proc start_step { step } {
set stopFile ".stop.rst"
if {[file isfile .stop.rst]} {
puts ""
puts "*** Halting run - EA reset detected ***"
puts ""
puts ""
return -code error
}
set beginFile ".$step.begin.rst"
set platform "$::tcl_platform(platform)"
set user "$::tcl_platform(user)"
set pid [pid]
set host ""
if { [string equal $platform unix] } {
if { [info exist ::env(HOSTNAME)] } {
set host $::env(HOSTNAME)
} elseif { [info exist ::env(HOST)] } {
set host $::env(HOST)
}
} else {
if { [info exist ::env(COMPUTERNAME)] } {
set host $::env(COMPUTERNAME)
}
}
set ch [open $beginFile w]
puts $ch "<?xml version=\"1.0\"?>"
puts $ch "<ProcessHandle Version=\"1\" Minor=\"0\">"
puts $ch " <Process Command=\".planAhead.\" Owner=\"$user\" Host=\"$host\" Pid=\"$pid\">"
puts $ch " </Process>"
puts $ch "</ProcessHandle>"
close $ch
}
proc end_step { step } {
set endFile ".$step.end.rst"
set ch [open $endFile w]
close $ch
}
proc step_failed { step } {
set endFile ".$step.error.rst"
set ch [open $endFile w]
close $ch
}
OPTRACE "Implementation" START { ROLLUP_1 }
OPTRACE "Phase: Init Design" START { ROLLUP_AUTO }
start_step init_design
set ACTIVE_STEP init_design
set rc [catch {
create_msg_db init_design.pb
set_param chipscope.maxJobs 1
OPTRACE "create in-memory project" START { }
create_project -in_memory -part xc7a50ticsg324-1L
set_property board_part digilentinc.com:nexys-a7-50t:part0:1.0 [current_project]
set_property design_mode GateLvl [current_fileset]
set_param project.singleFileAddWarning.threshold 0
OPTRACE "create in-memory project" END { }
OPTRACE "set parameters" START { }
set_property webtalk.parent_dir D:/Documents/230612/digital-electronics-1/labs/08-traffic_lights/traffic/traffic.cache/wt [current_project]
set_property parent.project_path D:/Documents/230612/digital-electronics-1/labs/08-traffic_lights/traffic/traffic.xpr [current_project]
set_property ip_output_repo D:/Documents/230612/digital-electronics-1/labs/08-traffic_lights/traffic/traffic.cache/ip [current_project]
set_property ip_cache_permissions {read write} [current_project]
OPTRACE "set parameters" END { }
OPTRACE "add files" START { }
add_files -quiet D:/Documents/230612/digital-electronics-1/labs/08-traffic_lights/traffic/traffic.runs/synth_1/top.dcp
OPTRACE "read constraints: implementation" START { }
read_xdc D:/Documents/230612/digital-electronics-1/labs/08-traffic_lights/traffic/traffic.srcs/constrs_1/new/nexys-a7-50t.xdc
OPTRACE "read constraints: implementation" END { }
OPTRACE "add files" END { }
OPTRACE "link_design" START { }
link_design -top top -part xc7a50ticsg324-1L
OPTRACE "link_design" END { }
OPTRACE "gray box cells" START { }
OPTRACE "gray box cells" END { }
OPTRACE "init_design_reports" START { REPORT }
OPTRACE "init_design_reports" END { }
OPTRACE "init_design_write_hwdef" START { }
OPTRACE "init_design_write_hwdef" END { }
close_msg_db -file init_design.pb
} RESULT]
if {$rc} {
step_failed init_design
return -code error $RESULT
} else {
end_step init_design
unset ACTIVE_STEP
}
OPTRACE "Phase: Init Design" END { }
OPTRACE "Phase: Opt Design" START { ROLLUP_AUTO }
start_step opt_design
set ACTIVE_STEP opt_design
set rc [catch {
create_msg_db opt_design.pb
OPTRACE "read constraints: opt_design" START { }
OPTRACE "read constraints: opt_design" END { }
OPTRACE "opt_design" START { }
opt_design
OPTRACE "opt_design" END { }
OPTRACE "read constraints: opt_design_post" START { }
OPTRACE "read constraints: opt_design_post" END { }
OPTRACE "Opt Design: write_checkpoint" START { CHECKPOINT }
write_checkpoint -force top_opt.dcp
OPTRACE "Opt Design: write_checkpoint" END { }
OPTRACE "opt_design reports" START { REPORT }
create_report "impl_1_opt_report_drc_0" "report_drc -file top_drc_opted.rpt -pb top_drc_opted.pb -rpx top_drc_opted.rpx"
OPTRACE "opt_design reports" END { }
close_msg_db -file opt_design.pb
} RESULT]
if {$rc} {
step_failed opt_design
return -code error $RESULT
} else {
end_step opt_design
unset ACTIVE_STEP
}
OPTRACE "Phase: Opt Design" END { }
OPTRACE "Phase: Place Design" START { ROLLUP_AUTO }
start_step place_design
set ACTIVE_STEP place_design
set rc [catch {
create_msg_db place_design.pb
OPTRACE "read constraints: place_design" START { }
OPTRACE "read constraints: place_design" END { }
if { [llength [get_debug_cores -quiet] ] > 0 } {
OPTRACE "implement_debug_core" START { }
implement_debug_core
OPTRACE "implement_debug_core" END { }
}
OPTRACE "place_design" START { }
place_design
OPTRACE "place_design" END { }
OPTRACE "read constraints: place_design_post" START { }
OPTRACE "read constraints: place_design_post" END { }
OPTRACE "Place Design: write_checkpoint" START { CHECKPOINT }
write_checkpoint -force top_placed.dcp
OPTRACE "Place Design: write_checkpoint" END { }
OPTRACE "place_design reports" START { REPORT }
create_report "impl_1_place_report_io_0" "report_io -file top_io_placed.rpt"
create_report "impl_1_place_report_utilization_0" "report_utilization -file top_utilization_placed.rpt -pb top_utilization_placed.pb"
create_report "impl_1_place_report_control_sets_0" "report_control_sets -verbose -file top_control_sets_placed.rpt"
OPTRACE "place_design reports" END { }
close_msg_db -file place_design.pb
} RESULT]
if {$rc} {
step_failed place_design
return -code error $RESULT
} else {
end_step place_design
unset ACTIVE_STEP
}
OPTRACE "Phase: Place Design" END { }
OPTRACE "Phase: Physical Opt Design" START { ROLLUP_AUTO }
start_step phys_opt_design
set ACTIVE_STEP phys_opt_design
set rc [catch {
create_msg_db phys_opt_design.pb
OPTRACE "read constraints: phys_opt_design" START { }
OPTRACE "read constraints: phys_opt_design" END { }
OPTRACE "phys_opt_design" START { }
phys_opt_design
OPTRACE "phys_opt_design" END { }
OPTRACE "read constraints: phys_opt_design_post" START { }
OPTRACE "read constraints: phys_opt_design_post" END { }
OPTRACE "Post-Place Phys Opt Design: write_checkpoint" START { CHECKPOINT }
write_checkpoint -force top_physopt.dcp
OPTRACE "Post-Place Phys Opt Design: write_checkpoint" END { }
OPTRACE "phys_opt_design report" START { REPORT }
OPTRACE "phys_opt_design report" END { }
close_msg_db -file phys_opt_design.pb
} RESULT]
if {$rc} {
step_failed phys_opt_design
return -code error $RESULT
} else {
end_step phys_opt_design
unset ACTIVE_STEP
}
OPTRACE "Phase: Physical Opt Design" END { }
OPTRACE "Phase: Route Design" START { ROLLUP_AUTO }
start_step route_design
set ACTIVE_STEP route_design
set rc [catch {
create_msg_db route_design.pb
OPTRACE "read constraints: route_design" START { }
OPTRACE "read constraints: route_design" END { }
OPTRACE "route_design" START { }
route_design
OPTRACE "route_design" END { }
OPTRACE "read constraints: route_design_post" START { }
OPTRACE "read constraints: route_design_post" END { }
OPTRACE "Route Design: write_checkpoint" START { CHECKPOINT }
write_checkpoint -force top_routed.dcp
OPTRACE "Route Design: write_checkpoint" END { }
OPTRACE "route_design reports" START { REPORT }
create_report "impl_1_route_report_drc_0" "report_drc -file top_drc_routed.rpt -pb top_drc_routed.pb -rpx top_drc_routed.rpx"
create_report "impl_1_route_report_methodology_0" "report_methodology -file top_methodology_drc_routed.rpt -pb top_methodology_drc_routed.pb -rpx top_methodology_drc_routed.rpx"
create_report "impl_1_route_report_power_0" "report_power -file top_power_routed.rpt -pb top_power_summary_routed.pb -rpx top_power_routed.rpx"
create_report "impl_1_route_report_route_status_0" "report_route_status -file top_route_status.rpt -pb top_route_status.pb"
create_report "impl_1_route_report_timing_summary_0" "report_timing_summary -max_paths 10 -file top_timing_summary_routed.rpt -pb top_timing_summary_routed.pb -rpx top_timing_summary_routed.rpx -warn_on_violation "
create_report "impl_1_route_report_incremental_reuse_0" "report_incremental_reuse -file top_incremental_reuse_routed.rpt"
create_report "impl_1_route_report_clock_utilization_0" "report_clock_utilization -file top_clock_utilization_routed.rpt"
create_report "impl_1_route_report_bus_skew_0" "report_bus_skew -warn_on_violation -file top_bus_skew_routed.rpt -pb top_bus_skew_routed.pb -rpx top_bus_skew_routed.rpx"
OPTRACE "route_design reports" END { }
OPTRACE "route_design misc" START { }
close_msg_db -file route_design.pb
OPTRACE "route_design write_checkpoint" START { CHECKPOINT }
OPTRACE "route_design write_checkpoint" END { }
} RESULT]
if {$rc} {
write_checkpoint -force top_routed_error.dcp
step_failed route_design
return -code error $RESULT
} else {
end_step route_design
unset ACTIVE_STEP
}
OPTRACE "route_design misc" END { }
OPTRACE "Phase: Route Design" END { }
OPTRACE "Phase: Write Bitstream" START { ROLLUP_AUTO }
OPTRACE "write_bitstream setup" START { }
start_step write_bitstream
set ACTIVE_STEP write_bitstream
set rc [catch {
create_msg_db write_bitstream.pb
OPTRACE "read constraints: write_bitstream" START { }
OPTRACE "read constraints: write_bitstream" END { }
catch { write_mem_info -force top.mmi }
OPTRACE "write_bitstream setup" END { }
OPTRACE "write_bitstream" START { }
write_bitstream -force top.bit
OPTRACE "write_bitstream" END { }
OPTRACE "write_bitstream misc" START { }
OPTRACE "read constraints: write_bitstream_post" START { }
OPTRACE "read constraints: write_bitstream_post" END { }
catch {write_debug_probes -quiet -force top}
catch {file copy -force top.ltx debug_nets.ltx}
close_msg_db -file write_bitstream.pb
} RESULT]
if {$rc} {
step_failed write_bitstream
return -code error $RESULT
} else {
end_step write_bitstream
unset ACTIVE_STEP
}
OPTRACE "write_bitstream misc" END { }
OPTRACE "Phase: Write Bitstream" END { }
OPTRACE "Implementation" END { }
| high | 0.600334 | 327 |
private
tag: anObject
tag := anObject | low | 0.519876 | 328 |
// Copyright (c) 2008- 2010 Bluespec, Inc. All rights reserved.
package FIFOLevel ;
import FIFOF_ :: * ;
import GetPut :: * ;
export FIFOLevelIfc(..) ;
export mkFIFOLevel ;
export mkGFIFOLevel ;
export SyncFIFOLevelIfc(..) ;
export mkSyncFIFOLevel ;
export FIFOCountIfc(..) ;
export mkFIFOCount ;
export mkGFIFOCount ;
export SyncFIFOCountIfc(..) ;
export mkSyncFIFOCount ;
export mkGSyncFIFOCount ;
//@ \subsubsection{Level FIFO}
//@ \index{Clocks@\te{LevelFIFO} (package)|textbf}
//@
//@ The BSV \te{LevelFIFO} library provides FIFO interfaces and modules
//@ which include methods to indicate the level or the current number
//@ of items stored in the FIFO. Two versions are included in this
//@ package, the first for a single clock, and the second for
//@ dual clocks. The interface and module definitions are detailed
//@ below.
//@
//@ \index{FIFOLevelIfc@\te{FIFOLevelIfc} (interface)|textbf}
//@ In addition to common FIFO methods, the \te{FIFOLevelIfc}
//@ interface defines methods to compare the current level to
//@ \te{Integer} constants.
//@ Note that \te{FIFOLevelIfc} interface has a parameter for the
//@ fifoDepth. This numeric type parameter is needed, since the width
//@ of the counter is dependant on the FIFO depth.
//@ # 15
interface FIFOLevelIfc#( type a_type, numeric type fifoDepth ) ;
method Action enq( a_type x1 );
method Action deq();
method a_type first();
method Action clear();
method Bool notFull ;
method Bool notEmpty ;
method Bool isLessThan ( Integer c1 ) ;
method Bool isGreaterThan( Integer c1 ) ;
// method UInt#(TLog#(fifoDepth)) maxDepth ;
endinterface
//@
//@ \index{mkFIFOLevel@\te{mkFIFOLevel} (module)|textbf}
//@ The module mkFIFOLevel
//@
//@ # 3
module mkFIFOLevel( FIFOLevelIfc#(a_type, fifoDepth) )
provisos( Bits#(a_type, sa ), // Can convert to Bits
Log#(TAdd#(fifoDepth,1),cntSize)
) ; // Get the width from the depth
Integer ififoDepth = (valueOf( fifoDepth ) < 3 ?
(error ("mkFIFOLevel: fifoDepth must be greater than 2. " +
"Specified depth is " + integerToString( valueOf(fifoDepth)) + "." ) ) :
valueOf( fifoDepth ) );
FIFOLevel_INT#(a_type, cntSize)
_fifoLevel <- vbFIFOLevel( ififoDepth ) ;
Reg#(Bool) levelsValid <- mkReg(True);
PulseWire doResetEnq <- mkPulseWire;
PulseWire doResetDeq <- mkPulseWire;
PulseWire doResetClr <- mkPulseWire;
Bool doReset = doResetEnq || doResetDeq || doResetClr;
rule reset(doReset);
levelsValid <= True;
endrule
method Action enq( a_type x ) if ( _fifoLevel.i_notFull ) ;
_fifoLevel.enq( x ) ;
levelsValid <= False;
doResetEnq.send;
endmethod
method Action deq if ( _fifoLevel.i_notEmpty ) ;
_fifoLevel.deq ;
levelsValid <= False;
doResetDeq.send;
endmethod
method first if ( _fifoLevel.i_notEmpty ) ;
return _fifoLevel.first ;
endmethod
method Action clear;
_fifoLevel.clear ;
levelsValid <= False;
doResetClr.send;
endmethod
method notFull = _fifoLevel.notFull ;
method notEmpty = _fifoLevel.notEmpty ;
method Bool isLessThan ( Integer c1 ) if (levelsValid) ;
return rangeTest( _fifoLevel.i_count, c1, \< , 1, ififoDepth , "isLessThan" ) ;
endmethod
method Bool isGreaterThan ( Integer c1 ) if (levelsValid) ;
return rangeTest( _fifoLevel.i_count, c1, \> , 0, ififoDepth -1 , "isGreaterThan" ) ;
endmethod
// method maxDepth ;
// return fromInteger( ififoDepth );
// endmethod
endmodule
module mkGFIFOLevel#(Bool ugenq, Bool ugdeq, Bool ugcount)( FIFOLevelIfc#(a_type, fifoDepth) )
provisos( Bits#(a_type, sa ), // Can convert to Bits
Log#(TAdd#(fifoDepth,1),cntSize)
) ; // Get the width from the depth
Integer ififoDepth = (valueOf( fifoDepth ) < 3 ?
(error ("mkFIFOLevel: fifoDepth must be greater than 2. " +
"Specified depth is " + integerToString( valueOf(fifoDepth)) + "." ) ) :
valueOf( fifoDepth ) );
FIFOLevel_INT#(a_type, cntSize)
_fifoLevel <- vbFIFOLevel( ififoDepth ) ;
Action enqGuard = noAction ;
Action deqGuard = noAction ;
Action clrGuard = noAction ;
Bool levelsValid = ? ;
if ( ugcount )
begin
enqGuard = noAction ;
deqGuard = noAction ;
clrGuard = noAction ;
levelsValid = True ;
end
else
begin
Reg#(Bool) levelsValid_virtual_Reg <- mkReg(True);
PulseWire doResetEnq <- mkPulseWire;
PulseWire doResetDeq <- mkPulseWire;
PulseWire doResetClr <- mkPulseWire;
Bool doReset = doResetEnq || doResetDeq || doResetClr;
rule reset(doReset);
levelsValid_virtual_Reg <= True;
endrule
enqGuard = (action
levelsValid_virtual_Reg <= False;
doResetEnq.send;
endaction);
deqGuard = (action
levelsValid_virtual_Reg <= False;
doResetDeq.send;
endaction);
clrGuard = (action
levelsValid_virtual_Reg <= False;
doResetClr.send;
endaction);
levelsValid = levelsValid_virtual_Reg._read ;
end
method Action enq( a_type x ) if ( _fifoLevel.i_notFull || ugenq ) ;
_fifoLevel.enq( x ) ;
enqGuard ;
endmethod
method Action deq if ( _fifoLevel.i_notEmpty || ugdeq) ;
_fifoLevel.deq ;
deqGuard ;
endmethod
method first if ( _fifoLevel.i_notEmpty || ugdeq) ;
return _fifoLevel.first ;
endmethod
method Action clear;
_fifoLevel.clear ;
clrGuard ;
endmethod
method notFull = _fifoLevel.notFull ;
method notEmpty = _fifoLevel.notEmpty ;
method Bool isLessThan ( Integer c1 ) if (levelsValid) ;
return rangeTest( _fifoLevel.i_count, c1, \< , 1, ififoDepth , "isLessThan" ) ;
endmethod
method Bool isGreaterThan ( Integer c1 ) if (levelsValid) ;
return rangeTest( _fifoLevel.i_count, c1, \> , 0, ififoDepth -1 , "isGreaterThan" ) ;
endmethod
endmodule
//@ \index{SyncFIFOLevelIfc@\te{SyncFIFOLevelIfc} (interface)|textbf}
//@ In addition to common FIFO methods, the \te{SyncFIFOLevelIfc}
//@ interface defines methods to compare the current level to
//@ \te{Integer} constants. Methods are provided for both the source
//@ (enqueue side) and destination (dequeue side) clock domains.
//@
//@ Note that \te{SyncFIFOLevelIfc} interface has a parameter for the
//@ fifoDepth. This numeric type parameter is needed, since the width
//@ of the counter is dependant on the FIFO depth.
//@ # 19
interface SyncFIFOLevelIfc#( type a_type, numeric type fifoDepth ) ;
method Action enq ( a_type sendData ) ;
method Action deq () ;
method a_type first () ;
method Bool sNotFull ;
method Bool sNotEmpty ;
method Bool dNotFull ;
method Bool dNotEmpty ;
// Note that for the following methods, the Integer argument must
// be a compile-time constant.
method Bool sIsLessThan ( Integer c1 ) ;
method Bool sIsGreaterThan( Integer c1 ) ;
method Bool dIsLessThan ( Integer c1 ) ;
method Bool dIsGreaterThan( Integer c1 ) ;
method Action sClear ;
method Action dClear ;
endinterface
//@
//@ \index{mkSyncFIFOLevel@\te{mkSyncFIFOLevel} (module)|textbf}
//@ The module mkSyncFIFOLevel is dual clock FIFO, where enqueue and
//@ dequeue methods are in separate clocks domains -- sClkIn and
//@ dClkIn respectively. Because of the synchronization latency, the
//@ flag indicators will not necessarily be identical in value. Note
//@ however, that the sNotFull and dNotEmpty flags always give proper
//@ (pessimistic) indication for the safe use of enq and deq methods;
//@ these
//@ are automatically included as implicit condition in the enq and deq
//@ (and first) methods.
//@ # 6
module mkSyncFIFOLevel(
Clock sClkIn, Reset sRstIn,
Clock dClkIn,
SyncFIFOLevelIfc#(a_type, fifoDepth) ifc )
provisos( Bits#(a_type, sa), // Can convert into Bits
Log#(TAdd#(fifoDepth,1), cntSize) // Get the count width from the depth
) ;
Integer ififoDepth = valueOf( fifoDepth ) ;
SyncFIFOCount_INT#(a_type, cntSize) _syncFifo;
if (valueOf(sa) == 0) begin
(*hide*)
SyncFIFOCount0_INT#(cntSize) _ifc0 <- vSyncFIFOCount0( ififoDepth, sClkIn, sRstIn, dClkIn ) ;
_syncFifo = fromSyncFIFOCount0_INT( _ifc0 ) ;
end
else begin
(*hide*)
_syncFifo <- vSyncFIFOCount( ififoDepth, sClkIn, sRstIn, dClkIn ) ;
end
method Action enq(a_type x) if (_syncFifo.sNotFull);
_syncFifo.enq(x);
endmethod
method Action deq() if (_syncFifo.dNotEmpty);
_syncFifo.deq;
endmethod
method a_type first() if (_syncFifo.dNotEmpty);
return _syncFifo.first;
endmethod
method Bool sNotFull = _syncFifo.sNotFull ;
method Bool dNotEmpty = _syncFifo.dNotEmpty ;
method Bool sNotEmpty ;
return (_syncFifo.sCount != 0 );
endmethod
method Bool dNotFull ;
return _syncFifo.dCount != fromInteger( valueOf(fifoDepth) ) ;
endmethod
method Bool sIsLessThan( Integer x ) ;
return rangeTest( _syncFifo.sCount, x, \< , 1, ififoDepth, "sIsLessThan" ) ;
endmethod
method Bool dIsLessThan( Integer x ) ;
return rangeTest( _syncFifo.dCount, x, \< , 1, ififoDepth, "dIsLessThan" ) ;
endmethod
method Bool sIsGreaterThan( Integer x ) ;
return rangeTest( _syncFifo.sCount, x, \> , 0, ififoDepth-1, "sIsGreaterThan" ) ;
endmethod
method Bool dIsGreaterThan( Integer x ) ;
return rangeTest( _syncFifo.dCount, x, \> , 0, ififoDepth-1, "dIsGreaterThan" ) ;
endmethod
method Action sClear ;
_syncFifo.sClear ;
endmethod
method Action dClear ;
_syncFifo.dClear ;
endmethod
endmodule
// An internal Interface used for import BVI spec.
interface FIFOLevel_INT #(type a_type, numeric type cntSize ) ;
method Action enq( a_type sendData );
method Action deq() ;
method a_type first() ;
method Action clear() ;
// these follow stricter TRS rule
method Bool notFull ;
method Bool notEmpty ;
method UInt#(cntSize) count ;
// these always give non conflicting values at beginning of cycle
method Bool i_notFull ;
method Bool i_notEmpty ;
method UInt#(cntSize) i_count ;
endinterface
// A BSV wrapper for mkSizedFIFOF_ which adds the level features
module vbFIFOLevel#( Integer depthIn )
( FIFOLevel_INT#(a,cntSize) ifc)
provisos ( Bits#(a,sa) ) ;
FIFOF_#(a) _fifc <- mkSizedFIFOF_( depthIn, 1) ;
Reg#(UInt#(cntSize)) countReg <- mkReg( 0 ) ;
PulseWire r_enq <- mkPulseWire ;
PulseWire r_deq <- mkPulseWire ;
PulseWire r_clr <- mkPulseWire ;
rule _updateLevelCounter ( (r_enq != r_deq) || r_clr ) ;
countReg <= r_clr ? 0 : ((r_enq) ? (countReg + 1) : (countReg -1 )) ;
endrule
method Action enq( a sendData );
_fifc.enq( sendData ) ;
r_enq.send ;
endmethod
method Action deq() ;
_fifc.deq() ;
r_deq.send ;
endmethod
method a first() ;
return _fifc.first ;
endmethod
method Action clear() ;
_fifc.clear();
r_clr.send ;
endmethod
// these follow stricter TRS rule
method Bool notFull ;
return _fifc.notFull ;
endmethod
method Bool notEmpty ;
return _fifc.notEmpty ;
endmethod
method UInt#(cntSize) count ;
return countReg ;
endmethod
// these always give non conflicting values at beginning of cycle
method Bool i_notFull ;
return _fifc.i_notFull ;
endmethod
method Bool i_notEmpty ;
return _fifc.i_notEmpty ;
endmethod
method UInt#(cntSize) i_count ;
return countReg ;
endmethod
endmodule
// Common function to test the validity arguments to methods
function Bool rangeTest( UInt#(cntSz) value,
Integer comp,
function Bool foperation(UInt#(cntSz) a,
UInt#(cntSz) b ),
Integer minValue,
Integer maxValue,
String methodName );
return ((comp >= minValue) && (comp <= maxValue )) ?
(foperation (value, fromInteger( comp ))) :
error( "Argument of " + methodName + " must be in the range of " +
integerToString( minValue) +
" to " +
integerToString( maxValue ) +
"; " +
integerToString( comp ) +
" is out of range.") ;
endfunction
/* -----\/----- EXCLUDED -----\/-----
typedef Bit#(17) T ;
typedef 5 CntSz ;
(* synthesize *)
module mkTest () ;
Clock clk <- exposeCurrentClock ;
Reset rst <- exposeCurrentReset ;
SyncFIFOCount_INT#(T,CntSz) fifo <- vSyncFIFOCount( 12, clk, rst, clk ) ;
Reg#(UInt#(CntSz)) cnt <- mkReg(0) ;
rule test ;
cnt <= fifo.sCount ;
$display( "foo is %d", cnt ) ;
endrule
endmodule
-----/\----- EXCLUDED -----/\----- */
//@
/* -----\/----- EXCLUDED -----\/-----
(* synthesize *)
module mkTest2 () ;
Clock clk <- exposeCurrentClock ;
Reset rst <- exposeCurrentReset ;
Clock clk2 = clk ;
// Define a fifo of Int(#23) with 128 entries
SyncFIFOLevelIfc#(Int#(23),128) fifo <- mkSyncFIFOLevel( clk, rst, clk2 ) ;
// Define some constants
let sAlmostFull = fifo.sIsGreaterThan( 120 ) ;
let dAlmostFull = fifo.sIsGreaterThan( 120 ) ;
let dAlmostEmpty = fifo.dIsLessThan( 12 ) ;
// a register to indicate a burst mode
Reg#(Bool) burstOut <- mkReg( False ) ;
// Set and clear the burst mode depending on fifo status
rule timeToDeque( dAlmostFull && ! burstOut ) ;
burstOut <= True ;
endrule
rule timeToStop ( dAlmostEmpty && burstOut );
burstOut <= False ;
endrule
rule moveData ( burstOut ) ;
let dataToSend = fifo.first ;
fifo.deq ;
// bursting.send( dataToSend ) ;
endrule
Reg#(UInt#(CntSz)) cnt <- mkReg(0) ;
rule test ( ! fifo.sIsLessThan( 6 ) ) ;
$display( "greater than 5 " ) ;
endrule
rule test1 ( ! fifo.sIsLessThan( 1 ) ) ;
$display( "greater than 5 " ) ;
endrule
rule test2 ( ! fifo.sIsLessThan( 6 ) ) ;
$display( "greater than 5 " ) ;
endrule
rule test3 ( ! fifo.sIsLessThan( 6 ) ) ;
$display( "greater than 5 " ) ;
endrule
rule test3g ( ! fifo.sIsGreaterThan( 6 ) ) ;
$display( "greater than 5 " ) ;
endrule
rule test4 ( ! fifo.sIsLessThan( 3 ) ) ;
$display( "greater than 5 " ) ;
endrule
rule test5 ( ! fifo.sIsLessThan( 4 ) ) ;
$display( "greater than 5 " ) ;
endrule
// type error since we require an Integer
// rule testX ( ! fifo.levels.sIsLessThan( cnt ) ) ;
// $display( "greater than 5 " ) ;
// endrule
endmodule
-----/\----- EXCLUDED -----/\----- */
//@ \begin{itemize}
//@ \item{\bf Example}
//@
//@ The following example shows the use of \te{SyncLevelFIFO} as a way
//@ to collect data into a FIFO, and then send it out in a burst mode. The
//@ portion of the design shown, waits until the FIFO is almost
//@ full, and then sets a register, {\tt burstOut} which indicates
//@ that the FIFO should dequeue. When the FIFO is almost empty, the
//@ flag is cleared, and FIFO fills again.
//@
//@ \begin{libverbatim}
//@ . . .
//@ // Define a fifo of Int(#23) with 128 entries
//@ SyncFIFOLevelIfc#(Int#(23),128) fifo <- mkSyncFIFOLevel( clk, rst, clk2 ) ;
//@
//@ // Define some constants
//@ let sFifoAlmostFull = fifo.sIsGreaterThan( 120 ) ;
//@ let dFifoAlmostFull = fifo.dIsGreaterThan( 120 ) ;
//@ let dFifoAlmostEmpty = fifo.dIsLessThan( 12 ) ;
//@
//@ // a register to indicate a burst mode
//@ Reg#(Bool) burstOut <- mkReg( False ) ;
//@
//@ . . .
//@ // Set and clear the burst mode depending on fifo status
//@ rule timeToDeque( dFifoAlmostFull && ! burstOut ) ;
//@ burstOut <= True ;
//@ endrule
//@
//@ rule timeToStop ( dFifoAlmostEmpty && burstOut );
//@ burstOut <= False ;
//@ endrule
//@
//@ rule moveData ( burstOut ) ;
//@ let dataToSend = fifo.first ;
//@ fifo.deq ;
//@ ...
//@ bursting.send( dataToSend ) ;
//@ endrule
//@ \end{libverbatim}
//@ \end{itemize}
// TODO Add single clock version of this fifo
interface FIFOCountIfc#( type a_type, numeric type fifoDepth) ;
method Action enq ( a_type sendData ) ;
method Action deq () ;
method a_type first () ;
method Bool notFull ;
method Bool notEmpty ;
method UInt#(TLog#(TAdd#(fifoDepth,1))) count;
method Action clear;
endinterface
module mkFIFOCount( FIFOCountIfc#(a_type, fifoDepth) ifc )
provisos (Bits#(a_type,sa));
Integer ififoDepth = (valueOf( fifoDepth ) < 3 ?
(error ("mkFIFOLevel: fifoDepth must be greater than 2. " +
"Specified depth is " + integerToString( valueOf(fifoDepth)) + "." ) ) :
valueOf( fifoDepth ) );
FIFOLevel_INT#(a_type, (TLog#(TAdd#(fifoDepth,1))))
_fifoLevel <- vbFIFOLevel( ififoDepth ) ;
Reg#(Bool) levelsValid <- mkReg(True); // Needed only for scheduling
PulseWire doResetEnq <- mkPulseWire;
PulseWire doResetDeq <- mkPulseWire;
PulseWire doResetClr <- mkPulseWire;
Bool doReset = doResetEnq || doResetDeq || doResetClr;
rule reset(doReset);
levelsValid <= True;
endrule
method Action enq( a_type x ) if ( _fifoLevel.i_notFull ) ;
_fifoLevel.enq( x ) ;
levelsValid <= False;
doResetEnq.send;
endmethod
method Action deq if ( _fifoLevel.i_notEmpty ) ;
_fifoLevel.deq ;
levelsValid <= False;
doResetDeq.send;
endmethod
method first if ( _fifoLevel.i_notEmpty ) ;
return _fifoLevel.first ;
endmethod
method Action clear;
_fifoLevel.clear ;
levelsValid <= False;
doResetClr.send;
endmethod
method notFull = _fifoLevel.notFull ;
method notEmpty = _fifoLevel.notEmpty ;
method count if(levelsValid);
return _fifoLevel.i_count ;
endmethod
endmodule
module mkGFIFOCount#(Bool ugenq, Bool ugdeq, Bool ugcount)( FIFOCountIfc#(a_type, fifoDepth) ifc )
provisos (Bits#(a_type,sa));
Integer ififoDepth = (valueOf( fifoDepth ) < 3 ?
(error ("mkFIFOLevel: fifoDepth must be greater than 2. " +
"Specified depth is " + integerToString( valueOf(fifoDepth)) + "." ) ) :
valueOf( fifoDepth ) );
FIFOLevel_INT#(a_type, (TLog#(TAdd#(fifoDepth,1))))
_fifoLevel <- vbFIFOLevel( ififoDepth ) ;
Action enqGuard = noAction ;
Action deqGuard = noAction ;
Action clrGuard = noAction ;
Bool levelsValid = ? ;
if ( ugcount )
begin
enqGuard = noAction ;
deqGuard = noAction ;
clrGuard = noAction ;
levelsValid = True ;
end
else
begin
Reg#(Bool) levelsValid_virtual_Reg <- mkReg(True);
PulseWire doResetEnq <- mkPulseWire;
PulseWire doResetDeq <- mkPulseWire;
PulseWire doResetClr <- mkPulseWire;
Bool doReset = doResetEnq || doResetDeq || doResetClr;
rule reset(doReset);
levelsValid_virtual_Reg <= True;
endrule
enqGuard = (action
levelsValid_virtual_Reg <= False;
doResetEnq.send;
endaction);
deqGuard = (action
levelsValid_virtual_Reg <= False;
doResetDeq.send;
endaction);
clrGuard = (action
levelsValid_virtual_Reg <= False;
doResetClr.send;
endaction);
levelsValid = levelsValid_virtual_Reg._read ;
end
method Action enq( a_type x ) if ( _fifoLevel.i_notFull || ugenq ) ;
_fifoLevel.enq( x ) ;
enqGuard ;
endmethod
method Action deq if ( _fifoLevel.i_notEmpty || ugdeq ) ;
_fifoLevel.deq ;
deqGuard;
endmethod
method first if ( _fifoLevel.i_notEmpty || ugdeq ) ;
return _fifoLevel.first ;
endmethod
method Action clear;
_fifoLevel.clear ;
clrGuard;
endmethod
method notFull = _fifoLevel.notFull ;
method notEmpty = _fifoLevel.notEmpty ;
method count if(levelsValid);
return _fifoLevel.i_count ;
endmethod
endmodule
interface SyncFIFOCountIfc#( type a_type, numeric type fifoDepth) ;
method Action enq ( a_type sendData ) ;
method Action deq () ;
method a_type first () ;
method Bool sNotFull ;
method Bool sNotEmpty ;
method Bool dNotFull ;
method Bool dNotEmpty ;
method UInt#(TLog#(TAdd#(fifoDepth,1))) sCount;
method UInt#(TLog#(TAdd#(fifoDepth,1))) dCount;
method Action sClear;
method Action dClear;
endinterface
module mkSyncFIFOCount(
Clock sClkIn, Reset sRstIn,
Clock dClkIn,
SyncFIFOCountIfc#(a_type, fifoDepth) ifc )
provisos( Bits#(a_type, sa), // Can convert into Bits
Log#(TAdd#(fifoDepth,1), cntSize) // Get the count width from the depth
) ;
Integer ififoDepth = valueOf( fifoDepth ) ;
SyncFIFOCount_INT#(a_type, cntSize) _syncFifo;
if (valueOf(sa) == 0) begin
(*hide*)
SyncFIFOCount0_INT#(cntSize) _ifc0 <- vSyncFIFOCount0( ififoDepth, sClkIn, sRstIn, dClkIn ) ;
_syncFifo = fromSyncFIFOCount0_INT( _ifc0 ) ;
end
else begin
(*hide*)
_syncFifo <- vSyncFIFOCount( ififoDepth, sClkIn, sRstIn, dClkIn ) ;
end
method Action enq(a_type x) if (_syncFifo.sNotFull);
_syncFifo.enq(x);
endmethod
method Action deq() if (_syncFifo.dNotEmpty);
_syncFifo.deq();
endmethod
method a_type first() if (_syncFifo.dNotEmpty);
return _syncFifo.first;
endmethod
method Bool sNotFull = _syncFifo.sNotFull ;
method Bool dNotEmpty = _syncFifo.dNotEmpty ;
method Bool sNotEmpty ;
return (_syncFifo.sCount != 0 );
endmethod
method Bool dNotFull ;
return _syncFifo.dCount != fromInteger( valueOf(fifoDepth) ) ;
endmethod
method sCount ;
return _syncFifo.sCount;
endmethod
method dCount ;
return _syncFifo.dCount;
endmethod
method Action sClear;
_syncFifo.sClear;
endmethod
method Action dClear;
_syncFifo.dClear;
endmethod
endmodule
module mkGSyncFIFOCount#( Bool ugenq, Bool ugdeq )
( Clock sClkIn, Reset sRstIn,
Clock dClkIn,
SyncFIFOCountIfc#(a_type, fifoDepth) ifc )
provisos( Bits#(a_type, sa), // Can convert into Bits
Log#(TAdd#(fifoDepth,1), cntSize) // Get the count width from the depth
) ;
Integer ififoDepth = valueOf( fifoDepth ) ;
SyncFIFOCount_INT#(a_type, cntSize) _syncFifo;
if (valueOf(sa) == 0) begin
(*hide*)
SyncFIFOCount0_INT#(cntSize) _ifc0 <- vSyncFIFOCount0( ififoDepth, sClkIn, sRstIn, dClkIn ) ;
_syncFifo = fromSyncFIFOCount0_INT( _ifc0 ) ;
end
else begin
(*hide*)
_syncFifo <- vSyncFIFOCount( ififoDepth, sClkIn, sRstIn, dClkIn ) ;
end
method Action enq(a_type x) if (_syncFifo.sNotFull || ugenq);
_syncFifo.enq(x);
endmethod
method Action deq() if (_syncFifo.dNotEmpty || ugdeq);
_syncFifo.deq();
endmethod
method a_type first() if (_syncFifo.dNotEmpty || ugdeq);
return _syncFifo.first;
endmethod
method Bool sNotFull = _syncFifo.sNotFull ;
method Bool dNotEmpty = _syncFifo.dNotEmpty ;
method Bool sNotEmpty ;
return (_syncFifo.sCount != 0 );
endmethod
method Bool dNotFull ;
return _syncFifo.dCount != fromInteger( valueOf(fifoDepth) ) ;
endmethod
method sCount ;
return _syncFifo.sCount;
endmethod
method dCount ;
return _syncFifo.dCount;
endmethod
method Action sClear;
_syncFifo.sClear;
endmethod
method Action dClear;
_syncFifo.dClear;
endmethod
endmodule
// An internal Interface used for import BVI spec.
interface SyncFIFOCount_INT #(type a_type, numeric type cntSize ) ;
method Action enq( a_type sendData );
method Action deq() ;
method a_type first() ;
method Bool sNotFull ;
method Bool dNotEmpty ;
method UInt#(cntSize) sCount ;
method UInt#(cntSize) dCount ;
method Action sClear;
method Action dClear;
endinterface
// A variant for zero-width data
interface SyncFIFOCount0_INT #( numeric type cntSize ) ;
method Action enq();
method Action deq() ;
method Bool sNotFull ;
method Bool dNotEmpty ;
method UInt#(cntSize) sCount ;
method UInt#(cntSize) dCount ;
method Action sClear;
method Action dClear;
endinterface
function SyncFIFOCount_INT#(a,n) fromSyncFIFOCount0_INT (SyncFIFOCount0_INT#(n) ifc0);
return (interface SyncFIFOCount_INT;
method enq(sendData) = ifc0.enq;
method deq() = ifc0.deq;
method first() = ?;
method sNotFull() = ifc0.sNotFull;
method dNotEmpty() = ifc0.dNotEmpty;
method sCount() = ifc0.sCount;
method dCount() = ifc0.dCount;
method sClear() = ifc0.sClear;
method dClear() = ifc0.dClear;
endinterface);
endfunction
import "BVI" SyncFIFOLevel =
module vSyncFIFOCount#( Integer depthIn
) (Clock sClkIn, Reset sRstIn,
Clock dClkIn,
SyncFIFOCount_INT#(a,cntSize) ifc)
provisos ( Bits#(a,sa) ) ;
let logDepth = log2( depthIn ) ;
let pwrDepth = 2 ** logDepth ;
if (pwrDepth < 2) error( "mkSyncFIFOLevel depth must be greater than 1 for correct operation" ) ;
let depthErr = ("SyncFIFOCount depth must be power of 2. Please increased from "
+ integerToString (depthIn) + " to "
+ integerToString (pwrDepth) + "." );
let realDepth = (( depthIn == pwrDepth ) ? pwrDepth :
error ( depthErr )) ;
let indxErr = ( "SyncFIFOCount: indicator widths have wrong size specified: "
+ "width is "
+ integerToString ( valueOf(cntSize))
+ " and it must be: "
+ integerToString ( log2 (realDepth + 1) )
);
parameter dataWidth = valueOf( sa ) ;
parameter depth = realDepth ; // must be power of 2 !
parameter indxWidth = (log2(realDepth + 1) == valueOf(cntSize)) ? logDepth :
error (indxErr);
default_clock no_clock ;
no_reset ;
input_clock clk_src ( sCLK, (*unused*)sCLK_GATE ) = sClkIn;
input_clock clk_dst ( dCLK, (*unused*)dCLK_GATE ) = dClkIn;
input_reset (sRST) clocked_by (clk_src) = sRstIn ;
method enq ( sD_IN ) enable(sENQ) clocked_by(clk_src) reset_by(sRstIn);
method deq () enable(dDEQ) clocked_by(clk_dst) reset_by(no_reset);
method dD_OUT first() clocked_by(clk_dst) reset_by(no_reset);
method sFULL_N sNotFull clocked_by(clk_src) reset_by(sRstIn);
method dEMPTY_N dNotEmpty clocked_by(clk_dst) reset_by(no_reset);
method dCOUNT dCount clocked_by(clk_dst) reset_by(no_reset);
method sCOUNT sCount clocked_by(clk_src) reset_by(sRstIn);
method sClear() ready(sCLR_RDY) enable (sCLR) clocked_by(clk_src) reset_by(sRstIn);
method dClear() ready(dCLR_RDY) enable (dCLR) clocked_by(clk_dst) reset_by(no_reset);
// Scheduling annotation
schedule first CF first ;
schedule first SB deq ;
// XXX reconsider the following
schedule enq C enq;
schedule enq CF sNotFull ;
schedule deq CF dNotEmpty ;
schedule (sNotFull, sCount) CF (sNotFull, sCount);
schedule dNotEmpty CF (first, dNotEmpty, dCount) ;
// Since the count are possibly stale, they are SB with enq and deq
schedule deq C deq ;
schedule dCount SB deq;
schedule dCount CF (first, dCount) ;
schedule sCount SB enq ;
// The clears must go after everything else
schedule (first, deq, dCount, dNotEmpty) SB dClear;
schedule (enq, sCount, sNotFull) SB sClear ;
schedule sClear CF sClear;
schedule dClear CF dClear;
// Cross domains are all conflict free
schedule (first, deq, dCount, dNotEmpty, dClear) CF (enq, sCount, sNotFull, sClear) ;
endmodule
// Version for data width 0
import "BVI" SyncFIFOLevel0 =
module vSyncFIFOCount0#( Integer depthIn
) (Clock sClkIn, Reset sRstIn,
Clock dClkIn,
SyncFIFOCount0_INT#(cntSize) ifc);
let logDepth = log2( depthIn ) ;
let pwrDepth = 2 ** logDepth ;
if (pwrDepth < 2) error( "mkSyncFIFOLevel depth must be greater than 1 for correct operation" ) ;
let depthErr = ("SyncFIFOCount depth must be power of 2. Please increased from "
+ integerToString (depthIn) + " to "
+ integerToString (pwrDepth) + "." );
let realDepth = (( depthIn == pwrDepth ) ? pwrDepth :
error ( depthErr )) ;
let indxErr = ( "SyncFIFOCount: indicator widths have wrong size specified: "
+ "width is "
+ integerToString ( valueOf(cntSize))
+ " and it must be: "
+ integerToString ( log2 (realDepth + 1) )
);
parameter depth = realDepth ; // must be power of 2 !
parameter indxWidth = (log2(realDepth + 1) == valueOf(cntSize)) ? logDepth :
error (indxErr);
default_clock no_clock ;
no_reset ;
input_clock clk_src ( sCLK, (*unused*)sCLK_GATE ) = sClkIn;
input_clock clk_dst ( dCLK, (*unused*)dCLK_GATE ) = dClkIn;
input_reset (sRST) clocked_by (clk_src) = sRstIn ;
method enq () enable(sENQ) clocked_by(clk_src) reset_by(sRstIn);
method deq () enable(dDEQ) clocked_by(clk_dst) reset_by(no_reset);
method sFULL_N sNotFull clocked_by(clk_src) reset_by(sRstIn);
method dEMPTY_N dNotEmpty clocked_by(clk_dst) reset_by(no_reset);
method dCOUNT dCount clocked_by(clk_dst) reset_by(no_reset);
method sCOUNT sCount clocked_by(clk_src) reset_by(sRstIn);
method sClear() ready(sCLR_RDY) enable (sCLR) clocked_by(clk_src) reset_by(sRstIn);
method dClear() ready(dCLR_RDY) enable (dCLR) clocked_by(clk_dst) reset_by(no_reset);
// Scheduling annotation
// XXX reconsider the following
schedule enq C enq;
schedule enq CF sNotFull ;
schedule deq CF dNotEmpty ;
schedule (sNotFull, sCount) CF (sNotFull, sCount);
schedule dNotEmpty CF (dNotEmpty, dCount) ;
// Since the count are possibly stale, they are SB with enq and deq
schedule deq C deq ;
schedule dCount SB deq;
schedule dCount CF dCount ;
schedule sCount SB enq ;
// The clears must go after everything else
schedule (deq, dCount, dNotEmpty) SB dClear;
schedule (enq, sCount, sNotFull) SB sClear ;
schedule sClear CF sClear;
schedule dClear CF dClear;
// Cross domains are all conflict free
schedule (deq, dCount, dNotEmpty, dClear) CF (enq, sCount, sNotFull, sClear) ;
endmodule
// Define instances of ToGet and ToPut for the intefaces defined in this package
instance ToGet #( FIFOLevelIfc#(a,n), a ) ;
function Get#(a) toGet (FIFOLevelIfc#(a,n) i);
return (interface Get;
method ActionValue#(a) get();
i.deq ;
return i.first ;
endmethod
endinterface);
endfunction
endinstance
instance ToPut #( FIFOLevelIfc#(a,n), a ) ;
function Put#(a) toPut (FIFOLevelIfc#(a,n) i);
return (interface Put;
method Action put(a x);
i.enq(x) ;
endmethod
endinterface);
endfunction
endinstance
instance ToGet #( SyncFIFOLevelIfc#(a,n), a ) ;
function Get#(a) toGet (SyncFIFOLevelIfc#(a,n) i);
return (interface Get;
method ActionValue#(a) get();
i.deq ;
return i.first ;
endmethod
endinterface);
endfunction
endinstance
instance ToPut #( SyncFIFOLevelIfc#(a,n), a ) ;
function Put#(a) toPut (SyncFIFOLevelIfc#(a,n) i);
return (interface Put;
method Action put(a x);
i.enq(x) ;
endmethod
endinterface);
endfunction
endinstance
instance ToGet #( FIFOCountIfc#(a,n), a ) ;
function Get#(a) toGet (FIFOCountIfc#(a,n) i);
return (interface Get;
method ActionValue#(a) get();
i.deq ;
return i.first ;
endmethod
endinterface);
endfunction
endinstance
instance ToPut #( FIFOCountIfc#(a,n), a ) ;
function Put#(a) toPut (FIFOCountIfc#(a,n) i);
return (interface Put;
method Action put(a x);
i.enq(x) ;
endmethod
endinterface);
endfunction
endinstance
instance ToGet #( SyncFIFOCountIfc#(a,n), a ) ;
function Get#(a) toGet (SyncFIFOCountIfc#(a,n) i);
return (interface Get;
method ActionValue#(a) get();
i.deq ;
return i.first ;
endmethod
endinterface);
endfunction
endinstance
instance ToPut #( SyncFIFOCountIfc#(a,n), a ) ;
function Put#(a) toPut (SyncFIFOCountIfc#(a,n) i);
return (interface Put;
method Action put(a x);
i.enq(x) ;
endmethod
endinterface);
endfunction
endinstance
endpackage
| high | 0.438565 | 329 |
SELECT '< HIVE-6386: Add owner filed to database >' AS ' ';
ALTER TABLE `DBS` ADD `OWNER_NAME` varchar(128);
ALTER TABLE `DBS` ADD `OWNER_TYPE` varchar(10);
| low | 0.543263 | 330 |
#lang scribble/doc
@(require "utils.rkt")
@title[#:tag-prefix '(lib "scribblings/inside/inside.scrbl")
#:tag "top"]{Inside: Racket C API}
@author["Matthew Flatt"]
This manual describes the C interface of Racket's runtime system,
which varies depending on the variant of Racket (see @secref[#:doc
'(lib "scribblings/guide/guide.scrbl") "virtual-machines"]): the CS
variant of Racket has one interface, while the BC (3m and CGC)
variants of Racket have another.
The C interface is relevant to some degree when interacting with
foreign libraries as described in @other-manual['(lib
"scribblings/foreign/foreign.scrbl")]. Even though interactions with
foreign code are constructed in pure Racket using the
@racketmodname[ffi/unsafe] module, many details of representations,
memory management, and concurrency are described here. This manual
also describes embedding the Racket run-time system in larger programs
and extending Racket directly with C-implemented libraries.
@table-of-contents[]
@; ------------------------------------------------------------------------
@include-section["cs.scrbl"]
@include-section["bc.scrbl"]
@include-section["appendix.scrbl"]
@; ------------------------------------------------------------------------
@index-section[]
| low | 0.252272 | 331 |
#lang syntax-parse-example
@require[
(for-label racket/base syntax/parse syntax-parse-example/fnarg/fnarg)]
@title{Function Parameter Syntax Class}
@stxbee2021["shhyou" 23]
@; =============================================================================
@defmodule[syntax-parse-example/fnarg/fnarg]{}
Syntax classes offer a powerful mechanism for abstracting over classes of
conceptually related patterns. Moreover, syntax classes can be parameterized,
with @racket[expr/c] being one prominent example.
In this example, we define a syntax class that roughly captures the grammar of
formal parameters in function headers. It parses the name of the formal
parameter, the default expressions of optional arguments and the keywords of
keyworded arguments.
@defidform[fnarg]{
The @racket[fnarg] syntax class matches the basic argument patterns that
can appear in function headers: mandatory, optional, and keyword arguments.
The class optionally accepts two parameters to toggle whether optional and/or
keyword arguments are allowed.
Refer to the source file @tt{fnarg-test.rkt} for an example use.
@racketfile{fnarg.rkt}
}
| high | 0.420709 | 332 |
rem *************************************************************
rem
rem Licensed to the Apache Software Foundation (ASF) under one
rem or more contributor license agreements. See the NOTICE file
rem distributed with this work for additional information
rem regarding copyright ownership. The ASF licenses this file
rem to you under the Apache License, Version 2.0 (the
rem "License"); you may not use this file except in compliance
rem with the License. You may obtain a copy of the License at
rem
rem http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing,
rem software distributed under the License is distributed on an
rem "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
rem KIND, either express or implied. See the License for the
rem specific language governing permissions and limitations
rem under the License.
rem
rem *************************************************************
Attribute VB_Name = "Module1"
Option Explicit
Sub main()
Dim obj As Object
Set obj = CreateObject("dcomtest.writerdemo.wsc")
obj.run
End Sub
| high | 0.371115 | 333 |
// This program to exercise the call of static and non-static methods. A partial code is given defining two methods, namely sum( ) and multiply ( ). You have to call these methods to find the sum and product of two numbers.
import java.util.Scanner;
class QuestionScope {
int sum(int a, int b){ //non-static method
return a + b;
}
static int multiply(int a, int b){ //static method
return a * b;
}
}
public class Test3{
public static void main( String[] args ) {
Scanner sc = new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
//Called the method sum() to find the sum of two numbers.
QuestionScope q = new QuestionScope();
int sum;
sum= q.sum(n1,n2);
//Called the method multiply() to find the product of two numbers.
int multy= q.multiply(n1,n2);
System.out.println(sum);
System.out.print(multy);
}
} | high | 0.462426 | 334 |
function Remove-ProjectLicenseFile {
[CmdletBinding()]
param (
[parameter(Mandatory)]
[xml]$CSProj
)
begin {
}
process {
$CSProj.Project.ItemGroup.EmbeddedResource | ForEach-Object {
if ($_.Include -eq "Properties\licenses.licx") {
$_.parentnode.RemoveChild($_) | out-null
}
}
}
end {
}
} | high | 0.480558 | 335 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Sofia Broomé | Project 1</title>
<meta name="description" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design.
">
<link rel="shortcut icon" href="/assets/img/favicon.ico">
<link rel="stylesheet" href="/assets/css/main.css">
<link rel="canonical" href="/projects/1_project/">
</head>
<body>
<header class="site-header">
<div class="wrapper">
<span class="site-title">
<strong>Sofia</strong> Broomé
</span>
<nav class="site-nav">
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger">
<span class="menu-icon">
<svg viewBox="0 0 18 15" width="18px" height="15px">
<path fill="#424242" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/>
<path fill="#424242" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/>
<path fill="#424242" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/>
</svg>
</span>
</label>
<div class="trigger">
<!-- About -->
<a class="page-link" href="/">about</a>
<!-- Blog -->
<a class="page-link" href="/blog/">blog</a>
<!-- Pages -->
<a class="page-link" href="/publications/">publications</a>
<a class="page-link" href="/teaching/">teaching</a>
<!-- CV link -->
<!-- <a class="page-link" href="/assets/pdf/CV.pdf">vitae</a> -->
</div>
</nav>
</div>
</header>
<div class="page-content">
<div class="wrapper">
<div class="post">
<header class="post-header">
<h1 class="post-title">Project 1</h1>
<h5 class="post-description">a project with a background image</h5>
</header>
<article class="post-content Project 1 clearfix">
<p>Every project has a beautiful feature shocase page. It’s easy to include images, in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.</p>
<p>To give your project a background in the portfolio page, just add the img tag to the front matter like so:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>---
layout: page
title: Project
description: a project with a background image
img: /assets/img/12.jpg
---
</code></pre></div></div>
<div class="img_row">
<img class="col one left" src="/assets/img/1.jpg" alt="" title="example image" />
<img class="col one left" src="/assets/img/2.jpg" alt="" title="example image" />
<img class="col one left" src="/assets/img/3.jpg" alt="" title="example image" />
</div>
<div class="col three caption">
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
</div>
<div class="img_row">
<img class="col three left" src="/assets/img/5.jpg" alt="" title="example image" />
</div>
<div class="col three caption">
This image can also have a caption. It's like magic.
</div>
<p>You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, <em>bled</em> for your project, and then…. you reveal it’s glory in the next row of images.</p>
<div class="img_row">
<img class="col two left" src="/assets/img/6.jpg" alt="" title="example image" />
<img class="col one left" src="/assets/img/11.jpg" alt="" title="example image" />
</div>
<div class="col three caption">
You can also have artistically styled 2/3 + 1/3 images, like these.
</div>
<p><br /><br /></p>
<p>The code is simple. Just add a col class to your image, and another class specifying the width: one, two, or three columns wide. Here’s the code for the last row of images above:</p>
<div class="img_row">
<img class="col two left" src="/img/6.jpg" />
<img class="col one left" src="/img/11.jpg" />
</div>
</article>
</div>
</div>
</div>
<footer>
<div class="wrapper">
© Copyright 2021 Sofia Broomé.
Powered by <a href="http://jekyllrb.com/" target="_blank">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank">GitHub Pages</a>. Photos from <a href="https://unsplash.com" target="_blank">Unsplash</a>.
</div>
</footer>
<!-- Load jQuery -->
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<!-- Load Common JS -->
<script src="/assets/js/common.js"></script>
<!-- Load KaTeX -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.js"></script>
<script src="/assets/js/katex.js"></script>
<!-- Include custom icon fonts -->
<link rel="stylesheet" href="/assets/css/fontawesome-all.min.css">
<link rel="stylesheet" href="/assets/css/academicons.min.css">
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXXX', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| high | 0.820323 | 336 |
package tracer
import (
"fmt"
"io"
"strings"
"time"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
jaegercfg "github.com/uber/jaeger-client-go/config"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeJaeger] = TypeSpec{
constructor: NewJaeger,
Summary: `
Send spans to a [Jaeger](https://www.jaegertracing.io/) agent.`,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("agent_address", "The address of a Jaeger agent to send tracing events to.", "jaeger-agent:6831"),
docs.FieldCommon("collector_url", "The URL of a Jaeger collector to send tracing events to. If set, this will override `agent_address`.",
"https://jaeger-collector:14268/api/traces").AtVersion("3.38.0"),
docs.FieldCommon("service_name", "A name to provide for this service."),
docs.FieldCommon("sampler_type", "The sampler type to use.").HasAnnotatedOptions(
"const", "A constant decision for all traces, either 1 or 0.",
"probabilistic", "The sampler makes a random sampling decision with the probability of sampling equal to the value of sampler param.",
"ratelimiting", "The sampler uses a leaky bucket rate limiter to ensure that traces are sampled with a certain constant rate.",
"remote", "The sampler consults Jaeger agent for the appropriate sampling strategy to use in the current service.",
),
docs.FieldAdvanced("sampler_manager_address", "An optional address of a sampler manager."),
docs.FieldFloat("sampler_param", "A parameter to use for sampling. This field is unused for some sampling types.").Advanced(),
docs.FieldString("tags", "A map of tags to add to tracing spans.").Map().Advanced(),
docs.FieldCommon("flush_interval", "The period of time between each flush of tracing spans."),
},
}
}
//------------------------------------------------------------------------------
// JaegerConfig is config for the Jaeger metrics type.
type JaegerConfig struct {
AgentAddress string `json:"agent_address" yaml:"agent_address"`
CollectorURL string `json:"collector_url" yaml:"collector_url"`
ServiceName string `json:"service_name" yaml:"service_name"`
SamplerType string `json:"sampler_type" yaml:"sampler_type"`
SamplerManagerAddress string `json:"sampler_manager_address" yaml:"sampler_manager_address"`
SamplerParam float64 `json:"sampler_param" yaml:"sampler_param"`
Tags map[string]string `json:"tags" yaml:"tags"`
FlushInterval string `json:"flush_interval" yaml:"flush_interval"`
}
// NewJaegerConfig creates an JaegerConfig struct with default values.
func NewJaegerConfig() JaegerConfig {
return JaegerConfig{
AgentAddress: "localhost:6831",
ServiceName: "benthos",
SamplerType: "const",
SamplerManagerAddress: "",
SamplerParam: 1.0,
Tags: map[string]string{},
FlushInterval: "",
}
}
//------------------------------------------------------------------------------
// Jaeger is a tracer with the capability to push spans to a Jaeger instance.
type Jaeger struct {
closer io.Closer
}
// NewJaeger creates and returns a new Jaeger object.
func NewJaeger(config Config, opts ...func(Type)) (Type, error) {
j := &Jaeger{}
for _, opt := range opts {
opt(j)
}
var sampler *jaegercfg.SamplerConfig
if sType := config.Jaeger.SamplerType; len(sType) > 0 {
sampler = &jaegercfg.SamplerConfig{
Param: config.Jaeger.SamplerParam,
SamplingServerURL: config.Jaeger.SamplerManagerAddress,
}
switch strings.ToLower(sType) {
case "const":
sampler.Type = jaeger.SamplerTypeConst
case "probabilistic":
sampler.Type = jaeger.SamplerTypeProbabilistic
case "ratelimiting":
sampler.Type = jaeger.SamplerTypeRateLimiting
case "remote":
sampler.Type = jaeger.SamplerTypeRemote
default:
return nil, fmt.Errorf("unrecognised sampler type: %v", sType)
}
}
cfg := jaegercfg.Configuration{
ServiceName: config.Jaeger.ServiceName,
Sampler: sampler,
}
if tags := config.Jaeger.Tags; len(tags) > 0 {
var jTags []opentracing.Tag
for k, v := range config.Jaeger.Tags {
jTags = append(jTags, opentracing.Tag{
Key: k,
Value: v,
})
}
cfg.Tags = jTags
}
reporterConf := &jaegercfg.ReporterConfig{}
if i := config.Jaeger.FlushInterval; len(i) > 0 {
flushInterval, err := time.ParseDuration(i)
if err != nil {
return nil, fmt.Errorf("failed to parse flush interval '%s': %v", i, err)
}
reporterConf.BufferFlushInterval = flushInterval
cfg.Reporter = reporterConf
}
if i := config.Jaeger.AgentAddress; len(i) > 0 {
reporterConf.LocalAgentHostPort = i
cfg.Reporter = reporterConf
}
if i := config.Jaeger.CollectorURL; len(i) > 0 {
reporterConf.CollectorEndpoint = i
}
tracer, closer, err := cfg.NewTracer()
if err != nil {
return nil, err
}
opentracing.SetGlobalTracer(tracer)
j.closer = closer
return j, nil
}
//------------------------------------------------------------------------------
// Close stops the tracer.
func (j *Jaeger) Close() error {
if j.closer != nil {
j.closer.Close()
j.closer = nil
}
return nil
}
//------------------------------------------------------------------------------
| high | 0.673575 | 337 |
using System;
namespace Nano.Models.Extensions
{
/// <summary>
/// TimeSpan Extensions.
/// </summary>
public static class TimeSpanExtensions
{
/// <summary>
/// Is Within.
/// </summary>
/// <param name="timeSpan">The <see cref="TimeSpan"/>.</param>
/// <param name="timeBegin">The <see cref="TimeSpan"/> begin.</param>
/// <param name="timeEnd">The <see cref="TimeSpan"/> end.</param>
/// <returns>A boolean whether the instance waas within begin and end.</returns>
public static bool IsWithinPeriod(this TimeSpan timeSpan, TimeSpan timeBegin, TimeSpan timeEnd)
{
var isFound = timeSpan >= timeBegin && timeSpan <= timeEnd;
if (timeBegin > timeEnd)
{
if (timeSpan <= timeBegin && timeSpan >= timeEnd)
isFound = false;
else if (timeSpan <= timeBegin || timeSpan >= timeEnd)
isFound = true;
}
return isFound;
}
}
} | high | 0.831691 | 338 |
set Date 1399637825
set Time 6425
set Delay {}
set Problem A
set Team Pied_Piper
set Submission {}
set State delivered
| high | 0.241563 | 339 |
import Js.ASync
p : Int -> JS_IO Int
p x = do
putStrLn' "ola"
pure $ x + 1
call_fn : (Int -> JS_IO Int) -> Int -> JS_IO Int
call_fn f x =
jscall
"%0(%1)"
((JsFn (Int -> JS_IO Int)) -> Int -> JS_IO Int)
(MkJsFn f)
x
main : JS_IO ()
main = do
v <- call_fn p 73
putStrLn' $ show v
| high | 0.324 | 340 |
% \documentclass[leqno]{beamer}
\documentclass[envcountsect, leqno]{beamer}
\setbeamertemplate{theorems}[ams style]
\usetheme{Darmstadt}
\usecolortheme[rgb={1, 0.15, 0}]{structure}
%The following code inserts frame numbers
\newcommand*\oldmacro{}%
\let\oldmacro\insertshorttitle%
\renewcommand*\insertshorttitle{%
\oldmacro\hfill%
\insertframenumber\,/\,\inserttotalframenumber}
\usepackage[english]{babel}
\usepackage{times}
\usepackage[T1]{fontenc}
\usepackage{mathrsfs}
\usepackage{amsmath, amssymb, amsfonts}
\usepackage{calc, ifsym, bbding, dsfont, phaistos, manfnt}
\usepackage{caption, subcaption}
\captionsetup{compatibility=false}
% The following code fixes a compatibility issue
\makeatletter
\let\@@magyar@captionfix\relax
\makeatother
\usepackage[accumulated]{beamerseminar}
\usepackage{beamertexpower}
\usepackage{beamerthemeshadow}
\usepackage{hyperref}
% \usepackage{url}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage{xintfrac}
\usetikzlibrary{decorations.markings}
\usetikzlibrary{arrows, calc, intersections}
\usetikzlibrary{positioning, shadings, shadows, shapes.arrows}
\DeclareMathAlphabet{\mathpzc}{OT1}{pzc}{m}{it}
\input{header.tex}
%%=====================
%% Theorem Environments
%%=====================
\theoremstyle{plain} \newtheorem{thm}{Theorem}%[section]
% \numberwithin{thm}{section}
\theoremstyle{plain} \newtheorem*{thm*}{Theorem}%[section]
\theoremstyle{plain} \newtheorem{lma}[thm]{Lemma}%[section]
\theoremstyle{plain} \newtheorem*{lma*}{Lemma}
\theoremstyle{plain} \newtheorem{cor}[thm]{Corollary}%[section]
\theoremstyle{plain} \newtheorem*{cor*}{Corollary}%[section]
\theoremstyle{plain} \newtheorem{claim}[thm]{Claim}%[section]
\theoremstyle{plain} \newtheorem*{claim*}{Claim}
\theoremstyle{plain} \newtheorem{prop}[thm]{Proposition}%[section]
\theoremstyle{plain} \newtheorem*{prop*}{Proposition}%[section]
\theoremstyle{plain} \newtheorem{observation}{Observation}
\theoremstyle{plain} \newtheorem{property}{Property}
\theoremstyle{remark} \newtheorem*{rmk}{Remark}
\theoremstyle{remark} \newtheorem*{rcl}{Recall}
% \theoremstyle{remark} \newtheorem*{fact}{Fact}
\theoremstyle{definition} \newtheorem{defn}[thm]{Definition}%[section]
\theoremstyle{definition} \newtheorem*{defn*}{Definition}%[section]
\theoremstyle{definition} \newtheorem{ex}{Example}%[section]
\theoremstyle{definition} \newtheorem*{ex*}{Example}%[section]
\renewcommand{\qedsymbol}{\SquareShadowBottomRight}
% \renewenvironment{cases}{
% $
% \left\{
% \begin{aligned}
% &
% }
% {
% \end{aligned}
% \right.
% $
% } | high | 0.757975 | 341 |
ZEPHYRINCLUDE += -I$(srctree)/arch/arm/soc/nordic_nrf5/include
ifdef CONFIG_SOC_SERIES_NRF51X
soc-cflags += -DNRF51
soc-cflags += -DNRF51822
endif
obj-y += soc.o
zephyr: $(KERNEL_HEX_NAME)
all: $(KERNEL_HEX_NAME)
| high | 0.301547 | 342 |
#--------------------------------------------------------------------
# Spacetime Discretization methods in Julia
# Soham 04-2019
# Define operations for 1D spaces
#--------------------------------------------------------------------
using LinearAlgebra
import Base: maximum, minimum, range, size, ndims
export order, identity, incomingboundary, outgoingboundary
ndims(space::S) where {S<:Cardinal{Tag, N, T}} where {Tag, N, T} = 1
minimum(space::S) where {S<:Cardinal{Tag, N, T}} where {Tag, N, T} = space.min
maximum(space::S) where {S<:Cardinal{Tag, N, T}} where {Tag, N, T} = space.max
order(space::S) where {S<:Cardinal{Tag, N, T}} where {Tag, N, T} = N-1
size(space::S) where {S<:Cardinal{Tag, N, T}} where {Tag, N, T} = N
range(space::S) where {S<:Cardinal{Tag, N, T}} where {Tag, N, T} = (minimum(space), maximum(space))
function Base. identity(space::S)::Operator{S} where {S<:Cardinal{Tag, N, T}} where {Tag, N, T}
return Operator(space, Diagonal(ones(T, size(space))))
end
function outgoingboundary(space::S)::Operator{S} where {S<:Cardinal{Tag, N, T}} where {Tag, N, T}
return Operator(space, Diagonal([1, zeros(T, order(space))...]))
end
function incomingboundary(space::S)::Operator{S} where {S<:Cardinal{Tag, N, T}} where {Tag, N, T}
return Operator(space, Diagonal([zeros(T, order(space))..., 1]))
end
function derivative(space::S)::Operator{S} where {S<:Cardinal{Tag, N, T}} where {Tag, N, T}
return Operator(space, [derivative(space, i, j) for i in 1:size(space), j in 1:size(space)])
end
function integral(space::S)::Operator{S} where {S<:Cardinal{Tag, N, T}} where {Tag, N, T}
return Operator(space, Diagonal([integral(space, i) for i in 1:size(space)]))
end
function Field(space::S, umap::Function)::Field{S} where {S<:Cardinal{Tag, N, T}} where {Tag, N, T}
value = zeros(T, size(space))
for index in CartesianIndices(value)
value[index] = umap(collocation(space, index.I[1]))
end
return Field(space, value)
end
| high | 0.421841 | 343 |
---
title: Tables in R (And How to Export Them to Word)
author: <a href="http://stanford.edu/~ejdemyr/"> Simon Ejdemyr </a>
date: October, 2015
summary: This tutorial explains how to create and export different
types of tables in R. It was originally designed for undergraduate
students at Stanford who tend to use Word rather than LaTeX.
output:
html_document:
template: ../template/r-tutorial-template-v2.html
mathjax: null
---
Overview
==========================
How to export tables from R depends on what word processor you
use. This tutorial focuses on Word. If you use LaTeX, there are many
existing R packages and tutorials that will get you started, including
[xtable](https://cran.r-project.org/web/packages/xtable/xtable.pdf)
and
[stargazer](https://cran.r-project.org/web/packages/stargazer/stargazer.pdf).
To export tables to Word, follow these general steps:
<div style="margin-left: 20px">
1. Create a table or data.frame in R.
2. Write this table to a comma-separated .txt file using `write.table()`.
3. Copy and paste the content of the .txt file into Word.
4. In Word,
a. select the text you just pasted from the .txt file
b. go to Table $\rightarrow$ Convert $\rightarrow$ Convert Text to Table...
c. make sure "Commas" is selected under "Separate text at", click OK
</div>
You'll now have a basic table that you can format in Word. Below are
three examples of how to use this process to create crosstabs, tables
for summary statistics, and regression tables.
Data and Packages
--------------------
Before we get started, read in a
[dataset on U.S. states](../data/states.csv) (codebook
[here](../data/states_codebook.csv)) into R:
```{r, echo=FALSE}
states <- read.csv("../data/states.csv")
```
```{r, eval=FALSE}
states <- read.csv("states.csv")
```
Also install and load packages `dplyr`, `tidyr`, and `broom`:
```{r, eval=FALSE}
pkgs <- c("dplyr", "tidyr", "broom")
install.packages(pkgs) #install
sapply(pkgs, require, character.only = T) #load
```
```{r, echo=FALSE}
pkgs <- c("dplyr", "tidyr", "broom")
sapply(pkgs, require, character.only = T) #load
```
Crosstabs
====================
Create a table showing the proportion of states that supported Bush in
2000, by region (South versus Non-South):
```{r}
# Create table
t <- with(states, table(south, gb_win00))
t <- prop.table(t, margin = 1)
t #large majority of southern states supported Bush in 2000:
# Write this table to a comma separated .txt file:
write.table(t, file = "bush_south.txt", sep = ",", quote = FALSE, row.names = F)
```
The .txt file will end up in your working directory. Now follow steps 3 and 4
in the Overview section above to create the crosstab in Word.
Summary statistics
=======================
Here's another example that again uses the [states.csv](states.csv) dataset. Say we
wanted to create a table with summary statistics for five of the variables
in this dataset:
```{r}
sumstat <- states %>%
# Select and rename five variables
select(
`Black (%)` = blkpct,
`Attend church (%)` = attend_pct,
`Supported Bush in 2000 (%)` = bush00,
`Supported Obama in 2008 (%)` = obama08,
`Women in State Legislature (%)` = womleg
) %>%
# Find the mean, st. dev., min, and max for each variable
summarise_each(funs(mean, sd, min, max)) %>%
# Move summary stats to columns
gather(key, value, everything()) %>%
separate(key, into = c("variable", "stat"), sep = "_") %>%
spread(stat, value) %>%
# Set order of summary statistics
select(variable, mean, sd, min, max) %>%
# Round all numeric variables to one decimal point
mutate_each(funs(round(., 1)), -variable)
sumstat
# Write to .txt
write.table(sumstat, file = "sumstats.txt", sep = ",", quote = FALSE, row.names = F)
```
Again, the `sumstats.txt` file will end up in your working directory,
and you can use steps 3 and 4 from the Overview section above to
import this file into Word.
Exercise
-------------
Create a table of summary statistics in Word for `vep04_turnout`,
`vep08_turnout`, `unemploy`, `urban`, and `hispanic`. The table should
include the number of observations (*n*), mean, median, 10th
percentile, and 90th percentile of each of the variables. Put the
variables in the rows of the table and the summary statistics in the
columns, like we did in the example above. Format your table in Word
to make it look similar to [this table](summary_stats_example.tif).
Regression tables
=======================
Say we wanted to run three OLS models to predict state-level support
for Bush in 2000, where each model adds a predictor to the preceding
model. We can create a regression table with all three models like so:
```{r}
m1 <- tidy(lm(bush00 ~ blkpct, states))
m2 <- tidy(lm(bush00 ~ blkpct + south, data = states))
m3 <- tidy(lm(bush00 ~ blkpct + south + womleg, data = states))
# Note that tidy() from the broom package is used to convert each model to a data frame
all_models <- rbind_list(
m1 %>% mutate(model = 1),
m2 %>% mutate(model = 2),
m3 %>% mutate(model = 3))
all_models
# Now make this data frame look more like a regression table
ols_table <- all_models %>%
select(-statistic, -p.value) %>%
mutate_each(funs(round(., 2)), -term) %>%
gather(key, value, estimate:std.error) %>%
spread(model, value)
ols_table
# Export
write.table(ols_table, file = "olstab.txt", sep = ",", quote = FALSE, row.names = F)
```
Again, follow steps 3 and 4 from the Overview section above to import
the content of the .txt file into Word.
| high | 0.130837 | 344 |
class PlantsController < ApplicationController
before_action :redirect_if_not_logged_in
before_action :set_plant, only: [:show, :edit, :update, :destroy]
def new
@plant = Plant.new
end
def create
@plant = current_user.plants.build(plant_params)
if @plant.save
redirect_to plant_path(@plant)
else
render :new
end
end
def show
# @plant = Plant.find_by_id(params[:id])
# redirect_to plants_path if !@plant
end
def index
# binding.pry
@plants = Plant.all
end
def edit
end
def update
if @plant.update(plant_params)
redirect_to plants_path(@plant)
else
render :edit
end
end
def destroy
@plant.destroy
redirect_to plants_path
end
private
def set_plant
@plant = Plant.find_by_id(params[:id])
end
def plant_params
params.require(:plant).permit(:name, :description, :location, :light_requirement, :watering, )
end
end
| medium | 0.424695 | 345 |
defmodule RaemWeb.IgcControllerTest do
use RaemWeb.ConnCase
alias Raem.Igcs
@create_attrs %{alfa_proporcao_graduandos: 120.5, ano: "some ano", beta_proporcao_mestrandos: 120.5, cod_ies: 42, conceito_doutorado: 120.5, conceito_graduacao: 120.5, conceito_mestrado: 120.5, gama_proporcao_doutorando: 120.5, igc_continuo: 120.5, igc_faixa: 42, num_cursos_avaliados: 42, num_cursos_cpc: 42, observacao: "some observacao"}
@update_attrs %{alfa_proporcao_graduandos: 456.7, ano: "some updated ano", beta_proporcao_mestrandos: 456.7, cod_ies: 43, conceito_doutorado: 456.7, conceito_graduacao: 456.7, conceito_mestrado: 456.7, gama_proporcao_doutorando: 456.7, igc_continuo: 456.7, igc_faixa: 43, num_cursos_avaliados: 43, num_cursos_cpc: 43, observacao: "some updated observacao"}
@invalid_attrs %{alfa_proporcao_graduandos: nil, ano: nil, beta_proporcao_mestrandos: nil, cod_ies: nil, conceito_doutorado: nil, conceito_graduacao: nil, conceito_mestrado: nil, gama_proporcao_doutorando: nil, igc_continuo: nil, igc_faixa: nil, num_cursos_avaliados: nil, num_cursos_cpc: nil, observacao: nil}
def fixture(:igc) do
{:ok, igc} = Igcs.create_igc(@create_attrs)
igc
end
describe "index" do
test "lists all igcs", %{conn: conn} do
conn = get conn, igc_path(conn, :index)
assert html_response(conn, 200) =~ "Listing Igcs"
end
end
describe "new igc" do
test "renders form", %{conn: conn} do
conn = get conn, igc_path(conn, :new)
assert html_response(conn, 200) =~ "New Igc"
end
end
describe "create igc" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post conn, igc_path(conn, :create), igc: @create_attrs
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == igc_path(conn, :show, id)
conn = get conn, igc_path(conn, :show, id)
assert html_response(conn, 200) =~ "Show Igc"
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post conn, igc_path(conn, :create), igc: @invalid_attrs
assert html_response(conn, 200) =~ "New Igc"
end
end
describe "edit igc" do
setup [:create_igc]
test "renders form for editing chosen igc", %{conn: conn, igc: igc} do
conn = get conn, igc_path(conn, :edit, igc)
assert html_response(conn, 200) =~ "Edit Igc"
end
end
describe "update igc" do
setup [:create_igc]
test "redirects when data is valid", %{conn: conn, igc: igc} do
conn = put conn, igc_path(conn, :update, igc), igc: @update_attrs
assert redirected_to(conn) == igc_path(conn, :show, igc)
conn = get conn, igc_path(conn, :show, igc)
assert html_response(conn, 200) =~ "some updated ano"
end
test "renders errors when data is invalid", %{conn: conn, igc: igc} do
conn = put conn, igc_path(conn, :update, igc), igc: @invalid_attrs
assert html_response(conn, 200) =~ "Edit Igc"
end
end
describe "delete igc" do
setup [:create_igc]
test "deletes chosen igc", %{conn: conn, igc: igc} do
conn = delete conn, igc_path(conn, :delete, igc)
assert redirected_to(conn) == igc_path(conn, :index)
assert_error_sent 404, fn ->
get conn, igc_path(conn, :show, igc)
end
end
end
defp create_igc(_) do
igc = fixture(:igc)
{:ok, igc: igc}
end
end
| high | 0.399466 | 346 |
// ***************************************************************************
//
// Delphi MVC Framework
//
// Copyright (c) 2010-2022 Daniele Teti and the DMVCFramework Team
//
// https://github.com/danieleteti/delphimvcframework
//
// ***************************************************************************
//
// 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.
//
// *************************************************************************** }
unit WebModuleUnit;
interface
uses
System.SysUtils,
System.Classes,
Web.HTTPApp,
MVCFramework,
FireDAC.Stan.StorageJSON
{$IFDEF MSWINDOWS}
,MVCFramework.Serializer.JsonDataObjects.OptionalCustomTypes
{$ENDIF}
;
type
TMainWebModule = class(TWebModule)
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
procedure WebModuleCreate(Sender: TObject);
private
MVCEngine: TMVCEngine;
end;
var
WebModuleClass: TComponentClass = TMainWebModule;
implementation
{$R *.dfm}
uses
TestServerControllerU,
TestServerControllerExceptionU,
SpeedMiddlewareU,
MVCFramework.Middleware.Authentication,
System.Generics.Collections,
MVCFramework.Commons,
TestServerControllerPrivateU,
AuthHandlersU,
TestServerControllerJSONRPCU,
{$IFNDEF LINUX}
MVCFramework.View.Renderers.Mustache,
{$ENDIF}
MVCFramework.Middleware.Compression,
MVCFramework.Middleware.StaticFiles;
procedure TMainWebModule.WebModuleCreate(Sender: TObject);
begin
MVCEngine := TMVCEngine.Create(self,
procedure(Config: TMVCConfig)
begin
// no config here
Config[TMVCConfigKey.SessionTimeout] := '0'; // setting cookie
Config[TMVCConfigKey.PathPrefix] := '';
Config[TMVCConfigKey.ViewPath] := '..\templates';
Config[TMVCConfigKey.DefaultViewFileExtension] := 'html';
end, nil);
MVCEngine
.AddController(TTestServerController)
.AddController(TTestPrivateServerController)
.AddController(TTestServerControllerExceptionAfterCreate)
.AddController(TTestServerControllerExceptionBeforeDestroy)
.AddController(TTestServerControllerActionFilters)
.AddController(TTestPrivateServerControllerCustomAuth)
.AddController(TTestMultiPathController)
.AddController(TTestJSONRPCController, '/jsonrpc')
.AddController(TTestJSONRPCControllerWithGet, '/jsonrpcwithget')
.PublishObject(
function: TObject
begin
Result := TTestJSONRPCClass.Create
end, '/jsonrpcclass')
.PublishObject(
function: TObject
begin
Result := TTestJSONRPCClassWithGET.Create
end, '/jsonrpcclasswithget')
.PublishObject(
function: TObject
begin
Result := TTestJSONRPCHookClass.Create
end, '/jsonrpcclass1')
.PublishObject(
function: TObject
begin
Result := TTestJSONRPCHookClassWithGet.Create
end, '/jsonrpcclass1withget')
.AddController(TTestFaultController) // this will raise an exception
.AddController(TTestFault2Controller,
function: TMVCController
begin
Result := TTestFault2Controller.Create; // this will raise an exception
end)
.AddMiddleware(TMVCSpeedMiddleware.Create)
.AddMiddleware(TMVCCustomAuthenticationMiddleware.Create(TCustomAuthHandler.Create, '/system/users/logged'))
.AddMiddleware(TMVCStaticFilesMiddleware.Create('/static', 'www', 'index.html', False))
.AddMiddleware(TMVCStaticFilesMiddleware.Create('/spa', 'www', 'index.html', True))
// .AddMiddleware(TMVCStaticFilesMiddleware.Create('/', 'www', 'index.html', False))
.AddMiddleware(TMVCBasicAuthenticationMiddleware.Create(TBasicAuthHandler.Create))
.AddMiddleware(TMVCCompressionMiddleware.Create);
{$IFDEF MSWINDOWS}
MVCEngine.SetViewEngine(TMVCMustacheViewEngine);
RegisterOptionalCustomTypesSerializers(MVCEngine.Serializers[TMVCMediaType.APPLICATION_JSON]);
{$ENDIF}
end;
end.
| high | 0.777596 | 347 |
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import representation_theory.Action
import algebra.category.Module.abelian
import algebra.category.Module.colimits
import algebra.category.Module.monoidal
/-!
# `Rep k G` is the category of `k`-linear representations of `G`.
If `V : Rep k G`, there is a coercion that allows you to treat `V` as a type,
and this type comes equipped with a `module k V` instance.
Also `V.ρ` gives the homomorphism `G →* (V →ₗ[k] V)`.
Conversely, given a homomorphism `ρ : G →* (V →ₗ[k] V)`,
you can construct the bundled representation as `Rep.of ρ`.
We verify that `Rep k G` is a `k`-linear abelian symmetric monoidal category with all (co)limits.
-/
universes u
open category_theory
open category_theory.limits
/-- The category of `k`-linear representations of a monoid `G`. -/
@[derive [large_category, concrete_category, has_limits, has_colimits,
preadditive, abelian]]
abbreviation Rep (k G : Type u) [ring k] [monoid G] :=
Action (Module.{u} k) (Mon.of G)
instance (k G : Type u) [comm_ring k] [monoid G] : linear k (Rep k G) :=
by apply_instance
namespace Rep
variables {k G : Type u} [ring k] [monoid G]
instance : has_coe_to_sort (Rep k G) (Type u) := concrete_category.has_coe_to_sort _
instance (V : Rep k G) : add_comm_monoid V :=
by { change add_comm_monoid ((forget₂ (Rep k G) (Module k)).obj V), apply_instance, }
instance (V : Rep k G) : module k V :=
by { change module k ((forget₂ (Rep k G) (Module k)).obj V), apply_instance, }
-- This works well with the new design for representations:
example (V : Rep k G) : G →* (V →ₗ[k] V) := V.ρ
/-- Lift an unbundled representation to `Rep`. -/
@[simps ρ]
def of {V : Type u} [add_comm_group V] [module k V] (ρ : G →* (V →ₗ[k] V)) : Rep k G :=
⟨Module.of k V, ρ⟩
-- Verify that limits are calculated correctly.
noncomputable example : preserves_limits (forget₂ (Rep k G) (Module.{u} k)) :=
by apply_instance
noncomputable example : preserves_colimits (forget₂ (Rep k G) (Module.{u} k)) :=
by apply_instance
end Rep
namespace Rep
variables {k G : Type u} [comm_ring k] [monoid G]
-- Verify that the symmetric monoidal structure is available.
example : symmetric_category (Rep k G) := by apply_instance
example : monoidal_preadditive (Rep k G) := by apply_instance
example : monoidal_linear k (Rep k G) := by apply_instance
end Rep
| high | 0.422131 | 348 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Noise++: noisepp/utils/NoiseEndianUtils.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<h1>noisepp/utils/NoiseEndianUtils.h</h1><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">// Noise++ Library</span>
<a name="l00002"></a>00002 <span class="comment">// Copyright (c) 2008, Urs C. Hanselmann</span>
<a name="l00003"></a>00003 <span class="comment">// All rights reserved.</span>
<a name="l00004"></a>00004 <span class="comment">//</span>
<a name="l00005"></a>00005 <span class="comment">// Redistribution and use in source and binary forms, with or without modification,</span>
<a name="l00006"></a>00006 <span class="comment">// are permitted provided that the following conditions are met:</span>
<a name="l00007"></a>00007 <span class="comment">//</span>
<a name="l00008"></a>00008 <span class="comment">// * Redistributions of source code must retain the above copyright notice,</span>
<a name="l00009"></a>00009 <span class="comment">// this list of conditions and the following disclaimer.</span>
<a name="l00010"></a>00010 <span class="comment">// * Redistributions in binary form must reproduce the above copyright notice,</span>
<a name="l00011"></a>00011 <span class="comment">// this list of conditions and the following disclaimer in the documentation</span>
<a name="l00012"></a>00012 <span class="comment">// and/or other materials provided with the distribution.</span>
<a name="l00013"></a>00013 <span class="comment">//</span>
<a name="l00014"></a>00014 <span class="comment">// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"</span>
<a name="l00015"></a>00015 <span class="comment">// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,</span>
<a name="l00016"></a>00016 <span class="comment">// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE</span>
<a name="l00017"></a>00017 <span class="comment">// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE</span>
<a name="l00018"></a>00018 <span class="comment">// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES</span>
<a name="l00019"></a>00019 <span class="comment">// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;</span>
<a name="l00020"></a>00020 <span class="comment">// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND</span>
<a name="l00021"></a>00021 <span class="comment">// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT</span>
<a name="l00022"></a>00022 <span class="comment">// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS</span>
<a name="l00023"></a>00023 <span class="comment">// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span>
<a name="l00024"></a>00024 <span class="comment">//</span>
<a name="l00025"></a>00025
<a name="l00026"></a>00026 <span class="preprocessor">#ifndef NOISEENDIANUTILS_H</span>
<a name="l00027"></a>00027 <span class="preprocessor"></span><span class="preprocessor">#define NOISEENDIANUTILS_H</span>
<a name="l00028"></a>00028 <span class="preprocessor"></span>
<a name="l00029"></a>00029 <span class="preprocessor">#include "NoisePrerequisites.h"</span>
<a name="l00030"></a>00030
<a name="l00031"></a>00031 <span class="keyword">namespace </span>noisepp
<a name="l00032"></a>00032 {
<a name="l00033"></a>00033 <span class="keyword">namespace </span>utils
<a name="l00034"></a>00034 {
<a name="l00035"></a>00035
<a name="l00037"></a><a class="code" href="classnoisepp_1_1utils_1_1EndianUtils.html">00037</a> <span class="keyword">class </span><a class="code" href="classnoisepp_1_1utils_1_1EndianUtils.html" title="Endian utility class.">EndianUtils</a>
<a name="l00038"></a>00038 {
<a name="l00039"></a>00039 <span class="keyword">public</span>:
<a name="l00041"></a>00041 <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="classnoisepp_1_1utils_1_1EndianUtils.html#7b65dcf8da7326b0ab6af0fbc9c53c8a" title="Flips the endian mode if required.">flipEndian</a> (<span class="keywordtype">void</span> *data, <span class="keywordtype">size_t</span> size);
<a name="l00042"></a>00042 };
<a name="l00043"></a>00043
<a name="l00044"></a>00044 };
<a name="l00045"></a>00045 };
<a name="l00046"></a>00046
<a name="l00047"></a>00047 <span class="preprocessor">#endif // NOISEENDIANUTILS_H</span>
</pre></div></div>
<br>
<div style="text-align:center;"><a href="http://sourceforge.net"><img src="http://sflogo.sourceforge.net/sflogo.php?group_id=226538&type=5" width="210" height="62" border="0" alt="SourceForge.net Logo" /></a></div>
</BODY>
</HTML>
| high | 0.461081 | 349 |
/*
* Copyright (c) 2019-2020, NVIDIA CORPORATION.
*
* 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.
*/
#include <gtest/gtest.h>
#include <raft/cudart_utils.h>
#include <algorithm>
#include <iostream>
#include <metrics/contingencyMatrix.cuh>
#include <random>
#include "test_utils.h"
namespace MLCommon {
namespace Metrics {
struct ContingencyMatrixParam {
int nElements;
int minClass;
int maxClass;
bool calcCardinality;
bool skipLabels;
float tolerance;
};
template <typename T>
class ContingencyMatrixTest
: public ::testing::TestWithParam<ContingencyMatrixParam> {
protected:
void SetUp() override {
params = ::testing::TestWithParam<ContingencyMatrixParam>::GetParam();
int numElements = params.nElements;
int lowerLabelRange = params.minClass;
int upperLabelRange = params.maxClass;
std::vector<int> y(numElements, 0);
std::vector<int> y_hat(numElements, 0);
std::random_device rd;
std::default_random_engine dre(rd());
std::uniform_int_distribution<int> intGenerator(lowerLabelRange,
upperLabelRange);
std::generate(y.begin(), y.end(), [&]() { return intGenerator(dre); });
std::generate(y_hat.begin(), y_hat.end(),
[&]() { return intGenerator(dre); });
if (params.skipLabels) {
// remove two label value from input arrays
int y1 = (upperLabelRange - lowerLabelRange) / 2;
int y2 = y1 + (upperLabelRange - lowerLabelRange) / 4;
// replacement values
int y1_R = y1 + 1;
int y2_R = y2 + 1;
std::replace(y.begin(), y.end(), y1, y1_R);
std::replace(y.begin(), y.end(), y2, y2_R);
std::replace(y_hat.begin(), y_hat.end(), y1, y1_R);
std::replace(y_hat.begin(), y_hat.end(), y2, y2_R);
}
CUDA_CHECK(cudaStreamCreate(&stream));
raft::allocate(dY, numElements);
raft::allocate(dYHat, numElements);
raft::update_device(dYHat, &y_hat[0], numElements, stream);
raft::update_device(dY, &y[0], numElements, stream);
if (params.calcCardinality) {
MLCommon::Metrics::getInputClassCardinality(dY, numElements, stream,
minLabel, maxLabel);
} else {
minLabel = lowerLabelRange;
maxLabel = upperLabelRange;
}
numUniqueClasses = maxLabel - minLabel + 1;
raft::allocate(dComputedOutput, numUniqueClasses * numUniqueClasses);
raft::allocate(dGoldenOutput, numUniqueClasses * numUniqueClasses);
// generate golden output on CPU
size_t sizeOfMat = numUniqueClasses * numUniqueClasses * sizeof(int);
hGoldenOutput = (int *)malloc(sizeOfMat);
memset(hGoldenOutput, 0, sizeOfMat);
for (int i = 0; i < numElements; i++) {
auto row = y[i] - minLabel;
auto column = y_hat[i] - minLabel;
hGoldenOutput[row * numUniqueClasses + column] += 1;
}
raft::update_device(dGoldenOutput, hGoldenOutput,
numUniqueClasses * numUniqueClasses, stream);
workspaceSz = MLCommon::Metrics::getContingencyMatrixWorkspaceSize(
numElements, dY, stream, minLabel, maxLabel);
if (workspaceSz != 0) raft::allocate(pWorkspace, workspaceSz);
}
void TearDown() override {
CUDA_CHECK(cudaStreamSynchronize(stream));
free(hGoldenOutput);
CUDA_CHECK(cudaStreamDestroy(stream));
CUDA_CHECK(cudaFree(dY));
CUDA_CHECK(cudaFree(dYHat));
CUDA_CHECK(cudaFree(dComputedOutput));
CUDA_CHECK(cudaFree(dGoldenOutput));
if (pWorkspace) CUDA_CHECK(cudaFree(pWorkspace));
}
void RunTest() {
int numElements = params.nElements;
MLCommon::Metrics::contingencyMatrix(
dY, dYHat, numElements, dComputedOutput, stream, (void *)pWorkspace,
workspaceSz, minLabel, maxLabel);
ASSERT_TRUE(raft::devArrMatch(dComputedOutput, dGoldenOutput,
numUniqueClasses * numUniqueClasses,
raft::Compare<T>()));
}
ContingencyMatrixParam params;
int numUniqueClasses = -1;
T *dY = nullptr;
T *dYHat = nullptr;
T minLabel, maxLabel;
int *dComputedOutput = nullptr;
int *dGoldenOutput = nullptr;
int *hGoldenOutput = nullptr;
char *pWorkspace = nullptr;
cudaStream_t stream;
size_t workspaceSz;
};
const std::vector<ContingencyMatrixParam> inputs = {
{10000, 1, 10, true, false, 0.000001},
{10000, 1, 5000, true, false, 0.000001},
{10000, 1, 10000, true, false, 0.000001},
{10000, 1, 20000, true, false, 0.000001},
{10000, 1, 10, false, false, 0.000001},
{10000, 1, 5000, false, false, 0.000001},
{10000, 1, 10000, false, false, 0.000001},
{10000, 1, 20000, false, false, 0.000001},
{100000, 1, 100, false, false, 0.000001},
{1000000, 1, 1200, true, false, 0.000001},
{1000000, 1, 10000, false, false, 0.000001},
{100000, 1, 100, false, true, 0.000001},
};
typedef ContingencyMatrixTest<int> ContingencyMatrixTestS;
TEST_P(ContingencyMatrixTestS, Result) { RunTest(); }
INSTANTIATE_TEST_CASE_P(ContingencyMatrix, ContingencyMatrixTestS,
::testing::ValuesIn(inputs));
} // namespace Metrics
} // namespace MLCommon
| high | 0.531304 | 350 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
namespace cpp openr.thrift
namespace cpp2 openr.thrift
namespace go openr.OpenrCtrl
namespace py openr.OpenrCtrl
namespace py3 openr.thrift
namespace php Openr
namespace lua openr.OpenrCtrl
namespace wiki Open_Routing.Thrift_APIs.OpenrCtrl
include "fb303/thrift/fb303_core.thrift"
include "Network.thrift"
include "OpenrConfig.thrift"
include "Types.thrift"
exception OpenrError {
1: string message;
} (message = "message")
struct NodeAndArea {
1: string node;
2: string area;
}
struct AdvertisedRoute {
1: Network.PrefixType key;
2: Types.PrefixEntry route;
}
struct AdvertisedRouteDetail {
1: Network.IpPrefix prefix;
2: Network.PrefixType bestKey;
3: list<Network.PrefixType> bestKeys;
4: list<AdvertisedRoute> routes;
}
struct AdvertisedRouteFilter {
1: optional list<Network.IpPrefix> prefixes;
2: optional Network.PrefixType prefixType;
}
struct ReceivedRoute {
1: NodeAndArea key;
2: Types.PrefixEntry route;
}
struct ReceivedRouteDetail {
1: Network.IpPrefix prefix;
2: NodeAndArea bestKey;
3: list<NodeAndArea> bestKeys;
4: list<ReceivedRoute> routes;
}
struct ReceivedRouteFilter {
1: optional list<Network.IpPrefix> prefixes;
2: optional string nodeName;
3: optional string areaName;
}
struct AdjacenciesFilter {
1: set<string> selectAreas;
}
//
// RIB Policy related data structures
//
/**
* Matcher selects the routes. As of now supports selecting specified routes,
* but can be expanded to select route by tags as well.
*
* - Atleast one criteria must be specified for selection
* - `AND` operator is assumed for selecting on multiple attributes.
* - setting criteria to none will skip the matching
*/
struct RibRouteMatcher {
1: optional list<Network.IpPrefix> prefixes;
// Select route based on the tag. Specifying multiple tag match on any
2: optional list<string> tags;
}
/**
* `set weight <>` action for RibRoute
*/
struct RibRouteActionWeight {
// Default weight for the next-hops with no a neighbor not in the map.
// Usually next-hops from static routes (external next-hops)
2: i32 default_weight;
// Area name to weight mapping (internal next-hops)
3: map<string, i32> area_to_weight;
// Neighbor device name to weight mapping (internal next-hops)
4: map<string, i32> neighbor_to_weight;
}
/**
* Captures information for route transform. So far supports only weight
* manipulation, but in future we can add more `set_<>` action
* e.g. `set_admin_distance`
*
* - Atleast one `set_` statement must be specified
* - All provided `set_` statements are applied at once
*/
struct RibRouteAction {
1: optional RibRouteActionWeight set_weight;
}
/**
* RibPolicyStatement express a single `match` and `action`
* based on forseable need for route manipulation. However more sophisticated
* matching and transformation can be specified to modify multiple route
* attributes in granular way.
*/
struct RibPolicyStatement {
// Just for reference and understanding. Code doesn't use it in any way.
1: string name;
// Select routes to be transformed
2: RibRouteMatcher matcher;
// Transform operation for a single route object
3: RibRouteAction action;
}
/**
* Represents a RibPolicy. The intent of RibPolicy is to perform the route
* modifications on computed routes before programming. The technique provides
* ability to influence the forwarding decision of distributed computation with
* central knowledge (e.g. load-aware weight balancing among the areas) for
* non-oblivious routing scheme.
*
* `RibPolicy` is intends to be set via RPC API and is not supported via Config
* primarily because of its dynamic nature (ttl_secs). Read more about it below.
*/
struct RibPolicy {
// List of policy statements. Each statement can select routes and can
// transform it. The statements are applied in order they're specified. The
// first successful match/action will terminate the further policy processing.
// Different `action` can be specified for different set of routes (matchers).
1: list<RibPolicyStatement> statements;
// Number of seconds this policy is valid for. The policy must be refreshed or
// updated within `ttl_secs`. If not then policy will become in-effective.
// Policy is not preserved across restarts. Hence then external agent setting
// this policy should detect Open/R restart within `Initial Hold Time` (30s)
// and update the policy within the same window. No routes will be updated in
// HW within initial hold time window, which ensures the route programmed
// according to old policy will remain in effect until initial hold time
// expires.
// It is recommended to refresh policy every 20 seconds (< hold time).
2: i32 ttl_secs;
}
/*
* UnicastRouteDetail includes additional information from UnicastRoute which
* is not downloaded to FibService
*/
struct UnicastRouteDetail {
1: Network.UnicastRoute unicastRoute (cpp.mixin);
2: optional Types.PrefixEntry bestRoute;
}
/*
* MplsRouteDetail includes additional information from MplsRoute which
* is not downloaded to FibService
*/
struct MplsRouteDetail {
1: Network.MplsRoute mplsRoute (cpp.mixin);
}
/*
* RouteDatabaseDetail includes additional information from RouteDatabase which
* is not downloaded to FibService
*/
struct RouteDatabaseDetail {
1: string thisNodeName;
2: list<UnicastRouteDetail> unicastRoutes;
3: list<MplsRouteDetail> mplsRoutes;
}
/*
* RouteDatabaseDeltaDetail includes additional information from
* RouteDatabaseDelta which is not downloaded to FibService
*/
struct RouteDatabaseDeltaDetail {
1: list<UnicastRouteDetail> unicastRoutesToUpdate;
2: list<Network.IpPrefix> unicastRoutesToDelete;
3: list<MplsRouteDetail> mplsRoutesToUpdate;
4: list<i32> mplsRoutesToDelete;
}
/**
* Thrift service - exposes RPC APIs for interaction with all of Open/R's
* modules.
*/
service OpenrCtrl extends fb303_core.BaseService {
//
// Config APIs
//
/**
* get string config
*/
string getRunningConfig();
/**
* get config in thrift
*/
OpenrConfig.OpenrConfig getRunningConfigThrift();
/**
* Load file config and do validation. Throws exception upon error.
* Return - loaded config content.
*
* NOTE: json seriliazer ommit extra fields.
* loaded content is returned so user could verify the difference between
* file content and loaded content
*/
string dryrunConfig(1: string file) throws (1: OpenrError error);
//
// PrefixManager APIs
//
/**
* Advertise or Update prefixes
*/
void advertisePrefixes(1: list<Types.PrefixEntry> prefixes) throws (
1: OpenrError error,
);
/**
* Withdraw previously advertised prefixes. Only relevant attributes for this
* operation are `prefix` and `type`
*/
void withdrawPrefixes(1: list<Types.PrefixEntry> prefixes) throws (
1: OpenrError error,
);
/**
* Withdraw prefixes in bulk by type (aka client-id)
*/
void withdrawPrefixesByType(1: Network.PrefixType prefixType) throws (
1: OpenrError error,
);
/**
* Sync prefixes by type. This operation set the new state for given type.
* PrefixType specified in API parameter must match with individual
* PrefixEntry object
*/
void syncPrefixesByType(
1: Network.PrefixType prefixType,
2: list<Types.PrefixEntry> prefixes,
) throws (1: OpenrError error);
/**
* Get all prefixes being advertised
* @deprecated - use getAdvertisedRoutes() instead
*/
list<Types.PrefixEntry> getPrefixes() throws (1: OpenrError error);
/**
* Get prefixes of specific types
*/
list<Types.PrefixEntry> getPrefixesByType(
1: Network.PrefixType prefixType,
) throws (1: OpenrError error);
//
// Route APIs
//
/**
* Get routes that current node is advertising. Filter parameters if specified
* will follow `AND` operator
*/
list<AdvertisedRouteDetail> getAdvertisedRoutes();
list<AdvertisedRouteDetail> getAdvertisedRoutesFiltered(
1: AdvertisedRouteFilter filter,
) throws (1: OpenrError error);
/**
* Get received routes, aka Adjacency RIB. Filter parameters if specified will
* follow `AND` operator
*/
list<ReceivedRouteDetail> getReceivedRoutes();
list<ReceivedRouteDetail> getReceivedRoutesFiltered(
1: ReceivedRouteFilter filter,
) throws (1: OpenrError error);
/**
* Get route database of the current node. It is retrieved from FIB module.
*/
Types.RouteDatabase getRouteDb() throws (1: OpenrError error);
/**
* Get route detailed database of the current node. It is retrieved from FIB module.
*/
RouteDatabaseDetail getRouteDetailDb() throws (1: OpenrError error);
/**
* Get route database from decision module. Since Decision has global
* topology information, any node can be retrieved.
*
* NOTE: Current node's routes are returned if `nodeName` is empty.
*/
Types.RouteDatabase getRouteDbComputed(1: string nodeName) throws (
1: OpenrError error,
);
/**
* Get unicast routes after applying a list of prefix filter.
* Perform longest prefix match for each input filter among the prefixes
* in from FIB module.
* Return all unicast routes if the input list is empty.
*/
list<Network.UnicastRoute> getUnicastRoutesFiltered(
1: list<string> prefixes,
) throws (1: OpenrError error);
/**
* Get all unicast routes of the current node, retrieved from FIB module.
*/
list<Network.UnicastRoute> getUnicastRoutes() throws (1: OpenrError error);
/**
* Get Mpls routes after applying a list of prefix filter.
* Return all Mpls routes if the input list is empty.
*/
list<Network.MplsRoute> getMplsRoutesFiltered(1: list<i32> labels) throws (
1: OpenrError error,
);
/**
* Get all Mpls routes of the current node, retrieved from FIB module.
*/
list<Network.MplsRoute> getMplsRoutes() throws (1: OpenrError error);
/**
* Get all originated prefixes of the current node, retrieved from PrefixManager.
*/
list<Types.OriginatedPrefixEntry> getOriginatedPrefixes() throws (
1: OpenrError error,
);
//
// Performance stats APIs
//
/**
* Get latest performance events. Useful for debugging delays and performance
* of Open/R.
*/
Types.PerfDatabase getPerfDb() throws (1: OpenrError error);
//
// Decision APIs
//
/**
* Get default area adjacency databases of all nodes, representing default
* area topology from Decision module. This represents currently active nodes
* (includes bi-directional check)
* only selects default area adj DBs. Deprecated, perfer
* getDecisionAdjacenciesFiltered()
*/
Types.AdjDbs getDecisionAdjacencyDbs() throws (1: OpenrError error);
/**
* Get adjacency databases of all nodes. NOTE: for ABRs, there can be more
* than one AdjDb for a node (one per area)
* (includes bi-directional check)
*/
list<Types.AdjacencyDatabase> getDecisionAdjacenciesFiltered(
1: AdjacenciesFilter filter,
) throws (1: OpenrError error);
/**
* Get global prefix databases. This represents prefixes of actives nodes
* only. While KvStore can represent dead node's information until their keys
* expires
*
* DEPRECATED. Prefer getReceivedRoutes APIs
*/
Types.PrefixDbs getDecisionPrefixDbs() throws (1: OpenrError error);
//
// KvStore APIs
//
/**
* Get specific key-values from KvStore. If `filterKeys` is empty then no
* keys will be returned
*/
Types.Publication getKvStoreKeyVals(1: list<string> filterKeys) throws (
1: OpenrError error,
);
/**
* with area option
*/
Types.Publication getKvStoreKeyValsArea(
1: list<string> filterKeys,
2: string area,
) throws (1: OpenrError error);
/**
* Get raw key-values from KvStore with more control over filter
*/
Types.Publication getKvStoreKeyValsFiltered(
1: Types.KeyDumpParams filter,
) throws (1: OpenrError error);
/**
* Get raw key-values from KvStore with more control over filter with 'area'
* option
*/
Types.Publication getKvStoreKeyValsFilteredArea(
1: Types.KeyDumpParams filter,
2: string area,
) throws (1: OpenrError error);
/**
* Get kvstore metadata (no values) with filter
*/
Types.Publication getKvStoreHashFiltered(
1: Types.KeyDumpParams filter,
) throws (1: OpenrError error);
/**
* with area
*/
Types.Publication getKvStoreHashFilteredArea(
1: Types.KeyDumpParams filter,
2: string area,
) throws (1: OpenrError error);
/**
* Set/Update key-values in KvStore.
*/
void setKvStoreKeyVals(
1: Types.KeySetParams setParams,
2: string area,
) throws (1: OpenrError error);
/**
* Long poll API to get KvStore
* Will return true/false with our own KeyVal snapshot provided
*/
bool longPollKvStoreAdjArea(
1: string area,
2: Types.KeyVals snapshot,
) throws (1: OpenrError error);
// Deprecated, prefer API sepcfying area
// TODO, remove once EBB has transition away from this
bool longPollKvStoreAdj(1: Types.KeyVals snapshot) throws (
1: OpenrError error,
);
/**
* Send Dual message
*/
void processKvStoreDualMessage(
1: Types.DualMessages messages,
2: string area,
) throws (1: OpenrError error);
/**
* Set flood-topology parameters. Called by neighbors
*/
void updateFloodTopologyChild(
1: Types.FloodTopoSetParams params,
2: string area,
) throws (1: OpenrError error);
/**
* Get spanning tree information
*/
Types.SptInfos getSpanningTreeInfos(1: string area) throws (
1: OpenrError error,
);
/**
* Get KvStore peers
*/
Types.PeersMap getKvStorePeers() throws (1: OpenrError error);
Types.PeersMap getKvStorePeersArea(1: string area) throws (
1: OpenrError error,
);
/**
* Get KvStore Summary for each configured area (provided as the filter set).
* The resp is a list of Summary structs, one for each area
*/
list<Types.KvStoreAreaSummary> getKvStoreAreaSummary(
1: set<string> selectAreas,
) throws (1: OpenrError error);
//
// LinkMonitor APIs
//
/**
* Commands to set/unset overload bit. If overload bit is set then the node
* will not do any transit traffic. However node will still be reachable in
* the network from other nodes.
*/
void setNodeOverload() throws (1: OpenrError error);
void unsetNodeOverload() throws (1: OpenrError error);
/**
* Command to set/unset overload bit for interface. If overload bit is set
* then no transit traffic will pass through the interface which is equivalent
* to hard drain on the interface.
*/
void setInterfaceOverload(1: string interfaceName) throws (
1: OpenrError error,
);
void unsetInterfaceOverload(1: string interfaceName) throws (
1: OpenrError error,
);
/**
* Command to override metric for adjacencies over specific interfaces. This
* can be used to emulate soft-drain of interfaces by using higher metric
* value for link.
*
* Request must have valid `interfaceName` and `overrideMetric` values.
*/
void setInterfaceMetric(
1: string interfaceName,
2: i32 overrideMetric,
) throws (1: OpenrError error);
void unsetInterfaceMetric(1: string interfaceName) throws (
1: OpenrError error,
);
/**
* Command to override metric for specific adjacencies. Request must have
* valid interface name, adjacency-node name and override metric value.
*/
void setAdjacencyMetric(
1: string interfaceName,
2: string adjNodeName,
3: i32 overrideMetric,
) throws (1: OpenrError error);
void unsetAdjacencyMetric(
1: string interfaceName,
2: string adjNodeName,
) throws (1: OpenrError error);
/**
* Get the current link status information
*/
Types.DumpLinksReply getInterfaces() throws (1: OpenrError error);
/**
* Get the current adjacencies information, only works for nodes with one
* configured area. DEPRECATED, prefer
*/
Types.AdjacencyDatabase getLinkMonitorAdjacencies() throws (
1: OpenrError error,
);
/**
* Get the current adjacencies information, provide set of areas to get
* adjancecy databases for. Providing an empty set will return a DB for
* all configured areas
*/
list<Types.AdjacencyDatabase> getLinkMonitorAdjacenciesFiltered(
1: AdjacenciesFilter filter,
) throws (1: OpenrError error);
/**
* Command to request OpenR version
*/
Types.OpenrVersions getOpenrVersion() throws (1: OpenrError error);
/**
* Command to request build information
* @deprecated - instead use getRegexExportedValues("build.*") API
*/
Types.BuildInfo getBuildInfo() throws (1: OpenrError error);
//
// PersistentStore APIs (query / alter dynamic configuration)
//
/**
* Set new config key - you will never need to use it
* NOTE: This API should only be accessible from local node
*/
void setConfigKey(1: string key, 2: binary value) throws (
1: OpenrError error,
);
/**
* Erase key from config
* NOTE: This API should only be accessible from local node
*/
void eraseConfigKey(1: string key) throws (1: OpenrError error);
/**
* Get config key
*/
binary getConfigKey(1: string key) throws (1: OpenrError error);
//
// Spark APIs
//
/*
* Send out SparkHelloMsg with `restarting` flag
* indicating graceful restart usage
*/
void floodRestartingMsg() throws (1: OpenrError error);
/*
* Get info for Spark neighors
*/
list<Types.SparkNeighbor> getNeighbors() throws (1: OpenrError error);
//
// Monitor APIs (get log events)
//
// Get log events
list<string> getEventLogs() throws (1: OpenrError error);
// Get Openr Node Name
string getMyNodeName();
//
// RibPolicy
//
/**
* Set RibPolicy.
*
* @throws OpenrError if rib-policy is not valid or enabled via configuration
*/
void setRibPolicy(1: RibPolicy ribPolicy) throws (1: OpenrError error);
/**
* Get RibPolicy.
*
* @throws OpenrError if rib-policy is not enabled via configuration or is
* not set previously
*/
RibPolicy getRibPolicy() throws (1: OpenrError error);
/**
* Clear RibPolicy.
* @throws OpenrError if rib-policy is not enabled via configuration or is
* not set previously.
*/
void clearRibPolicy() throws (1: OpenrError error);
}
| high | 0.919415 | 351 |
-- jrnlmode.test
--
-- execsql {PRAGMA temp.journal_mode}
PRAGMA temp.journal_mode | low | 0.732793 | 352 |
nqubits = 16;
name = "16v6 2 4 1 1 2";
nstates = 4;
amplitude[x_,y_] := (Exp[-15 I y] (1 (I Sin[x])^5 Cos[x]^11 + 1 (I Sin[x])^11 Cos[x]^5) + Exp[-13 I y] (3 (I Sin[x])^4 Cos[x]^12 + 3 (I Sin[x])^12 Cos[x]^4 + 4 (I Sin[x])^10 Cos[x]^6 + 4 (I Sin[x])^6 Cos[x]^10 + 2 (I Sin[x])^3 Cos[x]^13 + 2 (I Sin[x])^13 Cos[x]^3 + 3 (I Sin[x])^9 Cos[x]^7 + 3 (I Sin[x])^7 Cos[x]^9 + 2 (I Sin[x])^8 Cos[x]^8 + 2 (I Sin[x])^5 Cos[x]^11 + 2 (I Sin[x])^11 Cos[x]^5) + Exp[-11 I y] (9 (I Sin[x])^4 Cos[x]^12 + 9 (I Sin[x])^12 Cos[x]^4 + 28 (I Sin[x])^6 Cos[x]^10 + 28 (I Sin[x])^10 Cos[x]^6 + 14 (I Sin[x])^5 Cos[x]^11 + 14 (I Sin[x])^11 Cos[x]^5 + 34 (I Sin[x])^7 Cos[x]^9 + 34 (I Sin[x])^9 Cos[x]^7 + 38 (I Sin[x])^8 Cos[x]^8 + 1 (I Sin[x])^3 Cos[x]^13 + 1 (I Sin[x])^13 Cos[x]^3) + Exp[-9 I y] (90 (I Sin[x])^5 Cos[x]^11 + 90 (I Sin[x])^11 Cos[x]^5 + 114 (I Sin[x])^9 Cos[x]^7 + 114 (I Sin[x])^7 Cos[x]^9 + 25 (I Sin[x])^3 Cos[x]^13 + 25 (I Sin[x])^13 Cos[x]^3 + 12 (I Sin[x])^2 Cos[x]^14 + 12 (I Sin[x])^14 Cos[x]^2 + 120 (I Sin[x])^8 Cos[x]^8 + 54 (I Sin[x])^4 Cos[x]^12 + 54 (I Sin[x])^12 Cos[x]^4 + 98 (I Sin[x])^6 Cos[x]^10 + 98 (I Sin[x])^10 Cos[x]^6 + 2 (I Sin[x])^1 Cos[x]^15 + 2 (I Sin[x])^15 Cos[x]^1) + Exp[-7 I y] (31 (I Sin[x])^3 Cos[x]^13 + 31 (I Sin[x])^13 Cos[x]^3 + 455 (I Sin[x])^7 Cos[x]^9 + 455 (I Sin[x])^9 Cos[x]^7 + 207 (I Sin[x])^5 Cos[x]^11 + 207 (I Sin[x])^11 Cos[x]^5 + 341 (I Sin[x])^6 Cos[x]^10 + 341 (I Sin[x])^10 Cos[x]^6 + 488 (I Sin[x])^8 Cos[x]^8 + 82 (I Sin[x])^4 Cos[x]^12 + 82 (I Sin[x])^12 Cos[x]^4 + 5 (I Sin[x])^2 Cos[x]^14 + 5 (I Sin[x])^14 Cos[x]^2) + Exp[-5 I y] (733 (I Sin[x])^6 Cos[x]^10 + 733 (I Sin[x])^10 Cos[x]^6 + 946 (I Sin[x])^8 Cos[x]^8 + 276 (I Sin[x])^4 Cos[x]^12 + 276 (I Sin[x])^12 Cos[x]^4 + 123 (I Sin[x])^3 Cos[x]^13 + 123 (I Sin[x])^13 Cos[x]^3 + 884 (I Sin[x])^7 Cos[x]^9 + 884 (I Sin[x])^9 Cos[x]^7 + 478 (I Sin[x])^5 Cos[x]^11 + 478 (I Sin[x])^11 Cos[x]^5 + 29 (I Sin[x])^2 Cos[x]^14 + 29 (I Sin[x])^14 Cos[x]^2 + 6 (I Sin[x])^1 Cos[x]^15 + 6 (I Sin[x])^15 Cos[x]^1 + 1 Cos[x]^16 + 1 (I Sin[x])^16) + Exp[-3 I y] (274 (I Sin[x])^4 Cos[x]^12 + 274 (I Sin[x])^12 Cos[x]^4 + 2016 (I Sin[x])^8 Cos[x]^8 + 1226 (I Sin[x])^6 Cos[x]^10 + 1226 (I Sin[x])^10 Cos[x]^6 + 1771 (I Sin[x])^7 Cos[x]^9 + 1771 (I Sin[x])^9 Cos[x]^7 + 649 (I Sin[x])^5 Cos[x]^11 + 649 (I Sin[x])^11 Cos[x]^5 + 12 (I Sin[x])^2 Cos[x]^14 + 12 (I Sin[x])^14 Cos[x]^2 + 63 (I Sin[x])^3 Cos[x]^13 + 63 (I Sin[x])^13 Cos[x]^3 + 2 (I Sin[x])^1 Cos[x]^15 + 2 (I Sin[x])^15 Cos[x]^1) + Exp[-1 I y] (2097 (I Sin[x])^7 Cos[x]^9 + 2097 (I Sin[x])^9 Cos[x]^7 + 991 (I Sin[x])^5 Cos[x]^11 + 991 (I Sin[x])^11 Cos[x]^5 + 452 (I Sin[x])^4 Cos[x]^12 + 452 (I Sin[x])^12 Cos[x]^4 + 2272 (I Sin[x])^8 Cos[x]^8 + 1572 (I Sin[x])^6 Cos[x]^10 + 1572 (I Sin[x])^10 Cos[x]^6 + 141 (I Sin[x])^3 Cos[x]^13 + 141 (I Sin[x])^13 Cos[x]^3 + 40 (I Sin[x])^2 Cos[x]^14 + 40 (I Sin[x])^14 Cos[x]^2 + 6 (I Sin[x])^1 Cos[x]^15 + 6 (I Sin[x])^15 Cos[x]^1) + Exp[1 I y] (762 (I Sin[x])^5 Cos[x]^11 + 762 (I Sin[x])^11 Cos[x]^5 + 2404 (I Sin[x])^7 Cos[x]^9 + 2404 (I Sin[x])^9 Cos[x]^7 + 69 (I Sin[x])^3 Cos[x]^13 + 69 (I Sin[x])^13 Cos[x]^3 + 1577 (I Sin[x])^6 Cos[x]^10 + 1577 (I Sin[x])^10 Cos[x]^6 + 2748 (I Sin[x])^8 Cos[x]^8 + 238 (I Sin[x])^4 Cos[x]^12 + 238 (I Sin[x])^12 Cos[x]^4 + 11 (I Sin[x])^2 Cos[x]^14 + 11 (I Sin[x])^14 Cos[x]^2) + Exp[3 I y] (1245 (I Sin[x])^6 Cos[x]^10 + 1245 (I Sin[x])^10 Cos[x]^6 + 2022 (I Sin[x])^8 Cos[x]^8 + 253 (I Sin[x])^4 Cos[x]^12 + 253 (I Sin[x])^12 Cos[x]^4 + 81 (I Sin[x])^3 Cos[x]^13 + 81 (I Sin[x])^13 Cos[x]^3 + 1769 (I Sin[x])^7 Cos[x]^9 + 1769 (I Sin[x])^9 Cos[x]^7 + 635 (I Sin[x])^5 Cos[x]^11 + 635 (I Sin[x])^11 Cos[x]^5 + 11 (I Sin[x])^2 Cos[x]^14 + 11 (I Sin[x])^14 Cos[x]^2) + Exp[5 I y] (117 (I Sin[x])^4 Cos[x]^12 + 117 (I Sin[x])^12 Cos[x]^4 + 1366 (I Sin[x])^8 Cos[x]^8 + 712 (I Sin[x])^6 Cos[x]^10 + 712 (I Sin[x])^10 Cos[x]^6 + 1162 (I Sin[x])^7 Cos[x]^9 + 1162 (I Sin[x])^9 Cos[x]^7 + 311 (I Sin[x])^5 Cos[x]^11 + 311 (I Sin[x])^11 Cos[x]^5 + 18 (I Sin[x])^3 Cos[x]^13 + 18 (I Sin[x])^13 Cos[x]^3) + Exp[7 I y] (524 (I Sin[x])^7 Cos[x]^9 + 524 (I Sin[x])^9 Cos[x]^7 + 163 (I Sin[x])^5 Cos[x]^11 + 163 (I Sin[x])^11 Cos[x]^5 + 54 (I Sin[x])^4 Cos[x]^12 + 54 (I Sin[x])^12 Cos[x]^4 + 326 (I Sin[x])^6 Cos[x]^10 + 326 (I Sin[x])^10 Cos[x]^6 + 584 (I Sin[x])^8 Cos[x]^8 + 6 (I Sin[x])^3 Cos[x]^13 + 6 (I Sin[x])^13 Cos[x]^3) + Exp[9 I y] (58 (I Sin[x])^5 Cos[x]^11 + 58 (I Sin[x])^11 Cos[x]^5 + 173 (I Sin[x])^9 Cos[x]^7 + 173 (I Sin[x])^7 Cos[x]^9 + 204 (I Sin[x])^8 Cos[x]^8 + 114 (I Sin[x])^6 Cos[x]^10 + 114 (I Sin[x])^10 Cos[x]^6 + 8 (I Sin[x])^4 Cos[x]^12 + 8 (I Sin[x])^12 Cos[x]^4) + Exp[11 I y] (60 (I Sin[x])^8 Cos[x]^8 + 26 (I Sin[x])^6 Cos[x]^10 + 26 (I Sin[x])^10 Cos[x]^6 + 7 (I Sin[x])^5 Cos[x]^11 + 7 (I Sin[x])^11 Cos[x]^5 + 42 (I Sin[x])^7 Cos[x]^9 + 42 (I Sin[x])^9 Cos[x]^7) + Exp[13 I y] (6 (I Sin[x])^6 Cos[x]^10 + 6 (I Sin[x])^10 Cos[x]^6 + 4 (I Sin[x])^8 Cos[x]^8 + 7 (I Sin[x])^9 Cos[x]^7 + 7 (I Sin[x])^7 Cos[x]^9) + Exp[15 I y] (1 (I Sin[x])^9 Cos[x]^7 + 1 (I Sin[x])^7 Cos[x]^9))/Sqrt[2^nqubits];
amplitude2[x_,y_] := (Exp[-15 I y] (1 (I Sin[x])^5 Cos[x]^11 + 1 (I Sin[x])^11 Cos[x]^5) + Exp[-13 I y] (3 (I Sin[x])^4 Cos[x]^12 + 3 (I Sin[x])^12 Cos[x]^4 + 4 (I Sin[x])^10 Cos[x]^6 + 4 (I Sin[x])^6 Cos[x]^10 + 2 (I Sin[x])^3 Cos[x]^13 + 2 (I Sin[x])^13 Cos[x]^3 + 3 (I Sin[x])^9 Cos[x]^7 + 3 (I Sin[x])^7 Cos[x]^9 + 2 (I Sin[x])^8 Cos[x]^8 + 2 (I Sin[x])^5 Cos[x]^11 + 2 (I Sin[x])^11 Cos[x]^5) + Exp[-11 I y] (9 (I Sin[x])^4 Cos[x]^12 + 9 (I Sin[x])^12 Cos[x]^4 + 28 (I Sin[x])^6 Cos[x]^10 + 28 (I Sin[x])^10 Cos[x]^6 + 14 (I Sin[x])^5 Cos[x]^11 + 14 (I Sin[x])^11 Cos[x]^5 + 34 (I Sin[x])^7 Cos[x]^9 + 34 (I Sin[x])^9 Cos[x]^7 + 38 (I Sin[x])^8 Cos[x]^8 + 1 (I Sin[x])^3 Cos[x]^13 + 1 (I Sin[x])^13 Cos[x]^3) + Exp[-9 I y] (90 (I Sin[x])^5 Cos[x]^11 + 90 (I Sin[x])^11 Cos[x]^5 + 114 (I Sin[x])^9 Cos[x]^7 + 114 (I Sin[x])^7 Cos[x]^9 + 25 (I Sin[x])^3 Cos[x]^13 + 25 (I Sin[x])^13 Cos[x]^3 + 12 (I Sin[x])^2 Cos[x]^14 + 12 (I Sin[x])^14 Cos[x]^2 + 120 (I Sin[x])^8 Cos[x]^8 + 54 (I Sin[x])^4 Cos[x]^12 + 54 (I Sin[x])^12 Cos[x]^4 + 98 (I Sin[x])^6 Cos[x]^10 + 98 (I Sin[x])^10 Cos[x]^6 + 2 (I Sin[x])^1 Cos[x]^15 + 2 (I Sin[x])^15 Cos[x]^1) + Exp[-7 I y] (31 (I Sin[x])^3 Cos[x]^13 + 31 (I Sin[x])^13 Cos[x]^3 + 455 (I Sin[x])^7 Cos[x]^9 + 455 (I Sin[x])^9 Cos[x]^7 + 207 (I Sin[x])^5 Cos[x]^11 + 207 (I Sin[x])^11 Cos[x]^5 + 341 (I Sin[x])^6 Cos[x]^10 + 341 (I Sin[x])^10 Cos[x]^6 + 488 (I Sin[x])^8 Cos[x]^8 + 82 (I Sin[x])^4 Cos[x]^12 + 82 (I Sin[x])^12 Cos[x]^4 + 5 (I Sin[x])^2 Cos[x]^14 + 5 (I Sin[x])^14 Cos[x]^2) + Exp[-5 I y] (733 (I Sin[x])^6 Cos[x]^10 + 733 (I Sin[x])^10 Cos[x]^6 + 946 (I Sin[x])^8 Cos[x]^8 + 276 (I Sin[x])^4 Cos[x]^12 + 276 (I Sin[x])^12 Cos[x]^4 + 123 (I Sin[x])^3 Cos[x]^13 + 123 (I Sin[x])^13 Cos[x]^3 + 884 (I Sin[x])^7 Cos[x]^9 + 884 (I Sin[x])^9 Cos[x]^7 + 478 (I Sin[x])^5 Cos[x]^11 + 478 (I Sin[x])^11 Cos[x]^5 + 29 (I Sin[x])^2 Cos[x]^14 + 29 (I Sin[x])^14 Cos[x]^2 + 6 (I Sin[x])^1 Cos[x]^15 + 6 (I Sin[x])^15 Cos[x]^1 + 1 Cos[x]^16 + 1 (I Sin[x])^16) + Exp[-3 I y] (274 (I Sin[x])^4 Cos[x]^12 + 274 (I Sin[x])^12 Cos[x]^4 + 2016 (I Sin[x])^8 Cos[x]^8 + 1226 (I Sin[x])^6 Cos[x]^10 + 1226 (I Sin[x])^10 Cos[x]^6 + 1771 (I Sin[x])^7 Cos[x]^9 + 1771 (I Sin[x])^9 Cos[x]^7 + 649 (I Sin[x])^5 Cos[x]^11 + 649 (I Sin[x])^11 Cos[x]^5 + 12 (I Sin[x])^2 Cos[x]^14 + 12 (I Sin[x])^14 Cos[x]^2 + 63 (I Sin[x])^3 Cos[x]^13 + 63 (I Sin[x])^13 Cos[x]^3 + 2 (I Sin[x])^1 Cos[x]^15 + 2 (I Sin[x])^15 Cos[x]^1) + Exp[-1 I y] (2097 (I Sin[x])^7 Cos[x]^9 + 2097 (I Sin[x])^9 Cos[x]^7 + 991 (I Sin[x])^5 Cos[x]^11 + 991 (I Sin[x])^11 Cos[x]^5 + 452 (I Sin[x])^4 Cos[x]^12 + 452 (I Sin[x])^12 Cos[x]^4 + 2272 (I Sin[x])^8 Cos[x]^8 + 1572 (I Sin[x])^6 Cos[x]^10 + 1572 (I Sin[x])^10 Cos[x]^6 + 141 (I Sin[x])^3 Cos[x]^13 + 141 (I Sin[x])^13 Cos[x]^3 + 40 (I Sin[x])^2 Cos[x]^14 + 40 (I Sin[x])^14 Cos[x]^2 + 6 (I Sin[x])^1 Cos[x]^15 + 6 (I Sin[x])^15 Cos[x]^1) + Exp[1 I y] (762 (I Sin[x])^5 Cos[x]^11 + 762 (I Sin[x])^11 Cos[x]^5 + 2404 (I Sin[x])^7 Cos[x]^9 + 2404 (I Sin[x])^9 Cos[x]^7 + 69 (I Sin[x])^3 Cos[x]^13 + 69 (I Sin[x])^13 Cos[x]^3 + 1577 (I Sin[x])^6 Cos[x]^10 + 1577 (I Sin[x])^10 Cos[x]^6 + 2748 (I Sin[x])^8 Cos[x]^8 + 238 (I Sin[x])^4 Cos[x]^12 + 238 (I Sin[x])^12 Cos[x]^4 + 11 (I Sin[x])^2 Cos[x]^14 + 11 (I Sin[x])^14 Cos[x]^2) + Exp[3 I y] (1245 (I Sin[x])^6 Cos[x]^10 + 1245 (I Sin[x])^10 Cos[x]^6 + 2022 (I Sin[x])^8 Cos[x]^8 + 253 (I Sin[x])^4 Cos[x]^12 + 253 (I Sin[x])^12 Cos[x]^4 + 81 (I Sin[x])^3 Cos[x]^13 + 81 (I Sin[x])^13 Cos[x]^3 + 1769 (I Sin[x])^7 Cos[x]^9 + 1769 (I Sin[x])^9 Cos[x]^7 + 635 (I Sin[x])^5 Cos[x]^11 + 635 (I Sin[x])^11 Cos[x]^5 + 11 (I Sin[x])^2 Cos[x]^14 + 11 (I Sin[x])^14 Cos[x]^2) + Exp[5 I y] (117 (I Sin[x])^4 Cos[x]^12 + 117 (I Sin[x])^12 Cos[x]^4 + 1366 (I Sin[x])^8 Cos[x]^8 + 712 (I Sin[x])^6 Cos[x]^10 + 712 (I Sin[x])^10 Cos[x]^6 + 1162 (I Sin[x])^7 Cos[x]^9 + 1162 (I Sin[x])^9 Cos[x]^7 + 311 (I Sin[x])^5 Cos[x]^11 + 311 (I Sin[x])^11 Cos[x]^5 + 18 (I Sin[x])^3 Cos[x]^13 + 18 (I Sin[x])^13 Cos[x]^3) + Exp[7 I y] (524 (I Sin[x])^7 Cos[x]^9 + 524 (I Sin[x])^9 Cos[x]^7 + 163 (I Sin[x])^5 Cos[x]^11 + 163 (I Sin[x])^11 Cos[x]^5 + 54 (I Sin[x])^4 Cos[x]^12 + 54 (I Sin[x])^12 Cos[x]^4 + 326 (I Sin[x])^6 Cos[x]^10 + 326 (I Sin[x])^10 Cos[x]^6 + 584 (I Sin[x])^8 Cos[x]^8 + 6 (I Sin[x])^3 Cos[x]^13 + 6 (I Sin[x])^13 Cos[x]^3) + Exp[9 I y] (58 (I Sin[x])^5 Cos[x]^11 + 58 (I Sin[x])^11 Cos[x]^5 + 173 (I Sin[x])^9 Cos[x]^7 + 173 (I Sin[x])^7 Cos[x]^9 + 204 (I Sin[x])^8 Cos[x]^8 + 114 (I Sin[x])^6 Cos[x]^10 + 114 (I Sin[x])^10 Cos[x]^6 + 8 (I Sin[x])^4 Cos[x]^12 + 8 (I Sin[x])^12 Cos[x]^4) + Exp[11 I y] (60 (I Sin[x])^8 Cos[x]^8 + 26 (I Sin[x])^6 Cos[x]^10 + 26 (I Sin[x])^10 Cos[x]^6 + 7 (I Sin[x])^5 Cos[x]^11 + 7 (I Sin[x])^11 Cos[x]^5 + 42 (I Sin[x])^7 Cos[x]^9 + 42 (I Sin[x])^9 Cos[x]^7) + Exp[13 I y] (6 (I Sin[x])^6 Cos[x]^10 + 6 (I Sin[x])^10 Cos[x]^6 + 4 (I Sin[x])^8 Cos[x]^8 + 7 (I Sin[x])^9 Cos[x]^7 + 7 (I Sin[x])^7 Cos[x]^9) + Exp[15 I y] (1 (I Sin[x])^9 Cos[x]^7 + 1 (I Sin[x])^7 Cos[x]^9));
probability[x_, y_] := Abs[amplitude[x, y]]^2;
result = NMaximize[{nstates*probability[a, b], 0 < a < Pi/2, 0 < b < Pi}, {a, b}, Method -> {"SimulatedAnnealing", "PerturbationScale" -> 15}];
Print[name, ": ", result]
f = probability[c, d]; n = Pi;
Plot3D[f, {c, 0, n/2}, {d, -n, n}, PlotRange -> All]
ContourPlot[probability[x, y], {x, 0, n/2}, {y, 0, n}, PlotLegends -> Automatic, Contours -> 30]
| high | 0.176503 | 353 |
visiting
visitYieldNode: node
(script prim: #yield) node: node | low | 0.745925 | 354 |
%%%-------------------------------------------------------------------
%%% @doc
%%% This module contains API for creation and manipulation of triangles.
%%% @end
%%%-------------------------------------------------------------------
-module(triangle).
-type triangle_edge() :: float().
%% The edge of a triangle, that is a positive floating point number.
-type triangle() :: {triangle_edge(), triangle_edge(), triangle_edge()}.
%% The triangle, that is a set of three edges.
-type edge_type() :: equilateral | isosceles | scalene.
%% The type of the triangle, based on its edges.
%% API
-export([new/3, edge_type/1]).
%% @doc Create a new triangle with given valid triangle edges.
-spec new(triangle_edge(), triangle_edge(), triangle_edge()) -> triangle().
new(Edge1, Edge2, Edge3) when (Edge1 + Edge2) > Edge3,
(Edge2 + Edge3) > Edge1,
(Edge1 + Edge3) > Edge2,
is_float(Edge1),
is_float(Edge2),
is_float(Edge3) ->
{Edge1, Edge2, Edge3}.
%% @doc Returns the edge type of the triangle based, given a valid triangle as an input.
-spec edge_type(triangle()) -> edge_type().
edge_type({Edge, Edge, Edge}) -> equilateral;
edge_type({Edge, Edge, _AnotherEdge}) -> isosceles;
edge_type({Edge, _AnotherEdge, Edge}) -> isosceles;
edge_type({_AnotherEdge, Edge, Edge}) -> isosceles;
edge_type(_) -> scalene.
| high | 0.717935 | 355 |
// This file was generated with the Protobuf generator tool.
// Dataset ID : 62
// Dataset Name : zoo;
// Dataset URL : https://www.openml.org/data/v1/download/52352/zoo.arff
// Num. Columns : 17
// Num. Rows : 101
// Target Feature: type
// Beginning of Description of Dataset:
// **Author**: Richard S. Forsyth
// **Source**: [UCI](https://archive.ics.uci.edu/ml/datasets/Zoo) - 5/15/1990
// **Please cite**:
// **Zoo database**
// A simple database containing 17 Boolean-valued attributes describing animals. The "type" attribute appears to be the class attribute.
// Notes:
// * I find it unusual that there are 2 instances of "frog" and one of "girl"!
// * feature 'animal' is an identifier (though not unique) and should be ignored when modeling
//
syntax = "proto3";
message Empty {
}
message Features {
string Hair = 1;
string Feathers = 2;
string Eggs = 3;
string Milk = 4;
string Airborne = 5;
string Aquatic = 6;
string Predator = 7;
string Toothed = 8;
string Backbone = 9;
string Breathes = 10;
string Venomous = 11;
string Fins = 12;
uint32 Legs = 13;
string Tail = 14;
string Domestic = 15;
string Catsize = 16;
string Type = 17;
}
service get_next_row {
rpc get_next_row(Empty) returns(Features);
}
/*
//This code section can be directly used
//at the end of gen_next_row in the server.py file
//for OpenML dataset nr. 62
response.Hair = row[0]
response.Feathers = row[1]
response.Eggs = row[2]
response.Milk = row[3]
response.Airborne = row[4]
response.Aquatic = row[5]
response.Predator = row[6]
response.Toothed = row[7]
response.Backbone = row[8]
response.Breathes = row[9]
response.Venomous = row[10]
response.Fins = row[11]
response.Legs = numpy.uint32(row[12])
response.Tail = row[13]
response.Domestic = row[14]
response.Catsize = row[15]
response.Type = row[16]
*/
| high | 0.635025 | 356 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% System :
% Module :
% Object Name : $RCSfile$
% Revision : $Revision$
% Date : $Date$
% Author : $Author$
% Created By : Robert Heller
% Created : Thu May 20 07:35:55 2021
% Last Modified : <211227.1554>
%
% Description
%
% Notes
%
% History
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (C) 2021 Robert Heller D/B/A Deepwoods Software
% 51 Locke Hill Road
% Wendell, MA 01379-9728
%
% 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.
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{ESP32-PWMHalfSidingSMD: Half Siding board base board for an ESP32 Dev Kit MCU board}
This is a circuit board that supports an ESP32 Dev Kit board or TTGO-T1 board
to manage one half (one end) of a siding. This board can also be used to
manage two bi-directional single track ABS blocks or one bi-directional dual
track ABS block. There are other trackwork cases this board can handle as
well. The board contains these I/O sections:
\begin{itemize}
\item Two occupancy detectors. These are optoisolator based, so they will
work for both DC and DCC systems.
\item Two stall-motor with point sense.
\item Sixteen PWM Led drivers. These are meant to light lamps in signal
heads.
\end{itemize}
This board uses six GPIO pins and one I2C channel:
\begin{description}
\item[GPIO0] Motor Select 1: select the position of stall motor 1.
\item[GPIO12] Motor Select 2: select the position of stall motor 2.
\item[GPIO34] Point Sense 1: return the state of the points for
stall motor 1.
\item[GPIO35] Point Sense 2: return the state of the points for
stall motor 2.
\item[GPIO26] Occupancy Detector 1.
\item[GPIO27] Occupancy Detector 2.
\item[GPIO16] (Optional) Output enable for the PWM LED Controller.
\item[I2C Address 0x40] A PCA9685 16-channel, 12-bit PWM LED Controller.
\end{description}
Each of the motor drive circuits is through a TC4428, which can drive up to
1.5A, which is way more needed to drive a typical stall motor. It is enough to
drive a pair of stall motors, wired in parallel as would be the case for a
cross over.
\section{Circuit Description}
\subsection{Turnout Control}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-1.pdf}
\caption{Circuit Diagram of the ESP32-PWMHalfSidingSMD, page 1 (ESP32 MCU and
Turnout Driver and Sense)}
\end{centering}\end{figure}
The turnout control has two parts. There is an output section that contains
two TC4428 chips. Each chip has a non-inverting and an inverting driver. The
inputs of both drivers are connected to one of the motor GPIO pins. The output
are wired to the terminal block for a one of the motors. For any given logic
state of the motor control output, one of the drivers is ``on'' and the other
is ``off'', thus one motor terminal is ground and one is raised to the 12V
supply. This means alternative states of the logic line will drive the stall
motor in alternative directions.
The other section is a pair of flip-flop debounce circuits, one for each of
two SPDT switch contacts that report the position of the turnout points. The
output of these flip-flops goes to a pair of GPIO input pins.
\clearpage
\subsection{CAN Transceiver}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-2.pdf}
\caption{Circuit Diagram of the ESP32-PWMHalfSidingSMD, page 2 (CAN Transceiver)}
\end{centering}\end{figure}
This section contains the CAN Transceiver, along with a termination jumper
block. Power insertion and pick off and the RJ45 Jacks.
\clearpage
\subsection{Power Supply}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-3.pdf}
\caption{Circuit Diagram of the ESP32-PWMHalfSidingSMD, page 3 (Power Supply)}
\end{centering}\end{figure}
This section contains a 5V power supply that takes the nominal 12V on the CAN
power bus and regulates it down to 5V to supply the ESP32 MCU board.
\clearpage
\subsection{Occupancy Detectors}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-4.pdf}
\caption{Circuit Diagram of the ESP32-PWMHalfSidingSMD, page 4 (Occupancy
Detector 1)}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-5.pdf}
\caption{Circuit Diagram of the ESP32-PWMHalfSidingSMD, page 5 (Occupancy
Detector 2)}
\end{centering}\end{figure}
The occupancy detectors use optoisolators in series with the track power
supply. There is a heavy duty bridge rectifier in parallel with the
optoisolators to carry the bulk of the current to the track. They will work
with either DC or DCC track power.
\clearpage
\subsection{PWM LED Driver}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-6.pdf}
\caption{Circuit Diagram of the ESP32-PWMHalfSidingSMD, page 6 (PWM LED Driver)}
\end{centering}\end{figure}
The PWM LED Driver uses a PCA9685 which is a 16 channel, 12 bit PWD LED
driver. A pair of octal MOSFET drivers and series load resistors are also
included on the board. The MOSFET drivers come in both inverting (low-side
drive) and non-inverting (high-side drive), so it is possible to support both
common anode and common cathode LED signals.
\clearpage
\section{User Installed Parts}
\begin{centering}\begin{tabular}{|r|l|l|p{1.5in}|p{1.5in}|}
\hline
Index&Qty&Refs&Mouser Part Number&Description\\
\hline
1&2&J1, J2&710-615008144221&RJ45 Jacks\\
\hline
2&1&JP1&649-67997-404HLF&Termination Jumper -- 2x2 pin header\\
\hline
3&1&J3&649-1012937890304BLF&I2C SCL Select Jumper -- 3-pos 2.54 pitch pin header\\
\hline
4&2&P601, P602&651-1725724&Signal Lamp Terminals -- 9-pos 2.54 pitch screw terminals\\
\hline
5&3&T1, T2, T601&651-1725656&LCC and Signal power -- 2-pos 2.54 pitch screw terminals\\
\hline
6&2&T3, T6&490-TB007-508-02BE&Occupancy Terminals -- 2-pos 5.08 pitch screw terminals\\
\hline
7&2&T4, T5&651-1725685&Turnout terminals -- 5-pos 2.54 pitch screw terminals\\
\hline
8&2&U0&517-929974-01-19-RK&MCU Headers -- 19x1 pin socket headers\\
\hline
9&1&U0&517-929850-01-18-10&MCU Headers -- 18x1 pin socket headers\\
\hline
\end{tabular}\end{centering}
\section{Circuit Board Layout}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-brd.png}
\caption{Fabrication image of the ESP32-PWMHalfSiding board}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32-PWMHalfSidingSMD-top3D.png}
\caption{3D image of the ESP32-PWMHalfSiding board}
\end{centering}\end{figure}
\subsection{Notes on Building the board}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32HalfSidingWiringSMD.png}
\caption{Placement of terminal blocks, connectors, and jumper blocks.}
\end{centering}\end{figure}
The board comes with all the surface mount devices soldered to the board. All
you need to do is solder the through-hole parts, which consists of:
\begin{description}
\item[Screw Terminals] 3 2-position 2.54 pitch terminals (LCC power in and
out, lamp power in), 2 5-position 2.54 pitch terminals (motor 1 and motor
2), 2 9-position 2.54 pitch terminals (signal lamp outputs), and 2 2-position
5.08 pitch terminals (Occ. Det. 1 and Occ. Det. 2).
\item[Pin Headers] 1 2x2 pin header (termination jumpers) and 1 1x3 pin header
(I2C SCL GPIO selection).
\item[Connectors] 2 RJ45 connectors (LCC Network).
\item[Pin Socket Headers] 2 19x1 and 1 18x1, for the MCU module.
\end{description}
For most of these parts you should solder one pin and then while pressing the
part against the board, reflow the solder to make sure the part is tight and
square to the board before letting the solder cool while holding the part
tight to the board. Before soldering the rest of the pins, check that the part
is fully tight and flush to the board. Also for the screw terminals, make sure
the wire openings are facing out from the board. The install ordering is from
shortest to tallest parts.
\clearpage
\section{Downloadables and Software Support}
The ESP32 needs to have a program installed in it to run the board. This
program can be downloaded from GitHub as part of the RRCircuits package:
\url{https://github.com/RobertPHeller/RPi-RRCircuits}. The sketch is in the
ESP32MRNSketches folder and is named ESP32-PWMHalfSiding.
\subsection{Building and installing the software}
The ESP32 MCU is programmed with the Arduino IDE. It uses two libraries: the
FaBo PWM PCA9685 library for the PCA9685 chip and the OpenMRN\_lite library to
implement the OpenLCB/LCC stack. First you need to install board support for
the ESP32 and then install the FaBo PWM PCA9685 library. Both of these can be
done using the Arduino IDE board and library managers. Installing the
OpenMRN\_lite library is a little different. The OpenMRN\_lite library is part
of the OpenMRN package, available on GitHub here:
\url{https://github.com/bakerstu/openmrn}. You will also need the sketch for
this board which is also on GitHub in the RRCircuits repository:
\url{https://github.com/RobertPHeller/RPi-RRCircuits} in the
ESP32MRNSketches/ESP32-PWMHalfSiding. The kit includes a thumb drive that
contains two Zip files: one for the OpenMRN\_lite library
(\texttt{OpenMRN\_lite.zip}) and one for the sketch
(\texttt{ESP32-PWMHalfSiding.zip}). Just unpack the \texttt{OpenMRN\_lite.zip}
file under your Arduino libraries folder (usually named libraries in the
Arduino folder in your home folder). And then unpack the sketch
(\texttt{ESP32-PWMHalfSiding.zip}) directly under your Arduino folder. Then
open the sketch with the Arduino IDE. Before you compile it, you will need to
edit the NODEID.h file to set the node ID, which should be one of the node ids
you got from the OpenLCB website. If you have more than one of these boards,
you need to give each one a different node id.
Once you have built the sketch, you can upload it using an USB cable connected
between your computer and the MCU board.
\subsection{Program Description}
The program consists of a main sketch file, and several support files. Most
of the support files implement I/O or logic elements:
\begin{description}
\item[Blink.h] This file provides support for blinking (flashing) signal
lamps.
\item[config.h] This file defines the structure of the node's configuration.
\item[Lamp.h] This file implements the output functions for signal lamps.
\item[Logic.cpp, Logic.h] These files implement the Logic elements available
in the node.
\item[Mast.cpp, Mast.h] These files implement signal masts.
\item[NODEID.h] This file contains the Node ID.
\item[OccupancyDetector.h] This file implements the occupancy detector inputs.
\item[Points.h] This file implements the point sense inputs.
\item[PWM.h] This file implements the PWM abstraction.
\item[Rule.cpp, Rule.h] These files implement traffic rules.
\item[TrackCircuit.cpp, TrackCircuit.h] These files implement track circuits.
\item[Turnout.h] This file implements the switch motor outputs.
\end{description}
\section{General Wiring Notes}
There are various terminal blocks, connectors, and jumper blocks on this
board. At the top end of the board are a pair of two position terminal blocks,
one for injecting power into the LCC bus and one for extracting power from the
LCC bus. Between these terminal blocks is the termination jumper block for
the LCC bus. Below the LCC power terminal blocks is a pair of RJ45
connectors. These are for connecting the board to the LCC bus. These
connectors are wired in parallel. Down along the left side are the two stall
motor terminal blocks (small 5 position terminal blocks) and the occupancy
detector terminal blocks (large 2 position terminal blocks). On the right
side are two 9 position terminal blocks for the signal lamp LEDs. Finally, at
the bottom right is a two position terminal block to (optionally) provide
power for the signal lamp LEDs.
\subsection{LCC Power}
Power can be optionally injected into the LCC bus or extracted from the LCC
bus. Power can be injected to into the LCC bus to power this and other boards.
Power can also be extracted to power local devices.
\subsection{I2C SCL GPIO Selection}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics{I2C-SCL-Jumper_edited.png}
\caption{I2C SCL Jumper Options}
\label{fig:ESP32-PWMHalfSidingI2CSCLJumper}
\end{centering}\end{figure}
There is a jumper to selecting the GPIO pin to use for I2C SCL line. If you
are using an ESP32 DevKit you would use GPIO 22. If you are using a Lily Go
TTGO-T1, you might want to use GPIO 23 since GPIO 22 on the TTGO-T1 is wired
to its on-board LED and this has been known to cause issues with the I2C
interface. If you select Arduino IDE's board type ``TTGO-T1'', SCL is mapped
to GPIO 23 -- it is possible to select the generic ESP32 DevKit as the board
type to compile for the ``TTGO-T1'', in which case SCL is mapped to GPIO 22.
You should install a shunt jumper that matches how you compiled the firmware.
\subsection{LCC Bus connections and termination}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics{ESP32-PWMHalfSidingTermination.png}
\caption{Termination Jumper Options}
\label{fig:ESP32-PWMHalfSidingTermination}
\end{centering}\end{figure}
The two RJ45 connections connect to the LCC bus. If this board is at the end
of bus, you will need to terminate the bus. There are two possible
termination options as shown in
Figure~\ref{fig:ESP32-PWMHalfSidingTermination}.
\subsection{Stall Motor connections}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics{ESP32-PWMHalfSidingTurnoutMotorsFig.png}
\caption{Stall Motor terminal block connections}
\label{fig:ESP32-PWMHalfSidingTurnoutMotorsFig}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics{ESP32-PWMHalfSidingTotoiseWiring.png}
\caption{Wiring a Tortoise to the ESP32-PWMHalfSiding Turnout Motors terminals}
\label{fig:ESP32-PWMHalfSidingTotoiseWiring}
\end{centering}\end{figure}
The five position Stall Motor terminal blocks, shown in
Figure~\ref{fig:ESP32-PWMHalfSidingTurnoutMotorsFig}, connect to the turnout
stall motors, the Motor A and Motor B connections go to the motor (pins 1 and
8 of a tortoise), the other three connections go to a single pole double
through switch contacts to sense the position of the stall motor / points.
There are contacts available on tortoise stall motor that can be used for this
purpose, as shown in Figure~\ref{fig:ESP32-PWMHalfSidingTotoiseWiring}.
\clearpage
\subsection{Occupancy Detector connections}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics{ESP32-PWMHalfSidingOccupancyDetectors.png}
\caption{Occupancy Detector Wiring}
\label{fig:ESP32-PWMHalfSidingOccupancyDetectors}
\end{centering}\end{figure}
The larger two position Occupancy Detector terminal blocks are connected to
the track power feeds as shown in
Figure~\ref{fig:ESP32-PWMHalfSidingOccupancyDetectors}.
\clearpage
\subsection{Signal Lamp (LED) connections}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics{ESP32-PWMHalfSidingLampDivers.png}
\caption{Typical Signal Lamp Diver Wiring}
\label{fig:ESP32-PWMHalfSidingLampDivers}
\end{centering}\end{figure}
Signal lamp diver wiring assumes common cathode or common anode signals as
shown Figure~\ref{fig:ESP32-PWMHalfSidingLampDivers}.
\clearpage
\section{Application Notes}
Three applications will presented, a typical siding using two boards, an
implementation of a section of Automatic Block Signals, and Crossing with
Interchange. Other trackwork arrangements are possible as well.
\subsection{Typical Siding}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ExampleSiding.png}
\caption{A Typical Siding}
\label{fig:ExampleSiding}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ESP32HalfSiding-CP1Wiring.png}
\caption{Wiring the ESP32HalfSiding board to the control elements of CP1 (West
end of the siding)}
\label{fig:ESP32HalfSiding-CP1Wiring}
\end{centering}\end{figure}
A typical siding is shown in Figure~\ref{fig:ExampleSiding}. And the wiring of
the west end, CP1, is shown in Figure~\ref{fig:ESP32HalfSiding-CP1Wiring}. The
other end is wired similarly (except that the second occupancy detector is
wired to the main line block between the turnouts).
\subsubsection{Configuring the CP1 node (west end)}
\paragraph{Node identification configuration}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-ID-Config-Annotated.png}
\caption{CP1 Node ID configuration}
\label{fig:CP1-ID-Config}
\end{centering}\end{figure}
First the node's user name and description is configured. This makes it easier
to find the node in the node listing.
\clearpage
\paragraph{Occupancy Detector configuration}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-OC-Config-Annotated.png}
\caption{CP1 Occupancy Detectors configuration}
\label{fig:CP1-OC-Config}
\end{centering}\end{figure}
Next we configure the Occupancy Detectors. All we do at this point is fill in
the names of the blocks. This helps us when we grab the event ids later.
\clearpage
\paragraph{Turnout and Points configuration}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-Turnout-Config-Annotated.png}
\caption{CP1 Turnout and Points configuration}
\label{fig:CP1-Turnout-Config}
\end{centering}\end{figure}
Next we configure the Turnout and Points. All we do at this point is fill in
the name of the turnout. We fill in the name for both the turnout and the
points. Only turnout 1 and points 1 are configured, since we are only using
motor 1.
\clearpage
\paragraph{Signal mast configuration}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-Mast1-Config-Annotated.png}
\caption{CP1, Mast1 configuration}
\label{fig:CP1-Mast1-Config}
\end{centering}\end{figure}
Now we skip down to the masts. Mast 1 is the two head signal at the points
entrance, named CP1ME (Control Point 1, main, eastbound). We set its Mast ID
and copy and past its Track Circuit Link Address to Circuit 1. This is a 3
(green-yellow-red) over 2 (yellow-red) signal. It has 4 rules:
\begin{table}[htbp]\begin{centering}\begin{tabular}{|l|l|l|l|}
\hline
Tab&Rule Name&Track Speed&Appearance\\
\hline
Rule 1&0-Stop&Stop&Red over Red\\
Rule 2&21-Approach&Approach&Yellow over Red\\
Rule 3&29-Clear&Clear/Proceed&Green over Red\\
Rule 4&1-Take Siding&Slow&Red over Yellow\\
\hline
\end{tabular}
\caption{CP1ME's Rules}
\label{tab:CP1MERules}
\end{centering}\end{table}
The LEDs are wired to lamp group A as follows (see Figure~\ref{fig:ESP32HalfSiding-CP1Wiring}:
\begin{description}
\item[A0] Upper Green
\item[A1] Upper Yellow
\item[A2] Upper Red
\item[A3] Lower Yellow
\item[A4] Lower Red
\end{description}
Lamp 1 will be the upper head and Lamp 2 will be for the lower head:
\begin{description}
\item[Rule 1: 0-Stop] Red over Red -- Lamp 1 will be A2 (upper red) and Lamp 2
will be A4 (lower red).
\item[Rule 2: 21-Approach] Yellow over Red -- Lamp 1 will be A1 (upper yellow)
and Lamp 2 will be A4 (lower red).
\item[Rule 3: 29-Clear] Green over Red -- Lamp 1 will be A0 (upper green) and
Lamp 2 will be A4 (lower red).
\item[Rule 4: 1-Take Siding] Red over Yellow -- Lamp 1 will be A2 (upper red)
and Lamp 2 will be A3 (lower yellow).
\end{description}
\clearpage
\paragraph{Logic block configuration}
\subparagraph{Logic for interlocking}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-OSVeto-Normal1-Annotated.png}
\caption{CP1 OS Veto, part 1 (description, group function, variable 1)}
\label{fig:CP1-OSVeto-Normal1}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-OSVeto-Normal2-Annotated.png}
\caption{CP1 OS Veto, part 2 (variable 2)}
\label{fig:CP1-OSVeto-Normal2}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1-OSVeto-Normal3-Annotated.png}
\caption{CP1 OS Veto, part 3 (Action 1)}
\label{fig:CP1-OSVeto-Normal3}
\end{centering}\end{figure}
Next we use the CP1 OS occupancy detector as a veto to prevent moving the
points while a train is occupying the turnout. This is done with two logic
elements. One logic handles the normal request and the other handles the
reverse request. The second variable consumer events for these logics become
the external events consumed for throwing the turnout and the variable 2
events for the first logic are cross copied to the second logic.
\clearpage
\subparagraph{Logic for signal CP1ME}
This signal uses a chain of four logic blocks to implement this logic:
\begin{verbatim}
if OS is occupied then
show Stop
else if CP1 points aligned for the siding then
show Take Siding
else if Main line beyond the turnout is occupied then
show Approach
else
show Clear
\end{verbatim}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Stop-Logic-Config1.png}
\caption{Configuring the logic element for CP1ME Stop aspect, part 1}
\label{fig:CP1ME-Stop-Logic-Config1}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Stop-Logic-Config2.png}
\caption{Configuring the logic element for CP1ME Stop aspect, part 2}
\label{fig:CP1ME-Stop-Logic-Config2}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Stop-Logic-Config3.png}
\caption{Configuring the logic element for CP1ME Stop aspect, part 3}
\label{fig:CP1ME-Stop-Logic-Config3}
\end{centering}\end{figure}
First we configure the logic element for the Stop aspect (the most restrictive
aspect) of signal CP1ME, as shown in Figures
\ref{fig:CP1ME-Stop-Logic-Config1}, \ref{fig:CP1ME-Stop-Logic-Config2}, and
\ref{fig:CP1ME-Stop-Logic-Config3}.
\clearpage
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-TakeSiding-Logic-Config1.png}
\caption{Configuring the logic element for CP1ME Take Siding aspect, part 1}
\label{fig:CP1ME-TakeSiding-Logic-Config1}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-TakeSiding-Logic-Config2.png}
\caption{Configuring the logic element for CP1ME Take Siding aspect, part 2}
\label{fig:CP1ME-TakeSiding-Logic-Config2}
\end{centering}\end{figure}
Next we configure the logic element for the Take Siding aspect (the next
restrictive aspect) of signal CP1ME, as shown in Figures
\ref{fig:CP1ME-TakeSiding-Logic-Config1} and
\ref{fig:CP1ME-TakeSiding-Logic-Config2}.
\clearpage
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Approach-Logic-Config1.png}
\caption{Configuring the logic element for CP1ME Approach aspect, part 1}
\label{fig:CP1ME-Approach-Logic-Config1}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Approach-Logic-Config2.png}
\caption{Configuring the logic element for CP1ME Approach aspect, part 2}
\label{fig:CP1ME-Approach-Logic-Config2}
\end{centering}\end{figure}
Next we configure the logic element for the Approach aspect (the next
restrictive aspect) of signal CP1ME, as shown in Figures
\ref{fig:CP1ME-Approach-Logic-Config1} and
\ref{fig:CP1ME-Approach-Logic-Config2}. We have not set up the events for the
variable yet, since these events will come from the other ESP32-PWMHalfSiding
board's second occupancy detector, which is for the main line between the
sidings.
\clearpage
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Clear-Logic-Config1.png}
\caption{Configuring the logic element for CP1ME Clear aspect, part 1}
\label{fig:CP1ME-Clear-Logic-Config1}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{CP1ME-Clear-Logic-Config2.png}
\caption{Configuring the logic element for CP1ME Clear aspect, part 2}
\label{fig:CP1ME-Clear-Logic-Config2}
\end{centering}\end{figure}
Lastly we configure the logic element for the Clear aspect (the least
restrictive aspect) of signal CP1ME, as shown in Figures
\ref{fig:CP1ME-Clear-Logic-Config1} and
\ref{fig:CP1ME-Clear-Logic-Config2}. This is an unconditional logic and is the
last in this chain.
\clearpage
\subsection{Implementing Automatic Block Signals}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ABSTrack_Annotated.png}
\caption{A Bi-directional track with ABS}
\label{fig:ABSTrack}
\end{centering}\end{figure}
\begin{figure}[hbpt]\begin{centering}%
\includegraphics[width=5in]{ABSTrack_Wiring.png}
\caption{Wiring two Bi-directional ABS blocks}
\label{fig:ABSTrack_Wiring}
\end{centering}\end{figure}
A stretch of Bi-directional track with ABS is shown in
Figure~\ref{fig:ABSTrack} and Figure~\ref{fig:ABSTrack_Wiring} shows how two
of the blocks would be wired to a ESP32 HalfSiding board. Additional boards
would be used for additional pairs of blocks.
\clearpage
\subsection{Crossing with Interchange}
| medium | 0.031085 | 357 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.
// Coding Conventions for this file:
//
// Structs/Enums/Unions
// * Struct, Enum, and Union names begin with a "T",
// and use a capital letter for each new word, with no underscores.
// * All fields should be declared as either optional or required.
//
// Functions
// * Function names start with a capital letter and have a capital letter for
// each new word, with no underscores.
// * Each function should take exactly one parameter, named TFunctionNameReq,
// and should return either void or TFunctionNameResp. This convention allows
// incremental updates.
//
// Services
// * Service names begin with the letter "T", use a capital letter for each
// new word (with no underscores), and end with the word "Service".
namespace java org.apache.hive.service.cli.thrift
namespace cpp apache.hive.service.cli.thrift
// List of protocol versions. A new token should be
// added to the end of this list every time a change is made.
enum TProtocolVersion {
HIVE_CLI_SERVICE_PROTOCOL_V1,
// V2 adds support for asynchronous execution
HIVE_CLI_SERVICE_PROTOCOL_V2
// V3 add varchar type, primitive type qualifiers
HIVE_CLI_SERVICE_PROTOCOL_V3
// V4 add decimal precision/scale, char type
HIVE_CLI_SERVICE_PROTOCOL_V4
// V5 adds error details when GetOperationStatus returns in error state
HIVE_CLI_SERVICE_PROTOCOL_V5
// V6 uses binary type for binary payload (was string) and uses columnar result set
HIVE_CLI_SERVICE_PROTOCOL_V6
// V7 adds support for delegation token based connection
HIVE_CLI_SERVICE_PROTOCOL_V7
// V8 adds support for interval types
HIVE_CLI_SERVICE_PROTOCOL_V8
}
enum TTypeId {
BOOLEAN_TYPE,
TINYINT_TYPE,
SMALLINT_TYPE,
INT_TYPE,
BIGINT_TYPE,
FLOAT_TYPE,
DOUBLE_TYPE,
STRING_TYPE,
TIMESTAMP_TYPE,
BINARY_TYPE,
ARRAY_TYPE,
MAP_TYPE,
STRUCT_TYPE,
UNION_TYPE,
USER_DEFINED_TYPE,
DECIMAL_TYPE,
NULL_TYPE,
DATE_TYPE,
VARCHAR_TYPE,
CHAR_TYPE,
INTERVAL_YEAR_MONTH_TYPE,
INTERVAL_DAY_TIME_TYPE
}
const set<TTypeId> PRIMITIVE_TYPES = [
TTypeId.BOOLEAN_TYPE,
TTypeId.TINYINT_TYPE,
TTypeId.SMALLINT_TYPE,
TTypeId.INT_TYPE,
TTypeId.BIGINT_TYPE,
TTypeId.FLOAT_TYPE,
TTypeId.DOUBLE_TYPE,
TTypeId.STRING_TYPE,
TTypeId.TIMESTAMP_TYPE,
TTypeId.BINARY_TYPE,
TTypeId.DECIMAL_TYPE,
TTypeId.NULL_TYPE,
TTypeId.DATE_TYPE,
TTypeId.VARCHAR_TYPE,
TTypeId.CHAR_TYPE,
TTypeId.INTERVAL_YEAR_MONTH_TYPE,
TTypeId.INTERVAL_DAY_TIME_TYPE
]
const set<TTypeId> COMPLEX_TYPES = [
TTypeId.ARRAY_TYPE
TTypeId.MAP_TYPE
TTypeId.STRUCT_TYPE
TTypeId.UNION_TYPE
TTypeId.USER_DEFINED_TYPE
]
const set<TTypeId> COLLECTION_TYPES = [
TTypeId.ARRAY_TYPE
TTypeId.MAP_TYPE
]
const map<TTypeId,string> TYPE_NAMES = {
TTypeId.BOOLEAN_TYPE: "BOOLEAN",
TTypeId.TINYINT_TYPE: "TINYINT",
TTypeId.SMALLINT_TYPE: "SMALLINT",
TTypeId.INT_TYPE: "INT",
TTypeId.BIGINT_TYPE: "BIGINT",
TTypeId.FLOAT_TYPE: "FLOAT",
TTypeId.DOUBLE_TYPE: "DOUBLE",
TTypeId.STRING_TYPE: "STRING",
TTypeId.TIMESTAMP_TYPE: "TIMESTAMP",
TTypeId.BINARY_TYPE: "BINARY",
TTypeId.ARRAY_TYPE: "ARRAY",
TTypeId.MAP_TYPE: "MAP",
TTypeId.STRUCT_TYPE: "STRUCT",
TTypeId.UNION_TYPE: "UNIONTYPE",
TTypeId.DECIMAL_TYPE: "DECIMAL",
TTypeId.NULL_TYPE: "NULL"
TTypeId.DATE_TYPE: "DATE"
TTypeId.VARCHAR_TYPE: "VARCHAR"
TTypeId.CHAR_TYPE: "CHAR"
TTypeId.INTERVAL_YEAR_MONTH_TYPE: "INTERVAL_YEAR_MONTH"
TTypeId.INTERVAL_DAY_TIME_TYPE: "INTERVAL_DAY_TIME"
}
// Thrift does not support recursively defined types or forward declarations,
// which makes it difficult to represent Hive's nested types.
// To get around these limitations TTypeDesc employs a type list that maps
// integer "pointers" to TTypeEntry objects. The following examples show
// how different types are represented using this scheme:
//
// "INT":
// TTypeDesc {
// types = [
// TTypeEntry.primitive_entry {
// type = INT_TYPE
// }
// ]
// }
//
// "ARRAY<INT>":
// TTypeDesc {
// types = [
// TTypeEntry.array_entry {
// object_type_ptr = 1
// },
// TTypeEntry.primitive_entry {
// type = INT_TYPE
// }
// ]
// }
//
// "MAP<INT,STRING>":
// TTypeDesc {
// types = [
// TTypeEntry.map_entry {
// key_type_ptr = 1
// value_type_ptr = 2
// },
// TTypeEntry.primitive_entry {
// type = INT_TYPE
// },
// TTypeEntry.primitive_entry {
// type = STRING_TYPE
// }
// ]
// }
typedef i32 TTypeEntryPtr
// Valid TTypeQualifiers key names
const string CHARACTER_MAXIMUM_LENGTH = "characterMaximumLength"
// Type qualifier key name for decimal
const string PRECISION = "precision"
const string SCALE = "scale"
union TTypeQualifierValue {
1: optional i32 i32Value
2: optional string stringValue
}
// Type qualifiers for primitive type.
struct TTypeQualifiers {
1: required map <string, TTypeQualifierValue> qualifiers
}
// Type entry for a primitive type.
struct TPrimitiveTypeEntry {
// The primitive type token. This must satisfy the condition
// that type is in the PRIMITIVE_TYPES set.
1: required TTypeId type
2: optional TTypeQualifiers typeQualifiers
}
// Type entry for an ARRAY type.
struct TArrayTypeEntry {
1: required TTypeEntryPtr objectTypePtr
}
// Type entry for a MAP type.
struct TMapTypeEntry {
1: required TTypeEntryPtr keyTypePtr
2: required TTypeEntryPtr valueTypePtr
}
// Type entry for a STRUCT type.
struct TStructTypeEntry {
1: required map<string, TTypeEntryPtr> nameToTypePtr
}
// Type entry for a UNIONTYPE type.
struct TUnionTypeEntry {
1: required map<string, TTypeEntryPtr> nameToTypePtr
}
struct TUserDefinedTypeEntry {
// The fully qualified name of the class implementing this type.
1: required string typeClassName
}
// We use a union here since Thrift does not support inheritance.
union TTypeEntry {
1: TPrimitiveTypeEntry primitiveEntry
2: TArrayTypeEntry arrayEntry
3: TMapTypeEntry mapEntry
4: TStructTypeEntry structEntry
5: TUnionTypeEntry unionEntry
6: TUserDefinedTypeEntry userDefinedTypeEntry
}
// Type descriptor for columns.
struct TTypeDesc {
// The "top" type is always the first element of the list.
// If the top type is an ARRAY, MAP, STRUCT, or UNIONTYPE
// type, then subsequent elements represent nested types.
1: required list<TTypeEntry> types
}
// A result set column descriptor.
struct TColumnDesc {
// The name of the column
1: required string columnName
// The type descriptor for this column
2: required TTypeDesc typeDesc
// The ordinal position of this column in the schema
3: required i32 position
4: optional string comment
}
// Metadata used to describe the schema (column names, types, comments)
// of result sets.
struct TTableSchema {
1: required list<TColumnDesc> columns
}
// A Boolean column value.
struct TBoolValue {
// NULL if value is unset.
1: optional bool value
}
// A Byte column value.
struct TByteValue {
// NULL if value is unset.
1: optional byte value
}
// A signed, 16 bit column value.
struct TI16Value {
// NULL if value is unset
1: optional i16 value
}
// A signed, 32 bit column value
struct TI32Value {
// NULL if value is unset
1: optional i32 value
}
// A signed 64 bit column value
struct TI64Value {
// NULL if value is unset
1: optional i64 value
}
// A floating point 64 bit column value
struct TDoubleValue {
// NULL if value is unset
1: optional double value
}
struct TStringValue {
// NULL if value is unset
1: optional string value
}
// A single column value in a result set.
// Note that Hive's type system is richer than Thrift's,
// so in some cases we have to map multiple Hive types
// to the same Thrift type. On the client-side this is
// disambiguated by looking at the Schema of the
// result set.
union TColumnValue {
1: TBoolValue boolVal // BOOLEAN
2: TByteValue byteVal // TINYINT
3: TI16Value i16Val // SMALLINT
4: TI32Value i32Val // INT
5: TI64Value i64Val // BIGINT, TIMESTAMP
6: TDoubleValue doubleVal // FLOAT, DOUBLE
7: TStringValue stringVal // STRING, LIST, MAP, STRUCT, UNIONTYPE, BINARY, DECIMAL, NULL, INTERVAL_YEAR_MONTH, INTERVAL_DAY_TIME
}
// Represents a row in a rowset.
struct TRow {
1: required list<TColumnValue> colVals
}
struct TBoolColumn {
1: required list<bool> values
2: required binary nulls
}
struct TByteColumn {
1: required list<byte> values
2: required binary nulls
}
struct TI16Column {
1: required list<i16> values
2: required binary nulls
}
struct TI32Column {
1: required list<i32> values
2: required binary nulls
}
struct TI64Column {
1: required list<i64> values
2: required binary nulls
}
struct TDoubleColumn {
1: required list<double> values
2: required binary nulls
}
struct TStringColumn {
1: required list<string> values
2: required binary nulls
}
struct TBinaryColumn {
1: required list<binary> values
2: required binary nulls
}
// Note that Hive's type system is richer than Thrift's,
// so in some cases we have to map multiple Hive types
// to the same Thrift type. On the client-side this is
// disambiguated by looking at the Schema of the
// result set.
union TColumn {
1: TBoolColumn boolVal // BOOLEAN
2: TByteColumn byteVal // TINYINT
3: TI16Column i16Val // SMALLINT
4: TI32Column i32Val // INT
5: TI64Column i64Val // BIGINT, TIMESTAMP
6: TDoubleColumn doubleVal // FLOAT, DOUBLE
7: TStringColumn stringVal // STRING, LIST, MAP, STRUCT, UNIONTYPE, DECIMAL, NULL
8: TBinaryColumn binaryVal // BINARY
}
// Represents a rowset
struct TRowSet {
// The starting row offset of this rowset.
1: required i64 startRowOffset
2: required list<TRow> rows
3: optional list<TColumn> columns
}
// The return status code contained in each response.
enum TStatusCode {
SUCCESS_STATUS,
SUCCESS_WITH_INFO_STATUS,
STILL_EXECUTING_STATUS,
ERROR_STATUS,
INVALID_HANDLE_STATUS
}
// The return status of a remote request
struct TStatus {
1: required TStatusCode statusCode
// If status is SUCCESS_WITH_INFO, info_msgs may be populated with
// additional diagnostic information.
2: optional list<string> infoMessages
// If status is ERROR, then the following fields may be set
3: optional string sqlState // as defined in the ISO/IEF CLI specification
4: optional i32 errorCode // internal error code
5: optional string errorMessage
}
// The state of an operation (i.e. a query or other
// asynchronous operation that generates a result set)
// on the server.
enum TOperationState {
// The operation has been initialized
INITIALIZED_STATE,
// The operation is running. In this state the result
// set is not available.
RUNNING_STATE,
// The operation has completed. When an operation is in
// this state its result set may be fetched.
FINISHED_STATE,
// The operation was canceled by a client
CANCELED_STATE,
// The operation was closed by a client
CLOSED_STATE,
// The operation failed due to an error
ERROR_STATE,
// The operation is in an unrecognized state
UKNOWN_STATE,
// The operation is in an pending state
PENDING_STATE,
}
// A string identifier. This is interpreted literally.
typedef string TIdentifier
// A search pattern.
//
// Valid search pattern characters:
// '_': Any single character.
// '%': Any sequence of zero or more characters.
// '\': Escape character used to include special characters,
// e.g. '_', '%', '\'. If a '\' precedes a non-special
// character it has no special meaning and is interpreted
// literally.
typedef string TPattern
// A search pattern or identifier. Used as input
// parameter for many of the catalog functions.
typedef string TPatternOrIdentifier
struct THandleIdentifier {
// 16 byte globally unique identifier
// This is the public ID of the handle and
// can be used for reporting.
1: required binary guid,
// 16 byte secret generated by the server
// and used to verify that the handle is not
// being hijacked by another user.
2: required binary secret,
}
// Client-side handle to persistent
// session information on the server-side.
struct TSessionHandle {
1: required THandleIdentifier sessionId
}
// The subtype of an OperationHandle.
enum TOperationType {
EXECUTE_STATEMENT,
GET_TYPE_INFO,
GET_CATALOGS,
GET_SCHEMAS,
GET_TABLES,
GET_TABLE_TYPES,
GET_COLUMNS,
GET_FUNCTIONS,
UNKNOWN,
}
// Client-side reference to a task running
// asynchronously on the server.
struct TOperationHandle {
1: required THandleIdentifier operationId
2: required TOperationType operationType
// If hasResultSet = TRUE, then this operation
// generates a result set that can be fetched.
// Note that the result set may be empty.
//
// If hasResultSet = FALSE, then this operation
// does not generate a result set, and calling
// GetResultSetMetadata or FetchResults against
// this OperationHandle will generate an error.
3: required bool hasResultSet
// For operations that don't generate result sets,
// modifiedRowCount is either:
//
// 1) The number of rows that were modified by
// the DML operation (e.g. number of rows inserted,
// number of rows deleted, etc).
//
// 2) 0 for operations that don't modify or add rows.
//
// 3) < 0 if the operation is capable of modifiying rows,
// but Hive is unable to determine how many rows were
// modified. For example, Hive's LOAD DATA command
// doesn't generate row count information because
// Hive doesn't inspect the data as it is loaded.
//
// modifiedRowCount is unset if the operation generates
// a result set.
4: optional double modifiedRowCount
}
// OpenSession()
//
// Open a session (connection) on the server against
// which operations may be executed.
struct TOpenSessionReq {
// The version of the HiveServer2 protocol that the client is using.
1: required TProtocolVersion client_protocol = TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8
// Username and password for authentication.
// Depending on the authentication scheme being used,
// this information may instead be provided by a lower
// protocol layer, in which case these fields may be
// left unset.
2: optional string username
3: optional string password
// Configuration overlay which is applied when the session is
// first created.
4: optional map<string, string> configuration
}
struct TOpenSessionResp {
1: required TStatus status
// The protocol version that the server is using.
2: required TProtocolVersion serverProtocolVersion = TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V8
// Session Handle
3: optional TSessionHandle sessionHandle
// The configuration settings for this session.
4: optional map<string, string> configuration
}
// CloseSession()
//
// Closes the specified session and frees any resources
// currently allocated to that session. Any open
// operations in that session will be canceled.
struct TCloseSessionReq {
1: required TSessionHandle sessionHandle
}
struct TCloseSessionResp {
1: required TStatus status
}
enum TGetInfoType {
CLI_MAX_DRIVER_CONNECTIONS = 0,
CLI_MAX_CONCURRENT_ACTIVITIES = 1,
CLI_DATA_SOURCE_NAME = 2,
CLI_FETCH_DIRECTION = 8,
CLI_SERVER_NAME = 13,
CLI_SEARCH_PATTERN_ESCAPE = 14,
CLI_DBMS_NAME = 17,
CLI_DBMS_VER = 18,
CLI_ACCESSIBLE_TABLES = 19,
CLI_ACCESSIBLE_PROCEDURES = 20,
CLI_CURSOR_COMMIT_BEHAVIOR = 23,
CLI_DATA_SOURCE_READ_ONLY = 25,
CLI_DEFAULT_TXN_ISOLATION = 26,
CLI_IDENTIFIER_CASE = 28,
CLI_IDENTIFIER_QUOTE_CHAR = 29,
CLI_MAX_COLUMN_NAME_LEN = 30,
CLI_MAX_CURSOR_NAME_LEN = 31,
CLI_MAX_SCHEMA_NAME_LEN = 32,
CLI_MAX_CATALOG_NAME_LEN = 34,
CLI_MAX_TABLE_NAME_LEN = 35,
CLI_SCROLL_CONCURRENCY = 43,
CLI_TXN_CAPABLE = 46,
CLI_USER_NAME = 47,
CLI_TXN_ISOLATION_OPTION = 72,
CLI_INTEGRITY = 73,
CLI_GETDATA_EXTENSIONS = 81,
CLI_NULL_COLLATION = 85,
CLI_ALTER_TABLE = 86,
CLI_ORDER_BY_COLUMNS_IN_SELECT = 90,
CLI_SPECIAL_CHARACTERS = 94,
CLI_MAX_COLUMNS_IN_GROUP_BY = 97,
CLI_MAX_COLUMNS_IN_INDEX = 98,
CLI_MAX_COLUMNS_IN_ORDER_BY = 99,
CLI_MAX_COLUMNS_IN_SELECT = 100,
CLI_MAX_COLUMNS_IN_TABLE = 101,
CLI_MAX_INDEX_SIZE = 102,
CLI_MAX_ROW_SIZE = 104,
CLI_MAX_STATEMENT_LEN = 105,
CLI_MAX_TABLES_IN_SELECT = 106,
CLI_MAX_USER_NAME_LEN = 107,
CLI_OJ_CAPABILITIES = 115,
CLI_XOPEN_CLI_YEAR = 10000,
CLI_CURSOR_SENSITIVITY = 10001,
CLI_DESCRIBE_PARAMETER = 10002,
CLI_CATALOG_NAME = 10003,
CLI_COLLATION_SEQ = 10004,
CLI_MAX_IDENTIFIER_LEN = 10005,
}
union TGetInfoValue {
1: string stringValue
2: i16 smallIntValue
3: i32 integerBitmask
4: i32 integerFlag
5: i32 binaryValue
6: i64 lenValue
}
// GetInfo()
//
// This function is based on ODBC's CLIGetInfo() function.
// The function returns general information about the data source
// using the same keys as ODBC.
struct TGetInfoReq {
// The session to run this request against
1: required TSessionHandle sessionHandle
2: required TGetInfoType infoType
}
struct TGetInfoResp {
1: required TStatus status
2: required TGetInfoValue infoValue
}
// ExecuteStatement()
//
// Execute a statement.
// The returned OperationHandle can be used to check on the
// status of the statement, and to fetch results once the
// statement has finished executing.
struct TExecuteStatementReq {
// The session to execute the statement against
1: required TSessionHandle sessionHandle
// The statement to be executed (DML, DDL, SET, etc)
2: required string statement
// Configuration properties that are overlayed on top of the
// the existing session configuration before this statement
// is executed. These properties apply to this statement
// only and will not affect the subsequent state of the Session.
3: optional map<string, string> confOverlay
// Execute asynchronously when runAsync is true
4: optional bool runAsync = false
}
struct TExecuteStatementResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetTypeInfo()
//
// Get information about types supported by the HiveServer instance.
// The information is returned as a result set which can be fetched
// using the OperationHandle provided in the response.
//
// Refer to the documentation for ODBC's CLIGetTypeInfo function for
// the format of the result set.
struct TGetTypeInfoReq {
// The session to run this request against.
1: required TSessionHandle sessionHandle
}
struct TGetTypeInfoResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetCatalogs()
//
// Returns the list of catalogs (databases)
// Results are ordered by TABLE_CATALOG
//
// Resultset columns :
// col1
// name: TABLE_CAT
// type: STRING
// desc: Catalog name. NULL if not applicable.
//
struct TGetCatalogsReq {
// Session to run this request against
1: required TSessionHandle sessionHandle
}
struct TGetCatalogsResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetSchemas()
//
// Retrieves the schema names available in this database.
// The results are ordered by TABLE_CATALOG and TABLE_SCHEM.
// col1
// name: TABLE_SCHEM
// type: STRING
// desc: schema name
// col2
// name: TABLE_CATALOG
// type: STRING
// desc: catalog name
struct TGetSchemasReq {
// Session to run this request against
1: required TSessionHandle sessionHandle
// Name of the catalog. Must not contain a search pattern.
2: optional TIdentifier catalogName
// schema name or pattern
3: optional TPatternOrIdentifier schemaName
}
struct TGetSchemasResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetTables()
//
// Returns a list of tables with catalog, schema, and table
// type information. The information is returned as a result
// set which can be fetched using the OperationHandle
// provided in the response.
// Results are ordered by TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, and TABLE_NAME
//
// Result Set Columns:
//
// col1
// name: TABLE_CAT
// type: STRING
// desc: Catalog name. NULL if not applicable.
//
// col2
// name: TABLE_SCHEM
// type: STRING
// desc: Schema name.
//
// col3
// name: TABLE_NAME
// type: STRING
// desc: Table name.
//
// col4
// name: TABLE_TYPE
// type: STRING
// desc: The table type, e.g. "TABLE", "VIEW", etc.
//
// col5
// name: REMARKS
// type: STRING
// desc: Comments about the table
//
struct TGetTablesReq {
// Session to run this request against
1: required TSessionHandle sessionHandle
// Name of the catalog or a search pattern.
2: optional TPatternOrIdentifier catalogName
// Name of the schema or a search pattern.
3: optional TPatternOrIdentifier schemaName
// Name of the table or a search pattern.
4: optional TPatternOrIdentifier tableName
// List of table types to match
// e.g. "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
// "LOCAL TEMPORARY", "ALIAS", "SYNONYM", etc.
5: optional list<string> tableTypes
}
struct TGetTablesResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetTableTypes()
//
// Returns the table types available in this database.
// The results are ordered by table type.
//
// col1
// name: TABLE_TYPE
// type: STRING
// desc: Table type name.
struct TGetTableTypesReq {
// Session to run this request against
1: required TSessionHandle sessionHandle
}
struct TGetTableTypesResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetColumns()
//
// Returns a list of columns in the specified tables.
// The information is returned as a result set which can be fetched
// using the OperationHandle provided in the response.
// Results are ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME,
// and ORDINAL_POSITION.
//
// Result Set Columns are the same as those for the ODBC CLIColumns
// function.
//
struct TGetColumnsReq {
// Session to run this request against
1: required TSessionHandle sessionHandle
// Name of the catalog. Must not contain a search pattern.
2: optional TIdentifier catalogName
// Schema name or search pattern
3: optional TPatternOrIdentifier schemaName
// Table name or search pattern
4: optional TPatternOrIdentifier tableName
// Column name or search pattern
5: optional TPatternOrIdentifier columnName
}
struct TGetColumnsResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetFunctions()
//
// Returns a list of functions supported by the data source. The
// behavior of this function matches
// java.sql.DatabaseMetaData.getFunctions() both in terms of
// inputs and outputs.
//
// Result Set Columns:
//
// col1
// name: FUNCTION_CAT
// type: STRING
// desc: Function catalog (may be null)
//
// col2
// name: FUNCTION_SCHEM
// type: STRING
// desc: Function schema (may be null)
//
// col3
// name: FUNCTION_NAME
// type: STRING
// desc: Function name. This is the name used to invoke the function.
//
// col4
// name: REMARKS
// type: STRING
// desc: Explanatory comment on the function.
//
// col5
// name: FUNCTION_TYPE
// type: SMALLINT
// desc: Kind of function. One of:
// * functionResultUnknown - Cannot determine if a return value or a table
// will be returned.
// * functionNoTable - Does not a return a table.
// * functionReturnsTable - Returns a table.
//
// col6
// name: SPECIFIC_NAME
// type: STRING
// desc: The name which uniquely identifies this function within its schema.
// In this case this is the fully qualified class name of the class
// that implements this function.
//
struct TGetFunctionsReq {
// Session to run this request against
1: required TSessionHandle sessionHandle
// A catalog name; must match the catalog name as it is stored in the
// database; "" retrieves those without a catalog; null means
// that the catalog name should not be used to narrow the search.
2: optional TIdentifier catalogName
// A schema name pattern; must match the schema name as it is stored
// in the database; "" retrieves those without a schema; null means
// that the schema name should not be used to narrow the search.
3: optional TPatternOrIdentifier schemaName
// A function name pattern; must match the function name as it is stored
// in the database.
4: required TPatternOrIdentifier functionName
}
struct TGetFunctionsResp {
1: required TStatus status
2: optional TOperationHandle operationHandle
}
// GetOperationStatus()
//
// Get the status of an operation running on the server.
struct TGetOperationStatusReq {
// Session to run this request against
1: required TOperationHandle operationHandle
}
struct TGetOperationStatusResp {
1: required TStatus status
2: optional TOperationState operationState
// If operationState is ERROR_STATE, then the following fields may be set
// sqlState as defined in the ISO/IEF CLI specification
3: optional string sqlState
// Internal error code
4: optional i32 errorCode
// Error message
5: optional string errorMessage
}
// CancelOperation()
//
// Cancels processing on the specified operation handle and
// frees any resources which were allocated.
struct TCancelOperationReq {
// Operation to cancel
1: required TOperationHandle operationHandle
}
struct TCancelOperationResp {
1: required TStatus status
}
// CloseOperation()
//
// Given an operation in the FINISHED, CANCELED,
// or ERROR states, CloseOperation() will free
// all of the resources which were allocated on
// the server to service the operation.
struct TCloseOperationReq {
1: required TOperationHandle operationHandle
}
struct TCloseOperationResp {
1: required TStatus status
}
// GetResultSetMetadata()
//
// Retrieves schema information for the specified operation
struct TGetResultSetMetadataReq {
// Operation for which to fetch result set schema information
1: required TOperationHandle operationHandle
}
struct TGetResultSetMetadataResp {
1: required TStatus status
2: optional TTableSchema schema
}
enum TFetchOrientation {
// Get the next rowset. The fetch offset is ignored.
FETCH_NEXT,
// Get the previous rowset. The fetch offset is ignored.
FETCH_PRIOR,
// Return the rowset at the given fetch offset relative
// to the current rowset.
// NOT SUPPORTED
FETCH_RELATIVE,
// Return the rowset at the specified fetch offset.
// NOT SUPPORTED
FETCH_ABSOLUTE,
// Get the first rowset in the result set.
FETCH_FIRST,
// Get the last rowset in the result set.
// NOT SUPPORTED
FETCH_LAST
}
// FetchResults()
//
// Fetch rows from the server corresponding to
// a particular OperationHandle.
struct TFetchResultsReq {
// Operation from which to fetch results.
1: required TOperationHandle operationHandle
// The fetch orientation. This must be either
// FETCH_NEXT, FETCH_PRIOR or FETCH_FIRST. Defaults to FETCH_NEXT.
2: required TFetchOrientation orientation = TFetchOrientation.FETCH_NEXT
// Max number of rows that should be returned in
// the rowset.
3: required i64 maxRows
// The type of a fetch results request. 0 represents Query output. 1 represents Log
4: optional i16 fetchType = 0
}
struct TFetchResultsResp {
1: required TStatus status
// TRUE if there are more rows left to fetch from the server.
2: optional bool hasMoreRows
// The rowset. This is optional so that we have the
// option in the future of adding alternate formats for
// representing result set data, e.g. delimited strings,
// binary encoded, etc.
3: optional TRowSet results
}
// GetDelegationToken()
// Retrieve delegation token for the current user
struct TGetDelegationTokenReq {
// session handle
1: required TSessionHandle sessionHandle
// userid for the proxy user
2: required string owner
// designated renewer userid
3: required string renewer
}
struct TGetDelegationTokenResp {
// status of the request
1: required TStatus status
// delegation token string
2: optional string delegationToken
}
// CancelDelegationToken()
// Cancel the given delegation token
struct TCancelDelegationTokenReq {
// session handle
1: required TSessionHandle sessionHandle
// delegation token to cancel
2: required string delegationToken
}
struct TCancelDelegationTokenResp {
// status of the request
1: required TStatus status
}
// RenewDelegationToken()
// Renew the given delegation token
struct TRenewDelegationTokenReq {
// session handle
1: required TSessionHandle sessionHandle
// delegation token to renew
2: required string delegationToken
}
struct TRenewDelegationTokenResp {
// status of the request
1: required TStatus status
}
service TCLIService {
TOpenSessionResp OpenSession(1:TOpenSessionReq req);
TCloseSessionResp CloseSession(1:TCloseSessionReq req);
TGetInfoResp GetInfo(1:TGetInfoReq req);
TExecuteStatementResp ExecuteStatement(1:TExecuteStatementReq req);
TGetTypeInfoResp GetTypeInfo(1:TGetTypeInfoReq req);
TGetCatalogsResp GetCatalogs(1:TGetCatalogsReq req);
TGetSchemasResp GetSchemas(1:TGetSchemasReq req);
TGetTablesResp GetTables(1:TGetTablesReq req);
TGetTableTypesResp GetTableTypes(1:TGetTableTypesReq req);
TGetColumnsResp GetColumns(1:TGetColumnsReq req);
TGetFunctionsResp GetFunctions(1:TGetFunctionsReq req);
TGetOperationStatusResp GetOperationStatus(1:TGetOperationStatusReq req);
TCancelOperationResp CancelOperation(1:TCancelOperationReq req);
TCloseOperationResp CloseOperation(1:TCloseOperationReq req);
TGetResultSetMetadataResp GetResultSetMetadata(1:TGetResultSetMetadataReq req);
TFetchResultsResp FetchResults(1:TFetchResultsReq req);
TGetDelegationTokenResp GetDelegationToken(1:TGetDelegationTokenReq req);
TCancelDelegationTokenResp CancelDelegationToken(1:TCancelDelegationTokenReq req);
TRenewDelegationTokenResp RenewDelegationToken(1:TRenewDelegationTokenReq req);
}
| high | 0.764224 | 358 |
<?xml version="1.0" encoding="UTF-8"?>
<!--
_=_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_=
Repose
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Copyright (C) 2010 - 2015 Rackspace US, Inc.
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_=_
-->
<transform xmlns:ver="http://docs.openstack.org/common/api/v1.0"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<output method="text" encoding="UTF-8"/>
<template match="ver:version">
<text>{ "version" :</text>
<call-template name="doVersion"/>
<text>}</text>
</template>
<template match="ver:versions | ver:choices">
<text>{ "</text>
<value-of select="local-name()"/>
<text>" : { "values" : [ </text>
<text> </text>
<for-each select="descendant::ver:version">
<if test="position() != 1">
<text>,</text>
</if>
<call-template name="doVersion"/>
</for-each>
<text>]}}</text>
</template>
<template name="doVersion">
<variable name="attribs" select="@*"/>
<variable name="links" select="descendant::atom:link"/>
<variable name="types" select="descendant::ver:media-type"/>
<text>{</text>
<apply-templates select="$attribs"/>
<if test="$links">
<if test="$attribs">
<text>,</text>
</if>
<call-template name="doArray">
<with-param name="name">links</with-param>
<with-param name="nodes" select="$links"/>
</call-template>
</if>
<if test="$types">
<if test="$links | $attribs">
<text>,</text>
</if>
<call-template name="doArray">
<with-param name="name">media-types</with-param>
<with-param name="nodes" select="$types"/>
</call-template>
</if>
<text>}</text>
</template>
<template name="doArray">
<param name="name"/>
<param name="nodes"/>
<call-template name="json-string">
<with-param name="in" select="$name"/>
</call-template>
<text> :[</text>
<for-each select="$nodes">
<if test="position() != 1">
<text>,</text>
</if>
<text>{</text>
<apply-templates select="./@*"/>
<text>}</text>
</for-each>
<text>]</text>
</template>
<template match="@*">
<if test="position() != 1">
<text>,</text>
</if>
<choose>
<when test="name()='status'">
<call-template name="do-status-attribute"/>
</when>
<otherwise>
<call-template name="do-attribute"/>
</otherwise>
</choose>
</template>
<template name="do-status-attribute">
<param name="content" select="."/>
<call-template name="json-string">
<with-param name="in" select="name()"/>
</call-template>
<text> : </text>
<call-template name="json-string">
<with-param name="in">
<choose>
<when test="$content='DEPRECATED'">deprecated</when>
<when test="$content='ALPHA'">alpha</when>
<when test="$content='BETA'">beta</when>
<when test="$content='CURRENT'">stable</when>
<otherwise><value-of select="$content"/></otherwise>
</choose>
</with-param>
</call-template>
</template>
<template name="do-attribute">
<call-template name="json-string">
<with-param name="in" select="name()"/>
</call-template>
<text> : </text>
<call-template name="json-string">
<with-param name="in" select="."/>
</call-template>
</template>
<template name="json-string">
<param name="in"/>
<variable name="no-backslash">
<call-template name="escape-out">
<with-param name="in" select="$in"/>
<with-param name="char" select="'\'"/>
</call-template>
</variable>
<variable name="no-quote">
<call-template name="escape-out">
<with-param name="in" select="$no-backslash"/>
<with-param name="char" select="'"'"/>
</call-template>
</variable>
<value-of select="concat('"',$no-quote,'"')"/>
</template>
<template name="escape-out">
<param name="in"/>
<param name="char"/>
<variable name="before" select="substring-before($in, $char)"/>
<variable name="after" select="substring-after($in, $char)"/>
<choose>
<when test="string-length($before) > 0 or string-length($after) > 0">
<value-of select="concat($before,'\',$char)"/>
<call-template name="escape-out">
<with-param name="in" select="$after"/>
<with-param name="char" select="$char"/>
</call-template>
</when>
<otherwise>
<value-of select="$in"/>
</otherwise>
</choose>
</template>
</transform>
| high | 0.478866 | 359 |
_ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
rewire = require 'rewire'
FilterRouter = rewire '../index.coffee'
describe 'FilterRouter', ->
beforeEach ->
@router = new FilterRouter params: new Backbone.Model
afterEach ->
benv.teardown()
describe '#navigate', ->
it 'reflects the filter params as query params in the url', ->
@router.navigate = sinon.stub()
@router.params.set { foo: 'bar' }
@router.navigate.args[0][0].should.containEql '/artworks?foo=bar'
it 'does not include page in the url params', ->
@router.navigate = sinon.stub()
@router.params.set { page: '10', foo: 'bar' }
@router.navigate.args[0][0].should.containEql '/artworks?foo=bar'
it 'does not route if no params in the url', ->
@router.navigate = sinon.stub()
@router.params.set { page: '10' }
@router.navigate.callCount.should.equal 0
describe '#artworks', ->
it 'sets the filter params', ->
FilterRouter.__set__ 'location', search: "?foo=bar"
@router.artworks()
@router.params.get('foo').should.equal 'bar'
| high | 0.552329 | 360 |
%%
%% Copyright 2013 Joaquim Rocha
%%
%% 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.
%%
-module(kill_bill_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/0]).
start_link() ->
supervisor:start_link(?MODULE, []).
init([]) ->
KB_RESOURCE = {kb_resource_sup, {kb_resource_sup, start_link, []}, permanent, infinity, supervisor, [kb_resource_sup]},
KB_APP = {kill_bill,{kill_bill, start_link, []}, permanent, 2000, worker, [kill_bill]},
{ok, {{one_for_one, 5, 60}, [KB_APP, KB_RESOURCE]}}.
| medium | 0.49978 | 361 |
{
"id": "fe4d3c9e-dda1-401d-aaad-3653af7c7408",
"modelName": "GMSprite",
"mvc": "1.12",
"name": "spr_ceiling_tileset",
"For3D": false,
"HTile": false,
"VTile": false,
"bbox_bottom": 191,
"bbox_left": 0,
"bbox_right": 255,
"bbox_top": 0,
"bboxmode": 0,
"colkind": 1,
"coltolerance": 0,
"edgeFiltering": false,
"frames": [
{
"id": "3911906c-675c-4d0f-9945-04ea7f76d603",
"modelName": "GMSpriteFrame",
"mvc": "1.0",
"SpriteId": "fe4d3c9e-dda1-401d-aaad-3653af7c7408",
"compositeImage": {
"id": "834df998-357b-4ba3-a842-f5add7fb05d4",
"modelName": "GMSpriteImage",
"mvc": "1.0",
"FrameId": "3911906c-675c-4d0f-9945-04ea7f76d603",
"LayerId": "00000000-0000-0000-0000-000000000000"
},
"images": [
{
"id": "7149c404-fd51-4888-b1a1-213687a10b4e",
"modelName": "GMSpriteImage",
"mvc": "1.0",
"FrameId": "3911906c-675c-4d0f-9945-04ea7f76d603",
"LayerId": "ea7c94e1-ef3a-4b8e-b5af-39b602021bd0"
}
]
}
],
"gridX": 0,
"gridY": 0,
"height": 192,
"layers": [
{
"id": "ea7c94e1-ef3a-4b8e-b5af-39b602021bd0",
"modelName": "GMImageLayer",
"mvc": "1.0",
"SpriteId": "fe4d3c9e-dda1-401d-aaad-3653af7c7408",
"blendMode": 0,
"isLocked": false,
"name": "default",
"opacity": 100,
"visible": true
}
],
"origin": 0,
"originLocked": false,
"playbackSpeed": 15,
"playbackSpeedType": 0,
"premultiplyAlpha": false,
"sepmasks": false,
"swatchColours": null,
"swfPrecision": 2.525,
"textureGroupId": "1225f6b0-ac20-43bd-a82e-be73fa0b6f4f",
"type": 0,
"width": 256,
"xorig": 0,
"yorig": 0
} | high | 0.550534 | 362 |
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "gamma.h"
#include <stdbool.h>
#include <string.h>
int main() {
/*
scenario: test_random_actions
uuid: 865420701
*/
/*
random actions, total chaos
*/
gamma_t* board = gamma_new(3, 3, 5, 3);
assert( board != NULL );
assert( gamma_move(board, 1, 1, 1) == 1 );
assert( gamma_move(board, 2, 1, 2) == 1 );
assert( gamma_move(board, 3, 2, 2) == 1 );
assert( gamma_move(board, 3, 2, 2) == 0 );
assert( gamma_move(board, 4, 2, 2) == 0 );
assert( gamma_move(board, 4, 2, 0) == 1 );
assert( gamma_move(board, 5, 2, 0) == 0 );
assert( gamma_move(board, 5, 0, 2) == 1 );
char* board318032839 = gamma_board(board);
assert( board318032839 != NULL );
assert( strcmp(board318032839,
"523\n"
".1.\n"
"..4\n") == 0);
free(board318032839);
board318032839 = NULL;
assert( gamma_move(board, 1, 1, 0) == 1 );
assert( gamma_move(board, 1, 1, 2) == 0 );
assert( gamma_golden_move(board, 1, 0, 2) == 1 );
assert( gamma_move(board, 3, 1, 2) == 0 );
assert( gamma_move(board, 3, 2, 2) == 0 );
assert( gamma_move(board, 5, 2, 0) == 0 );
assert( gamma_move(board, 5, 0, 2) == 0 );
assert( gamma_move(board, 1, 2, 0) == 0 );
assert( gamma_move(board, 1, 2, 2) == 0 );
assert( gamma_move(board, 2, 0, 1) == 1 );
assert( gamma_move(board, 2, 1, 2) == 0 );
assert( gamma_move(board, 3, 0, 0) == 1 );
assert( gamma_move(board, 4, 1, 2) == 0 );
assert( gamma_move(board, 5, 1, 2) == 0 );
assert( gamma_move(board, 5, 1, 0) == 0 );
assert( gamma_move(board, 1, 1, 2) == 0 );
char* board815975023 = gamma_board(board);
assert( board815975023 != NULL );
assert( strcmp(board815975023,
"123\n"
"21.\n"
"314\n") == 0);
free(board815975023);
board815975023 = NULL;
assert( gamma_move(board, 2, 1, 2) == 0 );
assert( gamma_move(board, 3, 1, 2) == 0 );
assert( gamma_golden_possible(board, 3) == 1 );
gamma_delete(board);
return 0;
}
| high | 0.77026 | 363 |
#!/bin/bash
git add .
git commit -m 'init'
git push
| low | 0.318341 | 364 |
(RSTOBJ::EAT-TYPED-RECORD)
(RSTOBJ::EAT-TYPED-RECORDS)
(RSTOBJ::TR-ALIST)
(RSTOBJ::FIX-ALIST)
(RSTOBJ::MAKE-$C-FIELDS)
(RSTOBJ::DESTRUCTURE-DEFSTOBJ-FIELD-TEMPLATE)
(RSTOBJ::MAKE-FTA)
(RSTOBJ::MAKE-FTAS)
(RSTOBJ::ADDITIONAL-EXEC-DEFS)
(RSTOBJ::CREATOR-LOGIC-UPDATES)
(RSTOBJ::SCALAR-FIXING-FUNCTION-THMS)
(RSTOBJ::SCALAR-FIXING-FUNCTION-THM-NAMES)
(RSTOBJ::COLLECT-TYPED-REC-THEOREMS)
(RSTOBJ::LOGIC-FIELD-FUNCTIONS-ONE)
(RSTOBJ::LOGIC-FIELD-FUNCTIONS)
(RSTOBJ::MAKE-FIELDMAP-ENTRIES)
(RSTOBJ::MAKE-TR-GET-ENTRIES)
(RSTOBJ::MAKE-TR-SET-ENTRIES)
(RSTOBJ::MAKE-TR-FIX-ENTRIES)
(RSTOBJ::MAKE-TR-DEFAULT-ENTRIES)
(RSTOBJ::MAKE-TR-ELEM-P-ENTRIES)
(RSTOBJ::MAKE-SCALAR-FIX-ENTRIES)
(RSTOBJ::MAKE-SCALAR-ELEM-P-ENTRIES)
(RSTOBJ::MAKE-FIELD-CORR-OF-TR-KEY-CONCLS)
(RSTOBJ::ARRAY-TYPES-PRESERVED-THMS)
(RSTOBJ::ABSSTOBJ-EXPORTS-ONE)
(RSTOBJ::ABSSTOBJ-EXPORTS)
(RSTOBJ::DESTRUCTURE-DEFSTOBJ-TEMPLATE)
(RSTOBJ::MAKE-VAL-FIXING-FN)
(RSTOBJ::TOP-LEVEL-GETTER-FNS)
(RSTOBJ::TOP-LEVEL-SETTER-FNS)
(RSTOBJ::GUARDS-FOR-TOP-LEVEL-ACC/UPD)
(RSTOBJ::MBE-ACCESSOR/UPDATER-FUNCTIONS-AUX)
(RSTOBJ::MBE-ACCESSOR/UPDATER-FUNCTIONS)
(RSTOBJ::MAKE-ARRAY-FIELDS-KWD-LIST)
(RSTOBJ::DEFRSTOBJ-FN)
(RSTOBJ::UBP-LISTP)
(RSTOBJ::UBP-FIX)
(RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P)
(RSTOBJ::ELEM-P-OF-DEFAULT-FOR-UBP8-TR-P)
(RSTOBJ::ELEM-P-OF-ELEM-FIX-FOR-UBP8-TR-P
(48 48 (:TYPE-PRESCRIPTION RSTOBJ::UBP-FIX))
(8 8 (:REWRITE DEFAULT-<-2))
(8 8 (:REWRITE DEFAULT-<-1)))
(RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-UBP8-TR-P (4 4 (:REWRITE DEFAULT-<-2))
(4 4 (:REWRITE DEFAULT-<-1)))
(RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-UBP8-TR-P
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 2))
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 1))
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 2))
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 1))
(1 1 (:REWRITE CONSP-BY-LEN)))
(RSTOBJ::ELEM-LIST-P-OF-CONS-FOR-UBP8-TR-P
(10 10 (:REWRITE DEFAULT-<-2))
(10 10 (:REWRITE DEFAULT-<-1))
(3 3 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE DEFAULT-CAR))
(2 2
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 2))
(2 2
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 1))
(2 2
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 2))
(2 2
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 1))
(2 2 (:REWRITE CONSP-BY-LEN)))
(RSTOBJ::UBP8-TR-P1)
(RSTOBJ::UBP8-TR-P)
(RSTOBJ::UBP8-TO-TR (1 1
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TO-TR)))
(RSTOBJ::UBP8-TR-BAD-PART)
(RSTOBJ::UBP8-TR-GET1)
(RSTOBJ::UBP8-TR-SET1)
(RSTOBJ::UBP8-TR-GET (22 22
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TO-TR)))
(RSTOBJ::UBP8-TR-SET)
(RSTOBJ::UBP8-TR-BADGUY (4 4
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TO-TR)))
(RSTOBJ::UBP8-ARRAY-TO-TR)
(RSTOBJ::UBP8-TR-TO-ARRAY
(4 1 (:DEFINITION RSTOBJ::UBP8-TR-P))
(3 1 (:DEFINITION RSTOBJ::UBP8-TR-GET1))
(2 1 (:DEFINITION RSTOBJ::UBP8-TR-P1))
(1 1
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P)))
(RSTOBJ::UBP8-TR-DELETE-INDICES)
(RSTOBJ::UBP8-ARRAY-REC-PAIR-P)
(RSTOBJ::ELEM-P-OF-UBP8-TR-GET (9 9
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TO-TR)))
(RSTOBJ::UBP8-TR-GET-OF-UBP8-TR-SET-SAME
(1 1
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TO-TR)))
(RSTOBJ::UBP8-TR-GET-OF-UBP8-TR-SET-DIFF)
(RSTOBJ::UBP8-TR-SET-OF-UBP8-TR-GET-SAME)
(RSTOBJ::UBP8-TR-SET-OF-UBP8-TR-SET-DIFF)
(RSTOBJ::UBP8-TR-SET-OF-UBP8-TR-SET-SAME)
(RSTOBJ::UBP8-TR-GET-OF-UBP8-TR-SET-STRONG)
(RSTOBJ::UBP8-TR-GET-OF-NIL)
(RSTOBJ::UBP8-TR-BAD-PART-OF-UBP8-TR-SET
(12 6 (:DEFINITION RSTOBJ::UBP8-TR-P1))
(6 6
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P)))
(RSTOBJ::UBP8-TR-BADGUY-FINDS-COUNTEREXAMPLE)
(RSTOBJ::UBP8-TR-BADGUY-UNLESS-EQUAL)
(RSTOBJ::EQUAL-OF-UBP8-TR-SET)
(RSTOBJ::UBP8-ELEM-P-OF-NTH)
(RSTOBJ::UBP8-TR-GET-OF-UBP8-ARRAY-TO-TR
(262 56
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-UBP8-TR-P))
(100 53
(:REWRITE RSTOBJ::UBP8-ELEM-P-OF-NTH))
(47 47
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-UBP8-TR-P))
(3 3
(:REWRITE RSTOBJ::ELEM-P-OF-ELEM-FIX-FOR-UBP8-TR-P)))
(RSTOBJ::LEN-OF-UBP8-TR-TO-ARRAY
(28 14 (:DEFINITION RSTOBJ::UBP8-TR-P1))
(14 14
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P)))
(RSTOBJ::ELEM-LIST-P-OF-UBP8-TR-TO-ARRAY)
(RSTOBJ::UBP8-TR-TO-ARRAY-IDEMPOTENT)
(RSTOBJ::UBP8-TR-TO-ARRAY-OF-UBP8-TR-SET)
(RSTOBJ::UBP8-TR-TO-ARRAY-OF-UBP8-ARRAY-TO-TR
(19 1
(:DEFINITION RSTOBJ::UBP8-TR-TO-ARRAY))
(17 1
(:REWRITE RSTOBJ::UBP8-TR-GET-OF-UBP8-ARRAY-TO-TR))
(17 1
(:DEFINITION RSTOBJ::UBP8-ARRAY-TO-TR))
(15 1 (:DEFINITION RSTOBJ::UBP8-TR-SET))
(12 2 (:DEFINITION RSTOBJ::UBP8-TO-TR))
(10 2
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-UBP8-TR-P))
(10 1 (:DEFINITION RSTOBJ::UBP8-TR-GET))
(8 8
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TR-P))
(8 2 (:DEFINITION RSTOBJ::UBP8-TR-P))
(6 6
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P))
(4 2 (:REWRITE RSTOBJ::UBP8-ELEM-P-OF-NTH))
(4 2 (:DEFINITION RSTOBJ::UBP8-TR-P1))
(3 1 (:DEFINITION RSTOBJ::UBP8-TR-SET1))
(3 1 (:DEFINITION RSTOBJ::UBP8-TR-GET1))
(2 2
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-UBP8-TR-P))
(2 2 (:DEFINITION ZP)))
(RSTOBJ::UBP8-TR-DELETE-INDICES-OF-NIL
(129 47
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-UBP8-TR-P))
(3 3
(:REWRITE RSTOBJ::ELEM-P-OF-ELEM-FIX-FOR-UBP8-TR-P)))
(RSTOBJ::UBP8-TR-DELETE-INDICES-IDEMPOTENT)
(RSTOBJ::UBP8-TR-DELETE-INDICES-OF-UBP8-TR-SET)
(RSTOBJ::UBP8-TR-DELETE-INDICES-OF-UBP8-ARRAY-TO-TR)
(RSTOBJ::UBP8-ARRAY-TO-TR-INVERSE)
(RSTOBJ::EQUAL-OF-UBP8-ARRAY-TO-TR
(30 2
(:DEFINITION RSTOBJ::UBP8-TR-DELETE-INDICES))
(26 2 (:DEFINITION RSTOBJ::UBP8-TR-SET))
(12 2 (:DEFINITION RSTOBJ::UBP8-TO-TR))
(8 8
(:TYPE-PRESCRIPTION RSTOBJ::UBP8-TR-P))
(8 2 (:DEFINITION RSTOBJ::UBP8-TR-P))
(6 6
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P))
(6 2
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-UBP8-TR-P))
(6 2 (:DEFINITION RSTOBJ::UBP8-TR-SET1))
(4 2 (:DEFINITION RSTOBJ::UBP8-TR-P1))
(2 2
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-UBP8-TR-P))
(2 2 (:DEFINITION ZP))
(2 2 (:DEFINITION LEN)))
(RSTOBJ::NONNEG-FIX)
(RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P)
(RSTOBJ::ELEM-P-OF-DEFAULT-FOR-NONNEG-TR-P)
(RSTOBJ::ELEM-P-OF-ELEM-FIX-FOR-NONNEG-TR-P)
(RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P
(3 1 (:REWRITE NATP-WHEN-GTE-0))
(2 2
(:REWRITE VL::NATP-WHEN-MEMBER-EQUAL-OF-NAT-LISTP))
(2 2 (:REWRITE DEFAULT-<-2))
(2 2 (:REWRITE DEFAULT-<-1))
(1 1 (:REWRITE NATP-WHEN-INTEGERP)))
(RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-NONNEG-TR-P
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 2))
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 1))
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 2))
(1 1
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 1))
(1 1 (:REWRITE CONSP-BY-LEN)))
(RSTOBJ::ELEM-LIST-P-OF-CONS-FOR-NONNEG-TR-P
(70 2
(:REWRITE VL::NATP-OF-CAR-WHEN-NAT-LISTP))
(58 2
(:REWRITE VL::NAT-LISTP-WHEN-NO-NILS-IN-VL-MAYBE-NAT-LISTP))
(38 2 (:DEFINITION MEMBER-EQUAL))
(16 4 (:REWRITE MEMBER-WHEN-ATOM))
(15 5 (:REWRITE NATP-WHEN-GTE-0))
(10 10 (:TYPE-PRESCRIPTION MEMBER-EQUAL))
(10 10
(:REWRITE VL::NATP-WHEN-MEMBER-EQUAL-OF-NAT-LISTP))
(5 5 (:REWRITE NATP-WHEN-INTEGERP))
(5 5 (:REWRITE DEFAULT-CDR))
(5 5 (:REWRITE DEFAULT-CAR))
(5 5 (:REWRITE DEFAULT-<-2))
(5 5 (:REWRITE DEFAULT-<-1))
(4 4 (:TYPE-PRESCRIPTION VL::NAT-LISTP))
(4 4 (:REWRITE SUBSETP-MEMBER . 4))
(4 4 (:REWRITE SUBSETP-MEMBER . 3))
(4 4 (:REWRITE SUBSETP-MEMBER . 2))
(4 4 (:REWRITE SUBSETP-MEMBER . 1))
(4 4
(:REWRITE VL::NAT-LISTP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE INTERSECTP-MEMBER . 3))
(4 4 (:REWRITE INTERSECTP-MEMBER . 2))
(4 4
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 2))
(4 4
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-PREFIXMAP-P
. 1))
(4 4
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 2))
(4 4
(:REWRITE VL::CONSP-WHEN-MEMBER-EQUAL-OF-VL-NAMEDB-NAMESET-P
. 1))
(4 4 (:REWRITE CONSP-BY-LEN))
(2 2
(:REWRITE VL::NAT-LISTP-WHEN-NOT-CONSP))
(2 2 (:REWRITE CONSP-OF-CDR-BY-LEN)))
(RSTOBJ::NONNEG-TR-P1)
(RSTOBJ::NONNEG-TR-P)
(RSTOBJ::NONNEG-TO-TR (1 1
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TO-TR)))
(RSTOBJ::NONNEG-TR-BAD-PART)
(RSTOBJ::NONNEG-TR-GET1)
(RSTOBJ::NONNEG-TR-SET1)
(RSTOBJ::NONNEG-TR-GET (22 22
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TO-TR)))
(RSTOBJ::NONNEG-TR-SET)
(RSTOBJ::NONNEG-TR-BADGUY (4 4
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TO-TR)))
(RSTOBJ::NONNEG-ARRAY-TO-TR)
(RSTOBJ::NONNEG-TR-TO-ARRAY (4 1 (:DEFINITION RSTOBJ::NONNEG-TR-P))
(3 1 (:DEFINITION RSTOBJ::NONNEG-TR-GET1))
(2 1 (:DEFINITION RSTOBJ::NONNEG-TR-P1)))
(RSTOBJ::NONNEG-TR-DELETE-INDICES)
(RSTOBJ::NONNEG-ARRAY-REC-PAIR-P)
(RSTOBJ::ELEM-P-OF-NONNEG-TR-GET
(9 9
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TO-TR)))
(RSTOBJ::NONNEG-TR-GET-OF-NONNEG-TR-SET-SAME
(1 1
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TO-TR)))
(RSTOBJ::NONNEG-TR-GET-OF-NONNEG-TR-SET-DIFF)
(RSTOBJ::NONNEG-TR-SET-OF-NONNEG-TR-GET-SAME)
(RSTOBJ::NONNEG-TR-SET-OF-NONNEG-TR-SET-DIFF)
(RSTOBJ::NONNEG-TR-SET-OF-NONNEG-TR-SET-SAME)
(RSTOBJ::NONNEG-TR-GET-OF-NONNEG-TR-SET-STRONG)
(RSTOBJ::NONNEG-TR-GET-OF-NIL)
(RSTOBJ::NONNEG-TR-BAD-PART-OF-NONNEG-TR-SET
(12 6 (:DEFINITION RSTOBJ::NONNEG-TR-P1))
(6 6 (:DEFINITION NATP)))
(RSTOBJ::NONNEG-TR-BADGUY-FINDS-COUNTEREXAMPLE)
(RSTOBJ::NONNEG-TR-BADGUY-UNLESS-EQUAL)
(RSTOBJ::EQUAL-OF-NONNEG-TR-SET)
(RSTOBJ::NONNEG-ELEM-P-OF-NTH)
(RSTOBJ::NONNEG-TR-GET-OF-NONNEG-ARRAY-TO-TR
(262 56
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(100 53
(:REWRITE RSTOBJ::NONNEG-ELEM-P-OF-NTH))
(53 53
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(47 47
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-NONNEG-TR-P))
(3 3
(:REWRITE RSTOBJ::ELEM-P-OF-ELEM-FIX-FOR-NONNEG-TR-P)))
(RSTOBJ::LEN-OF-NONNEG-TR-TO-ARRAY (28 14 (:DEFINITION RSTOBJ::NONNEG-TR-P1))
(14 14 (:DEFINITION NATP)))
(RSTOBJ::ELEM-LIST-P-OF-NONNEG-TR-TO-ARRAY)
(RSTOBJ::NONNEG-TR-TO-ARRAY-IDEMPOTENT)
(RSTOBJ::NONNEG-TR-TO-ARRAY-OF-NONNEG-TR-SET)
(RSTOBJ::NONNEG-TR-TO-ARRAY-OF-NONNEG-ARRAY-TO-TR
(19 1
(:DEFINITION RSTOBJ::NONNEG-TR-TO-ARRAY))
(17 1
(:REWRITE RSTOBJ::NONNEG-TR-GET-OF-NONNEG-ARRAY-TO-TR))
(17 1
(:DEFINITION RSTOBJ::NONNEG-ARRAY-TO-TR))
(15 1 (:DEFINITION RSTOBJ::NONNEG-TR-SET))
(12 2 (:DEFINITION RSTOBJ::NONNEG-TO-TR))
(10 2
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(10 1 (:DEFINITION RSTOBJ::NONNEG-TR-GET))
(8 8
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TR-P))
(8 2 (:DEFINITION RSTOBJ::NONNEG-TR-P))
(4 2
(:REWRITE RSTOBJ::NONNEG-ELEM-P-OF-NTH))
(4 2 (:DEFINITION RSTOBJ::NONNEG-TR-P1))
(3 1 (:DEFINITION RSTOBJ::NONNEG-TR-SET1))
(3 1 (:DEFINITION RSTOBJ::NONNEG-TR-GET1))
(2 2
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-NONNEG-TR-P))
(2 2 (:DEFINITION ZP)))
(RSTOBJ::NONNEG-TR-DELETE-INDICES-OF-NIL)
(RSTOBJ::NONNEG-TR-DELETE-INDICES-IDEMPOTENT)
(RSTOBJ::NONNEG-TR-DELETE-INDICES-OF-NONNEG-TR-SET)
(RSTOBJ::NONNEG-TR-DELETE-INDICES-OF-NONNEG-ARRAY-TO-TR)
(RSTOBJ::NONNEG-ARRAY-TO-TR-INVERSE)
(RSTOBJ::EQUAL-OF-NONNEG-ARRAY-TO-TR
(30 2
(:DEFINITION RSTOBJ::NONNEG-TR-DELETE-INDICES))
(26 2 (:DEFINITION RSTOBJ::NONNEG-TR-SET))
(12 2 (:DEFINITION RSTOBJ::NONNEG-TO-TR))
(8 8
(:TYPE-PRESCRIPTION RSTOBJ::NONNEG-TR-P))
(8 2 (:DEFINITION RSTOBJ::NONNEG-TR-P))
(6 2
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(6 2 (:DEFINITION RSTOBJ::NONNEG-TR-SET1))
(4 4 (:DEFINITION NATP))
(4 2 (:DEFINITION RSTOBJ::NONNEG-TR-P1))
(2 2
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(2 2
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-NONNEG-TR-P))
(2 2 (:DEFINITION ZP))
(2 2 (:DEFINITION LEN)))
(RSTOBJ::PLUS-COLLECT-CONSTS)
(RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORINTFLD
(1 1 (:REWRITE IFIX-WHEN-NOT-INTEGERP)))
(RSTOBJ::RSTOBJ-FIX-ELEM-P-FORINTFLD)
(RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORNATFLD (2 2 (:REWRITE DEFAULT-<-2))
(2 2 (:REWRITE DEFAULT-<-1)))
(RSTOBJ::RSTOBJ-FIX-ELEM-P-FORNATFLD)
(RSTOBJ::EMPTY-U8ARR$C)
(RSTOBJ::STP$A)
(RSTOBJ::CREATE-ST$A)
(RSTOBJ::NATARR-LENGTH$A)
(RSTOBJ::GET-NATARR$A)
(RSTOBJ::SET-NATARR$A)
(RSTOBJ::U8ARR-LENGTH$A)
(RSTOBJ::GET-U8ARR$A)
(RSTOBJ::SET-U8ARR$A)
(RSTOBJ::GROW-U8ARR$A)
(RSTOBJ::EMPTY-U8ARR$A)
(RSTOBJ::GET-INTFLD$A)
(RSTOBJ::SET-INTFLD$A)
(RSTOBJ::GET-NATFLD$A)
(RSTOBJ::SET-NATFLD$A)
(RSTOBJ::RSTOBJ-TMP-FIELD-MAP)
(RSTOBJ::RSTOBJ-TMP-TR-GET)
(RSTOBJ::RSTOBJ-TMP-TR-SET)
(RSTOBJ::RSTOBJ-TMP-TR-FIX)
(RSTOBJ::RSTOBJ-TMP-TR-DEFAULT)
(RSTOBJ::RSTOBJ-TMP-TR-ELEM-P)
(RSTOBJ::RSTOBJ-TMP-SCALAR-FIX)
(RSTOBJ::RSTOBJ-TMP-SCALAR-ELEM-P)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-NECC (42 42 (:DEFINITION MV-NTH)))
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY
(18 18 (:REWRITE NTH-WHEN-ATOM))
(15 5
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(11 11 (:REWRITE LEN-WHEN-ATOM))
(10 10
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P)))
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE
(14 14 (:REWRITE NTH-WHEN-ATOM))
(6 6
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(6 6
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(6 6 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-UPDATE-SCALAR)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-UPDATE-ARRAY)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-GROW-ARRAY)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-EMPTY-ARRAY)
(RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-CREATE
(40 10 (:REWRITE LEN-WHEN-ATOM))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::RSTOBJ-TMP-CORR)
(RSTOBJ::FIELD-LOOKUP-IN-RSTOBJ-TMP-FIELD-MAP)
(RSTOBJ::INDEX-LOOKUP-IN-RSTOBJ-TMP-FIELD-MAP)
(RSTOBJ::NATARR$CP-OF-REPEAT)
(RSTOBJ::NATARR$CP-OF-UPDATE-NTH
(8 8
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(7 7 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::NATARR$CP-OF-RESIZE-LIST (3 3
(:REWRITE RSTOBJ::PLUS-COLLECT-CONSTS)))
(RSTOBJ::U8ARR$CP-OF-REPEAT)
(RSTOBJ::U8ARR$CP-OF-UPDATE-NTH
(8 8
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(7 7 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::U8ARR$CP-OF-RESIZE-LIST (3 3
(:REWRITE RSTOBJ::PLUS-COLLECT-CONSTS)))
(RSTOBJ::CREATE-ST{CORRESPONDENCE} (8 8 (:REWRITE NTH-WHEN-ATOM))
(4 1 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::CREATE-ST{PRESERVED})
(RSTOBJ::NATARR-LENGTH{CORRESPONDENCE})
(RSTOBJ::GET-NATARR{CORRESPONDENCE}
(16 16 (:REWRITE NTH-WHEN-ATOM))
(5 5 (:REWRITE LEN-WHEN-ATOM))
(2 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(2 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(2 1 (:DEFINITION RSTOBJ::U8ARR$CP))
(1 1
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P))
(1 1 (:DEFINITION RSTOBJ::NATARR$CP)))
(RSTOBJ::GET-NATARR{GUARD-THM})
(RSTOBJ::SET-NATARR{CORRESPONDENCE}
(36 36 (:REWRITE NTH-WHEN-ATOM))
(15 15 (:REWRITE LEN-WHEN-ATOM))
(13 8
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(13 8
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(10 10
(:REWRITE RSTOBJ::FIELD-LOOKUP-IN-RSTOBJ-TMP-FIELD-MAP))
(3 3 (:DEFINITION RSTOBJ::NATARR$CP)))
(RSTOBJ::SET-NATARR{GUARD-THM})
(RSTOBJ::SET-NATARR{PRESERVED})
(RSTOBJ::U8ARR-LENGTH{CORRESPONDENCE}
(2 2 (:REWRITE NTH-WHEN-ATOM))
(2 2 (:REWRITE LEN-WHEN-ATOM))
(2 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::GET-U8ARR{CORRESPONDENCE}
(6 6 (:REWRITE NTH-WHEN-ATOM))
(4 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(2 2 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::GET-U8ARR{GUARD-THM}
(2 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(1 1 (:REWRITE NTH-WHEN-ATOM))
(1 1 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::SET-U8ARR{CORRESPONDENCE}
(30 30 (:REWRITE NTH-WHEN-ATOM))
(13 13 (:REWRITE LEN-WHEN-ATOM))
(6 3
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(4 2 (:DEFINITION RSTOBJ::U8ARR$CP)))
(RSTOBJ::SET-U8ARR{GUARD-THM}
(2 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(1 1 (:REWRITE NTH-WHEN-ATOM))
(1 1 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::SET-U8ARR{PRESERVED})
(RSTOBJ::GROW-U8ARR{CORRESPONDENCE}
(30 30 (:REWRITE NTH-WHEN-ATOM))
(12 12 (:REWRITE LEN-WHEN-ATOM))
(5 5 (:REWRITE RESIZE-LIST-WHEN-ZP))
(4 2 (:DEFINITION RSTOBJ::U8ARR$CP))
(2 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::GROW-U8ARR{PRESERVED})
(RSTOBJ::EMPTY-U8ARR{CORRESPONDENCE}
(21 21 (:REWRITE NTH-WHEN-ATOM))
(7 7 (:REWRITE LEN-WHEN-ATOM))
(4 2 (:DEFINITION RSTOBJ::U8ARR$CP))
(2 2
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P)))
(RSTOBJ::EMPTY-U8ARR{PRESERVED})
(RSTOBJ::GET-INTFLD{CORRESPONDENCE}
(13 13 (:REWRITE NTH-WHEN-ATOM))
(2 2 (:REWRITE LEN-WHEN-ATOM))
(2 1 (:DEFINITION RSTOBJ::U8ARR$CP))
(1 1
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P))
(1 1 (:DEFINITION RSTOBJ::NATARR$CP)))
(RSTOBJ::SET-INTFLD{CORRESPONDENCE} (20 20 (:REWRITE NTH-WHEN-ATOM))
(7 7 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::SET-INTFLD{PRESERVED})
(RSTOBJ::GET-NATFLD{CORRESPONDENCE}
(15 3
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(13 13 (:REWRITE NTH-WHEN-ATOM))
(6 6
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(6 3
(:REWRITE RSTOBJ::NONNEG-ELEM-P-OF-NTH))
(3 3
(:REWRITE RSTOBJ::ELEM-LIST-P-WHEN-ATOM-FOR-NONNEG-TR-P))
(2 2 (:REWRITE LEN-WHEN-ATOM))
(2 1 (:DEFINITION RSTOBJ::U8ARR$CP))
(1 1
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P))
(1 1 (:DEFINITION RSTOBJ::NATARR$CP)))
(RSTOBJ::SET-NATFLD{CORRESPONDENCE} (20 20 (:REWRITE NTH-WHEN-ATOM))
(7 7 (:REWRITE LEN-WHEN-ATOM)))
(RSTOBJ::SET-NATFLD{PRESERVED})
(RSTOBJ::ST-VALFIX)
(RSTOBJ::READ-ST)
(RSTOBJ::WRITE-ST)
(RSTOBJ::STP-OF-WRITE-ST)
(RSTOBJ::READ-ST-WRITE-ST-INTRA-FIELD
(27 9
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(22 22
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(22 22
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(18 18
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(9 9
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORNATFLD))
(9 3
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-UBP8-TR-P))
(8 8
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE))
(6 6
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-UBP8-TR-P))
(6 6
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORINTFLD)))
(RSTOBJ::READ-ST-WRITE-ST-INTER-FIELD
(60 60
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(60 60
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(30 10
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(20 20
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(20 20
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE))
(10 10
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORNATFLD))
(10 10
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORINTFLD)))
(RSTOBJ::WRITE-ST-WRITE-ST-SHADOW-WRITES
(10 10
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(10 10
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::WRITE-ST-WRITE-ST-INTRA-FIELD-ARRANGE-WRITES
(8 8
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(8 8
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::WRITE-ST-WRITE-ST-INTER-FIELD-ARRANGE-WRITES
(48 48
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(48 48
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::@NATARR$INLINE
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::READ-ST-NATARR-WELL-FORMED-VALUE
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::!NATARR$INLINE
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::@U8ARR$INLINE
(3 3
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(3 3
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(3 1 (:REWRITE NFIX-WHEN-NATP))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE)))
(RSTOBJ::READ-ST-U8ARR-WELL-FORMED-VALUE
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-TR-KEY-ELABORATE))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY)))
(RSTOBJ::!U8ARR$INLINE
(3 3
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(3 3
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(3 1 (:REWRITE NFIX-WHEN-NATP)))
(RSTOBJ::@INTFLD$INLINE
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORINTFLD)))
(RSTOBJ::READ-ST-INTFLD-WELL-FORMED-VALUE
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(1 1
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORINTFLD)))
(RSTOBJ::!INTFLD$INLINE)
(RSTOBJ::@NATFLD$INLINE
(6 2
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(4 4
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORNATFLD)))
(RSTOBJ::READ-ST-NATFLD-WELL-FORMED-VALUE
(6 2
(:REWRITE RSTOBJ::ELEM-FIX-IDEMPOTENT-FOR-NONNEG-TR-P))
(4 4
(:TYPE-PRESCRIPTION RSTOBJ::BOOLEANP-OF-ELEM-P-FOR-NONNEG-TR-P))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SIZE-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-TMP-FIELD-CORR-OF-SCALAR-KEY))
(2 2
(:REWRITE RSTOBJ::RSTOBJ-FIX-IDEMPOTENT-FORNATFLD)))
(RSTOBJ::!NATFLD$INLINE)
| high | 0.159221 | 365 |
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
%************************************************************************
%* *
\section[OccurAnal]{Occurrence analysis pass}
%* *
%************************************************************************
The occurrence analyser re-typechecks a core expression, returning a new
core expression with (hopefully) improved usage information.
\begin{code}
{-# LANGUAGE CPP, BangPatterns #-}
module OccurAnal (
occurAnalysePgm, occurAnalyseExpr, occurAnalyseExpr_NoBinderSwap
) where
#include "HsVersions.h"
import CoreSyn
import CoreFVs
import CoreUtils ( exprIsTrivial, isDefaultAlt, isExpandableApp )
import Id
import Name( localiseName )
import BasicTypes
import Module( Module )
import Coercion
import VarSet
import VarEnv
import Var
import Demand ( argOneShots, argsOneShots )
import Maybes ( orElse )
import Digraph ( SCC(..), stronglyConnCompFromEdgedVerticesR )
import Unique
import UniqFM
import Util
import Outputable
import FastString
import Data.List
\end{code}
%************************************************************************
%* *
\subsection[OccurAnal-main]{Counting occurrences: main function}
%* *
%************************************************************************
Here's the externally-callable interface:
\begin{code}
occurAnalysePgm :: Module -- Used only in debug output
-> (Activation -> Bool)
-> [CoreRule] -> [CoreVect] -> VarSet
-> CoreProgram -> CoreProgram
occurAnalysePgm this_mod active_rule imp_rules vects vectVars binds
| isEmptyVarEnv final_usage
= binds'
| otherwise -- See Note [Glomming]
= WARN( True, hang (text "Glomming in" <+> ppr this_mod <> colon)
2 (ppr final_usage ) )
[Rec (flattenBinds binds')]
where
(final_usage, binds') = go (initOccEnv active_rule) binds
initial_uds = addIdOccs emptyDetails
(rulesFreeVars imp_rules `unionVarSet`
vectsFreeVars vects `unionVarSet`
vectVars)
-- The RULES and VECTORISE declarations keep things alive! (For VECTORISE declarations,
-- we only get them *until* the vectoriser runs. Afterwards, these dependencies are
-- reflected in 'vectors' — see Note [Vectorisation declarations and occurrences].)
-- Note [Preventing loops due to imported functions rules]
imp_rules_edges = foldr (plusVarEnv_C unionVarSet) emptyVarEnv
[ mapVarEnv (const maps_to) (exprFreeIds arg `delVarSetList` ru_bndrs imp_rule)
| imp_rule <- imp_rules
, let maps_to = exprFreeIds (ru_rhs imp_rule)
`delVarSetList` ru_bndrs imp_rule
, arg <- ru_args imp_rule ]
go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
go _ []
= (initial_uds, [])
go env (bind:binds)
= (final_usage, bind' ++ binds')
where
(bs_usage, binds') = go env binds
(final_usage, bind') = occAnalBind env env imp_rules_edges bind bs_usage
occurAnalyseExpr :: CoreExpr -> CoreExpr
-- Do occurrence analysis, and discard occurrence info returned
occurAnalyseExpr = occurAnalyseExpr' True -- do binder swap
occurAnalyseExpr_NoBinderSwap :: CoreExpr -> CoreExpr
occurAnalyseExpr_NoBinderSwap = occurAnalyseExpr' False -- do not do binder swap
occurAnalyseExpr' :: Bool -> CoreExpr -> CoreExpr
occurAnalyseExpr' enable_binder_swap expr
= snd (occAnal env expr)
where
env = (initOccEnv all_active_rules) {occ_binder_swap = enable_binder_swap}
-- To be conservative, we say that all inlines and rules are active
all_active_rules = \_ -> True
\end{code}
%************************************************************************
%* *
\subsection[OccurAnal-main]{Counting occurrences: main function}
%* *
%************************************************************************
Bindings
~~~~~~~~
\begin{code}
occAnalBind :: OccEnv -- The incoming OccEnv
-> OccEnv -- Same, but trimmed by (binderOf bind)
-> IdEnv IdSet -- Mapping from FVs of imported RULE LHSs to RHS FVs
-> CoreBind
-> UsageDetails -- Usage details of scope
-> (UsageDetails, -- Of the whole let(rec)
[CoreBind])
occAnalBind env _ imp_rules_edges (NonRec binder rhs) body_usage
| isTyVar binder -- A type let; we don't gather usage info
= (body_usage, [NonRec binder rhs])
| not (binder `usedIn` body_usage) -- It's not mentioned
= (body_usage, [])
| otherwise -- It's mentioned in the body
= (body_usage' +++ rhs_usage4, [NonRec tagged_binder rhs'])
where
(body_usage', tagged_binder) = tagBinder body_usage binder
(rhs_usage1, rhs') = occAnalNonRecRhs env tagged_binder rhs
rhs_usage2 = addIdOccs rhs_usage1 (idUnfoldingVars binder)
rhs_usage3 = addIdOccs rhs_usage2 (idRuleVars binder)
-- See Note [Rules are extra RHSs] and Note [Rule dependency info]
rhs_usage4 = maybe rhs_usage3 (addIdOccs rhs_usage3) $ lookupVarEnv imp_rules_edges binder
-- See Note [Preventing loops due to imported functions rules]
occAnalBind _ env imp_rules_edges (Rec pairs) body_usage
= foldr occAnalRec (body_usage, []) sccs
-- For a recursive group, we
-- * occ-analyse all the RHSs
-- * compute strongly-connected components
-- * feed those components to occAnalRec
where
bndr_set = mkVarSet (map fst pairs)
sccs :: [SCC (Node Details)]
sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR nodes
nodes :: [Node Details]
nodes = {-# SCC "occAnalBind.assoc" #-} map (makeNode env imp_rules_edges bndr_set) pairs
\end{code}
Note [Dead code]
~~~~~~~~~~~~~~~~
Dropping dead code for a cyclic Strongly Connected Component is done
in a very simple way:
the entire SCC is dropped if none of its binders are mentioned
in the body; otherwise the whole thing is kept.
The key observation is that dead code elimination happens after
dependency analysis: so 'occAnalBind' processes SCCs instead of the
original term's binding groups.
Thus 'occAnalBind' does indeed drop 'f' in an example like
letrec f = ...g...
g = ...(...g...)...
in
...g...
when 'g' no longer uses 'f' at all (eg 'f' does not occur in a RULE in
'g'). 'occAnalBind' first consumes 'CyclicSCC g' and then it consumes
'AcyclicSCC f', where 'body_usage' won't contain 'f'.
------------------------------------------------------------
Note [Forming Rec groups]
~~~~~~~~~~~~~~~~~~~~~~~~~
We put bindings {f = ef; g = eg } in a Rec group if "f uses g"
and "g uses f", no matter how indirectly. We do a SCC analysis
with an edge f -> g if "f uses g".
More precisely, "f uses g" iff g should be in scope wherever f is.
That is, g is free in:
a) the rhs 'ef'
b) or the RHS of a rule for f (Note [Rules are extra RHSs])
c) or the LHS or a rule for f (Note [Rule dependency info])
These conditions apply regardless of the activation of the RULE (eg it might be
inactive in this phase but become active later). Once a Rec is broken up
it can never be put back together, so we must be conservative.
The principle is that, regardless of rule firings, every variable is
always in scope.
* Note [Rules are extra RHSs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
keeps the specialised "children" alive. If the parent dies
(because it isn't referenced any more), then the children will die
too (unless they are already referenced directly).
To that end, we build a Rec group for each cyclic strongly
connected component,
*treating f's rules as extra RHSs for 'f'*.
More concretely, the SCC analysis runs on a graph with an edge
from f -> g iff g is mentioned in
(a) f's rhs
(b) f's RULES
These are rec_edges.
Under (b) we include variables free in *either* LHS *or* RHS of
the rule. The former might seems silly, but see Note [Rule
dependency info]. So in Example [eftInt], eftInt and eftIntFB
will be put in the same Rec, even though their 'main' RHSs are
both non-recursive.
* Note [Rule dependency info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The VarSet in a SpecInfo is used for dependency analysis in the
occurrence analyser. We must track free vars in *both* lhs and rhs.
Hence use of idRuleVars, rather than idRuleRhsVars in occAnalBind.
Why both? Consider
x = y
RULE f x = v+4
Then if we substitute y for x, we'd better do so in the
rule's LHS too, so we'd better ensure the RULE appears to mention 'x'
as well as 'v'
* Note [Rules are visible in their own rec group]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want the rules for 'f' to be visible in f's right-hand side.
And we'd like them to be visible in other functions in f's Rec
group. E.g. in Note [Specialisation rules] we want f' rule
to be visible in both f's RHS, and fs's RHS.
This means that we must simplify the RULEs first, before looking
at any of the definitions. This is done by Simplify.simplRecBind,
when it calls addLetIdInfo.
------------------------------------------------------------
Note [Choosing loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Loop breaking is surprisingly subtle. First read the section 4 of
"Secrets of the GHC inliner". This describes our basic plan.
We avoid infinite inlinings by choosing loop breakers, and
ensuring that a loop breaker cuts each loop.
Fundamentally, we do SCC analysis on a graph. For each recursive
group we choose a loop breaker, delete all edges to that node,
re-analyse the SCC, and iterate.
But what is the graph? NOT the same graph as was used for Note
[Forming Rec groups]! In particular, a RULE is like an equation for
'f' that is *always* inlined if it is applicable. We do *not* disable
rules for loop-breakers. It's up to whoever makes the rules to make
sure that the rules themselves always terminate. See Note [Rules for
recursive functions] in Simplify.lhs
Hence, if
f's RHS (or its INLINE template if it has one) mentions g, and
g has a RULE that mentions h, and
h has a RULE that mentions f
then we *must* choose f to be a loop breaker. Example: see Note
[Specialisation rules].
In general, take the free variables of f's RHS, and augment it with
all the variables reachable by RULES from those starting points. That
is the whole reason for computing rule_fv_env in occAnalBind. (Of
course we only consider free vars that are also binders in this Rec
group.) See also Note [Finding rule RHS free vars]
Note that when we compute this rule_fv_env, we only consider variables
free in the *RHS* of the rule, in contrast to the way we build the
Rec group in the first place (Note [Rule dependency info])
Note that if 'g' has RHS that mentions 'w', we should add w to
g's loop-breaker edges. More concretely there is an edge from f -> g
iff
(a) g is mentioned in f's RHS `xor` f's INLINE rhs
(see Note [Inline rules])
(b) or h is mentioned in f's RHS, and
g appears in the RHS of an active RULE of h
or a transitive sequence of active rules starting with h
Why "active rules"? See Note [Finding rule RHS free vars]
Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
chosen as a loop breaker, because their RHSs don't mention each other.
And indeed both can be inlined safely.
Note again that the edges of the graph we use for computing loop breakers
are not the same as the edges we use for computing the Rec blocks.
That's why we compute
- rec_edges for the Rec block analysis
- loop_breaker_edges for the loop breaker analysis
* Note [Finding rule RHS free vars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this real example from Data Parallel Haskell
tagZero :: Array Int -> Array Tag
{-# INLINE [1] tagZeroes #-}
tagZero xs = pmap (\x -> fromBool (x==0)) xs
{-# RULES "tagZero" [~1] forall xs n.
pmap fromBool <blah blah> = tagZero xs #-}
So tagZero's RHS mentions pmap, and pmap's RULE mentions tagZero.
However, tagZero can only be inlined in phase 1 and later, while
the RULE is only active *before* phase 1. So there's no problem.
To make this work, we look for the RHS free vars only for
*active* rules. That's the reason for the occ_rule_act field
of the OccEnv.
* Note [Weak loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~
There is a last nasty wrinkle. Suppose we have
Rec { f = f_rhs
RULE f [] = g
h = h_rhs
g = h
...more...
}
Remember that we simplify the RULES before any RHS (see Note
[Rules are visible in their own rec group] above).
So we must *not* postInlineUnconditionally 'g', even though
its RHS turns out to be trivial. (I'm assuming that 'g' is
not choosen as a loop breaker.) Why not? Because then we
drop the binding for 'g', which leaves it out of scope in the
RULE!
Here's a somewhat different example of the same thing
Rec { g = h
; h = ...f...
; f = f_rhs
RULE f [] = g }
Here the RULE is "below" g, but we *still* can't postInlineUnconditionally
g, because the RULE for f is active throughout. So the RHS of h
might rewrite to h = ...g...
So g must remain in scope in the output program!
We "solve" this by:
Make g a "weak" loop breaker (OccInfo = IAmLoopBreaker True)
iff g is a "missing free variable" of the Rec group
A "missing free variable" x is one that is mentioned in an RHS or
INLINE or RULE of a binding in the Rec group, but where the
dependency on x may not show up in the loop_breaker_edges (see
note [Choosing loop breakers} above).
A normal "strong" loop breaker has IAmLoopBreaker False. So
Inline postInlineUnconditionally
IAmLoopBreaker False no no
IAmLoopBreaker True yes no
other yes yes
The **sole** reason for this kind of loop breaker is so that
postInlineUnconditionally does not fire. Ugh. (Typically it'll
inline via the usual callSiteInline stuff, so it'll be dead in the
next pass, so the main Ugh is the tiresome complication.)
Note [Rules for imported functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
f = /\a. B.g a
RULE B.g Int = 1 + f Int
Note that
* The RULE is for an imported function.
* f is non-recursive
Now we
can get
f Int --> B.g Int Inlining f
--> 1 + f Int Firing RULE
and so the simplifier goes into an infinite loop. This
would not happen if the RULE was for a local function,
because we keep track of dependencies through rules. But
that is pretty much impossible to do for imported Ids. Suppose
f's definition had been
f = /\a. C.h a
where (by some long and devious process), C.h eventually inlines to
B.g. We could only spot such loops by exhaustively following
unfoldings of C.h etc, in case we reach B.g, and hence (via the RULE)
f.
Note that RULES for imported functions are important in practice; they
occur a lot in the libraries.
We regard this potential infinite loop as a *programmer* error.
It's up the programmer not to write silly rules like
RULE f x = f x
and the example above is just a more complicated version.
Note [Preventing loops due to imported functions rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider:
import GHC.Base (foldr)
{-# RULES "filterList" forall p. foldr (filterFB (:) p) [] = filter p #-}
filter p xs = build (\c n -> foldr (filterFB c p) n xs)
filterFB c p = ...
f = filter p xs
Note that filter is not a loop-breaker, so what happens is:
f = filter p xs
= {inline} build (\c n -> foldr (filterFB c p) n xs)
= {inline} foldr (filterFB (:) p) [] xs
= {RULE} filter p xs
We are in an infinite loop.
A more elaborate example (that I actually saw in practice when I went to
mark GHC.List.filter as INLINABLE) is as follows. Say I have this module:
{-# LANGUAGE RankNTypes #-}
module GHCList where
import Prelude hiding (filter)
import GHC.Base (build)
{-# INLINABLE filter #-}
filter :: (a -> Bool) -> [a] -> [a]
filter p [] = []
filter p (x:xs) = if p x then x : filter p xs else filter p xs
{-# NOINLINE [0] filterFB #-}
filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b
filterFB c p x r | p x = x `c` r
| otherwise = r
{-# RULES
"filter" [~1] forall p xs. filter p xs = build (\c n -> foldr
(filterFB c p) n xs)
"filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
#-}
Then (because RULES are applied inside INLINABLE unfoldings, but inlinings
are not), the unfolding given to "filter" in the interface file will be:
filter p [] = []
filter p (x:xs) = if p x then x : build (\c n -> foldr (filterFB c p) n xs)
else build (\c n -> foldr (filterFB c p) n xs
Note that because this unfolding does not mention "filter", filter is not
marked as a strong loop breaker. Therefore at a use site in another module:
filter p xs
= {inline}
case xs of [] -> []
(x:xs) -> if p x then x : build (\c n -> foldr (filterFB c p) n xs)
else build (\c n -> foldr (filterFB c p) n xs)
build (\c n -> foldr (filterFB c p) n xs)
= {inline} foldr (filterFB (:) p) [] xs
= {RULE} filter p xs
And we are in an infinite loop again, except that this time the loop is producing an
infinitely large *term* (an unrolling of filter) and so the simplifier finally
dies with "ticks exhausted"
Because of this problem, we make a small change in the occurrence analyser
designed to mark functions like "filter" as strong loop breakers on the basis that:
1. The RHS of filter mentions the local function "filterFB"
2. We have a rule which mentions "filterFB" on the LHS and "filter" on the RHS
So for each RULE for an *imported* function we are going to add
dependency edges between the *local* FVS of the rule LHS and the
*local* FVS of the rule RHS. We don't do anything special for RULES on
local functions because the standard occurrence analysis stuff is
pretty good at getting loop-breakerness correct there.
It is important to note that even with this extra hack we aren't always going to get
things right. For example, it might be that the rule LHS mentions an imported Id,
and another module has a RULE that can rewrite that imported Id to one of our local
Ids.
Note [Specialising imported functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BUT for *automatically-generated* rules, the programmer can't be
responsible for the "programmer error" in Note [Rules for imported
functions]. In paricular, consider specialising a recursive function
defined in another module. If we specialise a recursive function B.g,
we get
g_spec = .....(B.g Int).....
RULE B.g Int = g_spec
Here, g_spec doesn't look recursive, but when the rule fires, it
becomes so. And if B.g was mutually recursive, the loop might
not be as obvious as it is here.
To avoid this,
* When specialising a function that is a loop breaker,
give a NOINLINE pragma to the specialised function
Note [Glomming]
~~~~~~~~~~~~~~~
RULES for imported Ids can make something at the top refer to something at the bottom:
f = \x -> B.g (q x)
h = \y -> 3
RULE: B.g (q x) = h x
Applying this rule makes f refer to h, although f doesn't appear to
depend on h. (And, as in Note [Rules for imported functions], the
dependency might be more indirect. For example, f might mention C.t
rather than B.g, where C.t eventually inlines to B.g.)
NOTICE that this cannot happen for rules whose head is a
locally-defined function, because we accurately track dependencies
through RULES. It only happens for rules whose head is an imported
function (B.g in the example above).
Solution:
- When simplifying, bring all top level identifiers into
scope at the start, ignoring the Rec/NonRec structure, so
that when 'h' pops up in f's rhs, we find it in the in-scope set
(as the simplifier generally expects). This happens in simplTopBinds.
- In the occurrence analyser, if there are any out-of-scope
occurrences that pop out of the top, which will happen after
firing the rule: f = \x -> h x
h = \y -> 3
then just glom all the bindings into a single Rec, so that
the *next* iteration of the occurrence analyser will sort
them all out. This part happens in occurAnalysePgm.
------------------------------------------------------------
Note [Inline rules]
~~~~~~~~~~~~~~~~~~~
None of the above stuff about RULES applies to Inline Rules,
stored in a CoreUnfolding. The unfolding, if any, is simplified
at the same time as the regular RHS of the function (ie *not* like
Note [Rules are visible in their own rec group]), so it should be
treated *exactly* like an extra RHS.
Or, rather, when computing loop-breaker edges,
* If f has an INLINE pragma, and it is active, we treat the
INLINE rhs as f's rhs
* If it's inactive, we treat f as having no rhs
* If it has no INLINE pragma, we look at f's actual rhs
There is a danger that we'll be sub-optimal if we see this
f = ...f...
[INLINE f = ..no f...]
where f is recursive, but the INLINE is not. This can just about
happen with a sufficiently odd set of rules; eg
foo :: Int -> Int
{-# INLINE [1] foo #-}
foo x = x+1
bar :: Int -> Int
{-# INLINE [1] bar #-}
bar x = foo x + 1
{-# RULES "foo" [~1] forall x. foo x = bar x #-}
Here the RULE makes bar recursive; but it's INLINE pragma remains
non-recursive. It's tempting to then say that 'bar' should not be
a loop breaker, but an attempt to do so goes wrong in two ways:
a) We may get
$df = ...$cfoo...
$cfoo = ...$df....
[INLINE $cfoo = ...no-$df...]
But we want $cfoo to depend on $df explicitly so that we
put the bindings in the right order to inline $df in $cfoo
and perhaps break the loop altogether. (Maybe this
b)
Example [eftInt]
~~~~~~~~~~~~~~~
Example (from GHC.Enum):
eftInt :: Int# -> Int# -> [Int]
eftInt x y = ...(non-recursive)...
{-# INLINE [0] eftIntFB #-}
eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
eftIntFB c n x y = ...(non-recursive)...
{-# RULES
"eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
"eftIntList" [1] eftIntFB (:) [] = eftInt
#-}
Note [Specialisation rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this group, which is typical of what SpecConstr builds:
fs a = ....f (C a)....
f x = ....f (C a)....
{-# RULE f (C a) = fs a #-}
So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
- the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
- fs is inlined (say it's small)
- now there's another opportunity to apply the RULE
This showed up when compiling Control.Concurrent.Chan.getChanContents.
\begin{code}
type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
-- which is gotten from the Id.
data Details
= ND { nd_bndr :: Id -- Binder
, nd_rhs :: CoreExpr -- RHS, already occ-analysed
, nd_uds :: UsageDetails -- Usage from RHS, and RULES, and stable unfoldings
-- ignoring phase (ie assuming all are active)
-- See Note [Forming Rec groups]
, nd_inl :: IdSet -- Free variables of
-- the stable unfolding (if present and active)
-- or the RHS (if not)
-- but excluding any RULES
-- This is the IdSet that may be used if the Id is inlined
, nd_weak :: IdSet -- Binders of this Rec that are mentioned in nd_uds
-- but are *not* in nd_inl. These are the ones whose
-- dependencies might not be respected by loop_breaker_edges
-- See Note [Weak loop breakers]
, nd_active_rule_fvs :: IdSet -- Free variables of the RHS of active RULES
}
instance Outputable Details where
ppr nd = ptext (sLit "ND") <> braces
(sep [ ptext (sLit "bndr =") <+> ppr (nd_bndr nd)
, ptext (sLit "uds =") <+> ppr (nd_uds nd)
, ptext (sLit "inl =") <+> ppr (nd_inl nd)
, ptext (sLit "weak =") <+> ppr (nd_weak nd)
, ptext (sLit "rule =") <+> ppr (nd_active_rule_fvs nd)
])
makeNode :: OccEnv -> IdEnv IdSet -> VarSet -> (Var, CoreExpr) -> Node Details
makeNode env imp_rules_edges bndr_set (bndr, rhs)
= (details, varUnique bndr, keysUFM node_fvs)
where
details = ND { nd_bndr = bndr
, nd_rhs = rhs'
, nd_uds = rhs_usage3
, nd_weak = node_fvs `minusVarSet` inl_fvs
, nd_inl = inl_fvs
, nd_active_rule_fvs = active_rule_fvs }
-- Constructing the edges for the main Rec computation
-- See Note [Forming Rec groups]
(rhs_usage1, rhs') = occAnalRecRhs env rhs
rhs_usage2 = addIdOccs rhs_usage1 all_rule_fvs -- Note [Rules are extra RHSs]
-- Note [Rule dependency info]
rhs_usage3 = case mb_unf_fvs of
Just unf_fvs -> addIdOccs rhs_usage2 unf_fvs
Nothing -> rhs_usage2
node_fvs = udFreeVars bndr_set rhs_usage3
-- Finding the free variables of the rules
is_active = occ_rule_act env :: Activation -> Bool
rules = filterOut isBuiltinRule (idCoreRules bndr)
rules_w_fvs :: [(Activation, VarSet)] -- Find the RHS fvs
rules_w_fvs = maybe id (\ids -> ((AlwaysActive, ids):)) (lookupVarEnv imp_rules_edges bndr)
-- See Note [Preventing loops due to imported functions rules]
[ (ru_act rule, fvs)
| rule <- rules
, let fvs = exprFreeVars (ru_rhs rule)
`delVarSetList` ru_bndrs rule
, not (isEmptyVarSet fvs) ]
all_rule_fvs = rule_lhs_fvs `unionVarSet` rule_rhs_fvs
rule_rhs_fvs = mapUnionVarSet snd rules_w_fvs
rule_lhs_fvs = mapUnionVarSet (\ru -> exprsFreeVars (ru_args ru)
`delVarSetList` ru_bndrs ru) rules
active_rule_fvs = unionVarSets [fvs | (a,fvs) <- rules_w_fvs, is_active a]
-- Finding the free variables of the INLINE pragma (if any)
unf = realIdUnfolding bndr -- Ignore any current loop-breaker flag
mb_unf_fvs = stableUnfoldingVars unf
-- Find the "nd_inl" free vars; for the loop-breaker phase
inl_fvs = case mb_unf_fvs of
Nothing -> udFreeVars bndr_set rhs_usage1 -- No INLINE, use RHS
Just unf_fvs -> unf_fvs
-- We could check for an *active* INLINE (returning
-- emptyVarSet for an inactive one), but is_active
-- isn't the right thing (it tells about
-- RULE activation), so we'd need more plumbing
-----------------------------
occAnalRec :: SCC (Node Details)
-> (UsageDetails, [CoreBind])
-> (UsageDetails, [CoreBind])
-- The NonRec case is just like a Let (NonRec ...) above
occAnalRec (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs, nd_uds = rhs_uds}, _, _))
(body_uds, binds)
| not (bndr `usedIn` body_uds)
= (body_uds, binds) -- See Note [Dead code]
| otherwise -- It's mentioned in the body
= (body_uds' +++ rhs_uds,
NonRec tagged_bndr rhs : binds)
where
(body_uds', tagged_bndr) = tagBinder body_uds bndr
-- The Rec case is the interesting one
-- See Note [Loop breaking]
occAnalRec (CyclicSCC nodes) (body_uds, binds)
| not (any (`usedIn` body_uds) bndrs) -- NB: look at body_uds, not total_uds
= (body_uds, binds) -- See Note [Dead code]
| otherwise -- At this point we always build a single Rec
= -- pprTrace "occAnalRec" (vcat
-- [ text "tagged nodes" <+> ppr tagged_nodes
-- , text "lb edges" <+> ppr loop_breaker_edges])
(final_uds, Rec pairs : binds)
where
bndrs = [b | (ND { nd_bndr = b }, _, _) <- nodes]
bndr_set = mkVarSet bndrs
----------------------------
-- Tag the binders with their occurrence info
tagged_nodes = map tag_node nodes
total_uds = foldl add_uds body_uds nodes
final_uds = total_uds `minusVarEnv` bndr_set
add_uds usage_so_far (nd, _, _) = usage_so_far +++ nd_uds nd
tag_node :: Node Details -> Node Details
tag_node (details@ND { nd_bndr = bndr }, k, ks)
= (details { nd_bndr = setBinderOcc total_uds bndr }, k, ks)
---------------------------
-- Now reconstruct the cycle
pairs :: [(Id,CoreExpr)]
pairs | isEmptyVarSet weak_fvs = reOrderNodes 0 bndr_set weak_fvs tagged_nodes []
| otherwise = loopBreakNodes 0 bndr_set weak_fvs loop_breaker_edges []
-- If weak_fvs is empty, the loop_breaker_edges will include all
-- the edges in tagged_nodes, so there isn't any point in doing
-- a fresh SCC computation that will yield a single CyclicSCC result.
weak_fvs :: VarSet
weak_fvs = mapUnionVarSet (nd_weak . fstOf3) nodes
-- See Note [Choosing loop breakers] for loop_breaker_edges
loop_breaker_edges = map mk_node tagged_nodes
mk_node (details@(ND { nd_inl = inl_fvs }), k, _)
= (details, k, keysUFM (extendFvs_ rule_fv_env inl_fvs))
------------------------------------
rule_fv_env :: IdEnv IdSet
-- Maps a variable f to the variables from this group
-- mentioned in RHS of active rules for f
-- Domain is *subset* of bound vars (others have no rule fvs)
rule_fv_env = transClosureFV (mkVarEnv init_rule_fvs)
init_rule_fvs -- See Note [Finding rule RHS free vars]
= [ (b, trimmed_rule_fvs)
| (ND { nd_bndr = b, nd_active_rule_fvs = rule_fvs },_,_) <- nodes
, let trimmed_rule_fvs = rule_fvs `intersectVarSet` bndr_set
, not (isEmptyVarSet trimmed_rule_fvs)]
\end{code}
@loopBreakSCC@ is applied to the list of (binder,rhs) pairs for a cyclic
strongly connected component (there's guaranteed to be a cycle). It returns the
same pairs, but
a) in a better order,
b) with some of the Ids having a IAmALoopBreaker pragma
The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
that the simplifier can guarantee not to loop provided it never records an inlining
for these no-inline guys.
Furthermore, the order of the binds is such that if we neglect dependencies
on the no-inline Ids then the binds are topologically sorted. This means
that the simplifier will generally do a good job if it works from top bottom,
recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
\begin{code}
type Binding = (Id,CoreExpr)
mk_loop_breaker :: Node Details -> Binding
mk_loop_breaker (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
= (setIdOccInfo bndr strongLoopBreaker, rhs)
mk_non_loop_breaker :: VarSet -> Node Details -> Binding
-- See Note [Weak loop breakers]
mk_non_loop_breaker used_in_rules (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
| bndr `elemVarSet` used_in_rules = (setIdOccInfo bndr weakLoopBreaker, rhs)
| otherwise = (bndr, rhs)
udFreeVars :: VarSet -> UsageDetails -> VarSet
-- Find the subset of bndrs that are mentioned in uds
udFreeVars bndrs uds = intersectUFM_C (\b _ -> b) bndrs uds
loopBreakNodes :: Int
-> VarSet -- All binders
-> VarSet -- Binders whose dependencies may be "missing"
-- See Note [Weak loop breakers]
-> [Node Details]
-> [Binding] -- Append these to the end
-> [Binding]
-- Return the bindings sorted into a plausible order, and marked with loop breakers.
loopBreakNodes depth bndr_set weak_fvs nodes binds
= go (stronglyConnCompFromEdgedVerticesR nodes) binds
where
go [] binds = binds
go (scc:sccs) binds = loop_break_scc scc (go sccs binds)
loop_break_scc scc binds
= case scc of
AcyclicSCC node -> mk_non_loop_breaker weak_fvs node : binds
CyclicSCC [node] -> mk_loop_breaker node : binds
CyclicSCC nodes -> reOrderNodes depth bndr_set weak_fvs nodes binds
reOrderNodes :: Int -> VarSet -> VarSet -> [Node Details] -> [Binding] -> [Binding]
-- Choose a loop breaker, mark it no-inline,
-- do SCC analysis on the rest, and recursively sort them out
reOrderNodes _ _ _ [] _ = panic "reOrderNodes"
reOrderNodes depth bndr_set weak_fvs (node : nodes) binds
= -- pprTrace "reOrderNodes" (text "unchosen" <+> ppr unchosen $$
-- text "chosen" <+> ppr chosen_nodes) $
loopBreakNodes new_depth bndr_set weak_fvs unchosen $
(map mk_loop_breaker chosen_nodes ++ binds)
where
(chosen_nodes, unchosen) = choose_loop_breaker (score node) [node] [] nodes
approximate_loop_breaker = depth >= 2
new_depth | approximate_loop_breaker = 0
| otherwise = depth+1
-- After two iterations (d=0, d=1) give up
-- and approximate, returning to d=0
choose_loop_breaker :: Int -- Best score so far
-> [Node Details] -- Nodes with this score
-> [Node Details] -- Nodes with higher scores
-> [Node Details] -- Unprocessed nodes
-> ([Node Details], [Node Details])
-- This loop looks for the bind with the lowest score
-- to pick as the loop breaker. The rest accumulate in
choose_loop_breaker _ loop_nodes acc []
= (loop_nodes, acc) -- Done
-- If approximate_loop_breaker is True, we pick *all*
-- nodes with lowest score, else just one
-- See Note [Complexity of loop breaking]
choose_loop_breaker loop_sc loop_nodes acc (node : nodes)
| sc < loop_sc -- Lower score so pick this new one
= choose_loop_breaker sc [node] (loop_nodes ++ acc) nodes
| approximate_loop_breaker && sc == loop_sc
= choose_loop_breaker loop_sc (node : loop_nodes) acc nodes
| otherwise -- Higher score so don't pick it
= choose_loop_breaker loop_sc loop_nodes (node : acc) nodes
where
sc = score node
score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
score (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _)
| not (isId bndr) = 100 -- A type or cercion variable is never a loop breaker
| isDFunId bndr = 9 -- Never choose a DFun as a loop breaker
-- Note [DFuns should not be loop breakers]
| Just be_very_keen <- hasStableCoreUnfolding_maybe (idUnfolding bndr)
= if be_very_keen then 6 -- Note [Loop breakers and INLINE/INLINEABLE pragmas]
else 3
-- Data structures are more important than INLINE pragmas
-- so that dictionary/method recursion unravels
-- Note that this case hits all stable unfoldings, so we
-- never look at 'rhs' for stable unfoldings. That's right, because
-- 'rhs' is irrelevant for inlining things with a stable unfolding
| is_con_app rhs = 5 -- Data types help with cases: Note [Constructor applications]
| exprIsTrivial rhs = 10 -- Practically certain to be inlined
-- Used to have also: && not (isExportedId bndr)
-- But I found this sometimes cost an extra iteration when we have
-- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
-- where df is the exported dictionary. Then df makes a really
-- bad choice for loop breaker
-- If an Id is marked "never inline" then it makes a great loop breaker
-- The only reason for not checking that here is that it is rare
-- and I've never seen a situation where it makes a difference,
-- so it probably isn't worth the time to test on every binder
-- | isNeverActive (idInlinePragma bndr) = -10
| isOneOcc (idOccInfo bndr) = 2 -- Likely to be inlined
| canUnfold (realIdUnfolding bndr) = 1
-- The Id has some kind of unfolding
-- Ignore loop-breaker-ness here because that is what we are setting!
| otherwise = 0
-- Checking for a constructor application
-- Cheap and cheerful; the simplifer moves casts out of the way
-- The lambda case is important to spot x = /\a. C (f a)
-- which comes up when C is a dictionary constructor and
-- f is a default method.
-- Example: the instance for Show (ST s a) in GHC.ST
--
-- However we *also* treat (\x. C p q) as a con-app-like thing,
-- Note [Closure conversion]
is_con_app (Var v) = isConLikeId v
is_con_app (App f _) = is_con_app f
is_con_app (Lam _ e) = is_con_app e
is_con_app (Tick _ e) = is_con_app e
is_con_app _ = False
\end{code}
Note [Complexity of loop breaking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The loop-breaking algorithm knocks out one binder at a time, and
performs a new SCC analysis on the remaining binders. That can
behave very badly in tightly-coupled groups of bindings; in the
worst case it can be (N**2)*log N, because it does a full SCC
on N, then N-1, then N-2 and so on.
To avoid this, we switch plans after 2 (or whatever) attempts:
Plan A: pick one binder with the lowest score, make it
a loop breaker, and try again
Plan B: pick *all* binders with the lowest score, make them
all loop breakers, and try again
Since there are only a small finite number of scores, this will
terminate in a constant number of iterations, rather than O(N)
iterations.
You might thing that it's very unlikely, but RULES make it much
more likely. Here's a real example from Trac #1969:
Rec { $dm = \d.\x. op d
{-# RULES forall d. $dm Int d = $s$dm1
forall d. $dm Bool d = $s$dm2 #-}
dInt = MkD .... opInt ...
dInt = MkD .... opBool ...
opInt = $dm dInt
opBool = $dm dBool
$s$dm1 = \x. op dInt
$s$dm2 = \x. op dBool }
The RULES stuff means that we can't choose $dm as a loop breaker
(Note [Choosing loop breakers]), so we must choose at least (say)
opInt *and* opBool, and so on. The number of loop breakders is
linear in the number of instance declarations.
Note [Loop breakers and INLINE/INLINEABLE pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Avoid choosing a function with an INLINE pramga as the loop breaker!
If such a function is mutually-recursive with a non-INLINE thing,
then the latter should be the loop-breaker.
It's vital to distinguish between INLINE and INLINEABLE (the
Bool returned by hasStableCoreUnfolding_maybe). If we start with
Rec { {-# INLINEABLE f #-}
f x = ...f... }
and then worker/wrapper it through strictness analysis, we'll get
Rec { {-# INLINEABLE $wf #-}
$wf p q = let x = (p,q) in ...f...
{-# INLINE f #-}
f x = case x of (p,q) -> $wf p q }
Now it is vital that we choose $wf as the loop breaker, so we can
inline 'f' in '$wf'.
Note [DFuns should not be loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's particularly bad to make a DFun into a loop breaker. See
Note [How instance declarations are translated] in TcInstDcls
We give DFuns a higher score than ordinary CONLIKE things because
if there's a choice we want the DFun to be the non-looop breker. Eg
rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
$fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
{-# DFUN #-}
$fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
}
Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
if we can't unravel the DFun first.
Note [Constructor applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's really really important to inline dictionaries. Real
example (the Enum Ordering instance from GHC.Base):
rec f = \ x -> case d of (p,q,r) -> p x
g = \ x -> case d of (p,q,r) -> q x
d = (v, f, g)
Here, f and g occur just once; but we can't inline them into d.
On the other hand we *could* simplify those case expressions if
we didn't stupidly choose d as the loop breaker.
But we won't because constructor args are marked "Many".
Inlining dictionaries is really essential to unravelling
the loops in static numeric dictionaries, see GHC.Float.
Note [Closure conversion]
~~~~~~~~~~~~~~~~~~~~~~~~~
We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
The immediate motivation came from the result of a closure-conversion transformation
which generated code like this:
data Clo a b = forall c. Clo (c -> a -> b) c
($:) :: Clo a b -> a -> b
Clo f env $: x = f env x
rec { plus = Clo plus1 ()
; plus1 _ n = Clo plus2 n
; plus2 Zero n = n
; plus2 (Succ m) n = Succ (plus $: m $: n) }
If we inline 'plus' and 'plus1', everything unravels nicely. But if
we choose 'plus1' as the loop breaker (which is entirely possible
otherwise), the loop does not unravel nicely.
@occAnalRhs@ deals with the question of bindings where the Id is marked
by an INLINE pragma. For these we record that anything which occurs
in its RHS occurs many times. This pessimistically assumes that ths
inlined binder also occurs many times in its scope, but if it doesn't
we'll catch it next time round. At worst this costs an extra simplifier pass.
ToDo: try using the occurrence info for the inline'd binder.
[March 97] We do the same for atomic RHSs. Reason: see notes with loopBreakSCC.
[June 98, SLPJ] I've undone this change; I don't understand it. See notes with loopBreakSCC.
\begin{code}
occAnalRecRhs :: OccEnv -> CoreExpr -- Rhs
-> (UsageDetails, CoreExpr)
-- Returned usage details covers only the RHS,
-- and *not* the RULE or INLINE template for the Id
occAnalRecRhs env rhs = occAnal (rhsCtxt env) rhs
occAnalNonRecRhs :: OccEnv
-> Id -> CoreExpr -- Binder and rhs
-- Binder is already tagged with occurrence info
-> (UsageDetails, CoreExpr)
-- Returned usage details covers only the RHS,
-- and *not* the RULE or INLINE template for the Id
occAnalNonRecRhs env bndr rhs
= occAnal rhs_env rhs
where
-- See Note [Use one-shot info]
env1 = env { occ_one_shots = argOneShots OneShotLam dmd }
-- See Note [Cascading inlines]
rhs_env | certainly_inline = env1
| otherwise = rhsCtxt env1
certainly_inline -- See Note [Cascading inlines]
= case idOccInfo bndr of
OneOcc in_lam one_br _ -> not in_lam && one_br && active && not_stable
_ -> False
dmd = idDemandInfo bndr
active = isAlwaysActive (idInlineActivation bndr)
not_stable = not (isStableUnfolding (idUnfolding bndr))
addIdOccs :: UsageDetails -> VarSet -> UsageDetails
addIdOccs usage id_set = foldVarSet add usage id_set
where
add v u | isId v = addOneOcc u v NoOccInfo
| otherwise = u
-- Give a non-committal binder info (i.e NoOccInfo) because
-- a) Many copies of the specialised thing can appear
-- b) We don't want to substitute a BIG expression inside a RULE
-- even if that's the only occurrence of the thing
-- (Same goes for INLINE.)
\end{code}
Note [Cascading inlines]
~~~~~~~~~~~~~~~~~~~~~~~~
By default we use an rhsCtxt for the RHS of a binding. This tells the
occ anal n that it's looking at an RHS, which has an effect in
occAnalApp. In particular, for constructor applications, it makes
the arguments appear to have NoOccInfo, so that we don't inline into
them. Thus x = f y
k = Just x
we do not want to inline x.
But there's a problem. Consider
x1 = a0 : []
x2 = a1 : x1
x3 = a2 : x2
g = f x3
First time round, it looks as if x1 and x2 occur as an arg of a
let-bound constructor ==> give them a many-occurrence.
But then x3 is inlined (unconditionally as it happens) and
next time round, x2 will be, and the next time round x1 will be
Result: multiple simplifier iterations. Sigh.
So, when analysing the RHS of x3 we notice that x3 will itself
definitely inline the next time round, and so we analyse x3's rhs in
an ordinary context, not rhsCtxt. Hence the "certainly_inline" stuff.
Annoyingly, we have to approximate SimplUtils.preInlineUnconditionally.
If we say "yes" when preInlineUnconditionally says "no" the simplifier iterates
indefinitely:
x = f y
k = Just x
inline ==>
k = Just (f y)
float ==>
x1 = f y
k = Just x1
This is worse than the slow cascade, so we only want to say "certainly_inline"
if it really is certain. Look at the note with preInlineUnconditionally
for the various clauses.
Expressions
~~~~~~~~~~~
\begin{code}
occAnal :: OccEnv
-> CoreExpr
-> (UsageDetails, -- Gives info only about the "interesting" Ids
CoreExpr)
occAnal _ expr@(Type _) = (emptyDetails, expr)
occAnal _ expr@(Lit _) = (emptyDetails, expr)
occAnal env expr@(Var v) = (mkOneOcc env v False, expr)
-- At one stage, I gathered the idRuleVars for v here too,
-- which in a way is the right thing to do.
-- But that went wrong right after specialisation, when
-- the *occurrences* of the overloaded function didn't have any
-- rules in them, so the *specialised* versions looked as if they
-- weren't used at all.
occAnal _ (Coercion co)
= (addIdOccs emptyDetails (coVarsOfCo co), Coercion co)
-- See Note [Gather occurrences of coercion variables]
\end{code}
Note [Gather occurrences of coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to gather info about what coercion variables appear, so that
we can sort them into the right place when doing dependency analysis.
\begin{code}
occAnal env (Tick tickish body)
| Breakpoint _ ids <- tickish
= (mapVarEnv markInsideSCC usage
+++ mkVarEnv (zip ids (repeat NoOccInfo)), Tick tickish body')
-- never substitute for any of the Ids in a Breakpoint
| tickishScoped tickish
= (mapVarEnv markInsideSCC usage, Tick tickish body')
| otherwise
= (usage, Tick tickish body')
where
!(usage,body') = occAnal env body
occAnal env (Cast expr co)
= case occAnal env expr of { (usage, expr') ->
let usage1 = markManyIf (isRhsEnv env) usage
usage2 = addIdOccs usage1 (coVarsOfCo co)
-- See Note [Gather occurrences of coercion variables]
in (usage2, Cast expr' co)
-- If we see let x = y `cast` co
-- then mark y as 'Many' so that we don't
-- immediately inline y again.
}
\end{code}
\begin{code}
occAnal env app@(App _ _)
= occAnalApp env (collectArgs app)
-- Ignore type variables altogether
-- (a) occurrences inside type lambdas only not marked as InsideLam
-- (b) type variables not in environment
occAnal env (Lam x body) | isTyVar x
= case occAnal env body of { (body_usage, body') ->
(body_usage, Lam x body')
}
-- For value lambdas we do a special hack. Consider
-- (\x. \y. ...x...)
-- If we did nothing, x is used inside the \y, so would be marked
-- as dangerous to dup. But in the common case where the abstraction
-- is applied to two arguments this is over-pessimistic.
-- So instead, we just mark each binder with its occurrence
-- info in the *body* of the multiple lambda.
-- Then, the simplifier is careful when partially applying lambdas.
occAnal env expr@(Lam _ _)
= case occAnal env_body body of { (body_usage, body') ->
let
(final_usage, tagged_binders) = tagLamBinders body_usage binders'
-- Use binders' to put one-shot info on the lambdas
really_final_usage
| all isOneShotBndr binders' = final_usage
| otherwise = mapVarEnv markInsideLam final_usage
in
(really_final_usage, mkLams tagged_binders body') }
where
(binders, body) = collectBinders expr
(env_body, binders') = oneShotGroup env binders
occAnal env (Case scrut bndr ty alts)
= case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
let
alts_usage = foldr combineAltsUsageDetails emptyDetails alts_usage_s
(alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
total_usage = scrut_usage +++ alts_usage1
in
total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
where
-- Note [Case binder usage]
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- The case binder gets a usage of either "many" or "dead", never "one".
-- Reason: we like to inline single occurrences, to eliminate a binding,
-- but inlining a case binder *doesn't* eliminate a binding.
-- We *don't* want to transform
-- case x of w { (p,q) -> f w }
-- into
-- case x of w { (p,q) -> f (p,q) }
tag_case_bndr usage bndr
= case lookupVarEnv usage bndr of
Nothing -> (usage, setIdOccInfo bndr IAmDead)
Just _ -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
alt_env = mkAltEnv env scrut bndr
occ_anal_alt = occAnalAlt alt_env
occ_anal_scrut (Var v) (alt1 : other_alts)
| not (null other_alts) || not (isDefaultAlt alt1)
= (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
-- in an interesting context; the case has
-- at least one non-default alternative
occ_anal_scrut scrut _alts
= occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
occAnal env (Let bind body)
= case occAnal env body of { (body_usage, body') ->
case occAnalBind env env emptyVarEnv bind body_usage of { (final_usage, new_binds) ->
(final_usage, mkLets new_binds body') }}
occAnalArgs :: OccEnv -> [CoreExpr] -> [OneShots] -> (UsageDetails, [CoreExpr])
occAnalArgs _ [] _
= (emptyDetails, [])
occAnalArgs env (arg:args) one_shots
| isTypeArg arg
= case occAnalArgs env args one_shots of { (uds, args') ->
(uds, arg:args') }
| otherwise
= case argCtxt env one_shots of { (arg_env, one_shots') ->
case occAnal arg_env arg of { (uds1, arg') ->
case occAnalArgs env args one_shots' of { (uds2, args') ->
(uds1 +++ uds2, arg':args') }}}
\end{code}
Applications are dealt with specially because we want
the "build hack" to work.
Note [Arguments of let-bound constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f x = let y = expensive x in
let z = (True,y) in
(case z of {(p,q)->q}, case z of {(p,q)->q})
We feel free to duplicate the WHNF (True,y), but that means
that y may be duplicated thereby.
If we aren't careful we duplicate the (expensive x) call!
Constructors are rather like lambdas in this way.
\begin{code}
occAnalApp :: OccEnv
-> (Expr CoreBndr, [Arg CoreBndr])
-> (UsageDetails, Expr CoreBndr)
occAnalApp env (Var fun, args)
= case args_stuff of { (args_uds, args') ->
let
final_args_uds = markManyIf (isRhsEnv env && is_exp) args_uds
-- We mark the free vars of the argument of a constructor or PAP
-- as "many", if it is the RHS of a let(rec).
-- This means that nothing gets inlined into a constructor argument
-- position, which is what we want. Typically those constructor
-- arguments are just variables, or trivial expressions.
--
-- This is the *whole point* of the isRhsEnv predicate
-- See Note [Arguments of let-bound constructors]
in
(fun_uds +++ final_args_uds, mkApps (Var fun) args') }
where
n_val_args = valArgCount args
fun_uds = mkOneOcc env fun (n_val_args > 0)
is_exp = isExpandableApp fun n_val_args
-- See Note [CONLIKE pragma] in BasicTypes
-- The definition of is_exp should match that in
-- Simplify.prepareRhs
one_shots = argsOneShots (idStrictness fun) n_val_args
-- See Note [Use one-shot info]
args_stuff = occAnalArgs env args one_shots
-- (foldr k z xs) may call k many times, but it never
-- shares a partial application of k; hence [False,True]
-- This means we can optimise
-- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
-- by floating in the v
occAnalApp env (fun, args)
= case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
-- The addAppCtxt is a bit cunning. One iteration of the simplifier
-- often leaves behind beta redexs like
-- (\x y -> e) a1 a2
-- Here we would like to mark x,y as one-shot, and treat the whole
-- thing much like a let. We do this by pushing some True items
-- onto the context stack.
case occAnalArgs env args [] of { (args_uds, args') ->
(fun_uds +++ args_uds, mkApps fun' args') }}
markManyIf :: Bool -- If this is true
-> UsageDetails -- Then do markMany on this
-> UsageDetails
markManyIf True uds = mapVarEnv markMany uds
markManyIf False uds = uds
\end{code}
Note [Use one-shot information]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The occurrrence analyser propagates one-shot-lambda information in two situation
* Applications: eg build (\cn -> blah)
Propagate one-shot info from the strictness signature of 'build' to
the \cn
* Let-bindings: eg let f = \c. let ... in \n -> blah
in (build f, build f)
Propagate one-shot info from the demanand-info on 'f' to the
lambdas in its RHS (which may not be syntactically at the top)
Some of this is done by the demand analyser, but this way it happens
much earlier, taking advantage of the strictness signature of
imported functions.
Note [Binders in case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case x of y { (a,b) -> f y }
We treat 'a', 'b' as dead, because they don't physically occur in the
case alternative. (Indeed, a variable is dead iff it doesn't occur in
its scope in the output of OccAnal.) It really helps to know when
binders are unused. See esp the call to isDeadBinder in
Simplify.mkDupableAlt
In this example, though, the Simplifier will bring 'a' and 'b' back to
life, beause it binds 'y' to (a,b) (imagine got inlined and
scrutinised y).
\begin{code}
occAnalAlt :: (OccEnv, Maybe (Id, CoreExpr))
-> CoreAlt
-> (UsageDetails, Alt IdWithOccInfo)
occAnalAlt (env, scrut_bind) (con, bndrs, rhs)
= case occAnal env rhs of { (rhs_usage1, rhs1) ->
let
(alt_usg, tagged_bndrs) = tagLamBinders rhs_usage1 bndrs
-- See Note [Binders in case alternatives]
(alt_usg', rhs2) =
wrapAltRHS env scrut_bind alt_usg tagged_bndrs rhs1
in
(alt_usg', (con, tagged_bndrs, rhs2)) }
wrapAltRHS :: OccEnv
-> Maybe (Id, CoreExpr) -- proxy mapping generated by mkAltEnv
-> UsageDetails -- usage for entire alt (p -> rhs)
-> [Var] -- alt binders
-> CoreExpr -- alt RHS
-> (UsageDetails, CoreExpr)
wrapAltRHS env (Just (scrut_var, let_rhs)) alt_usg bndrs alt_rhs
| occ_binder_swap env
, scrut_var `usedIn` alt_usg -- bndrs are not be present in alt_usg so this
-- handles condition (a) in Note [Binder swap]
, not captured -- See condition (b) in Note [Binder swap]
= ( alt_usg' +++ let_rhs_usg
, Let (NonRec tagged_scrut_var let_rhs') alt_rhs )
where
captured = any (`usedIn` let_rhs_usg) bndrs
-- The rhs of the let may include coercion variables
-- if the scrutinee was a cast, so we must gather their
-- usage. See Note [Gather occurrences of coercion variables]
(let_rhs_usg, let_rhs') = occAnal env let_rhs
(alt_usg', tagged_scrut_var) = tagBinder alt_usg scrut_var
wrapAltRHS _ _ alt_usg _ alt_rhs
= (alt_usg, alt_rhs)
\end{code}
%************************************************************************
%* *
OccEnv
%* *
%************************************************************************
\begin{code}
data OccEnv
= OccEnv { occ_encl :: !OccEncl -- Enclosing context information
, occ_one_shots :: !OneShots -- Tells about linearity
, occ_gbl_scrut :: GlobalScruts
, occ_rule_act :: Activation -> Bool -- Which rules are active
-- See Note [Finding rule RHS free vars]
, occ_binder_swap :: !Bool -- enable the binder_swap
-- See CorePrep Note [Dead code in CorePrep]
}
type GlobalScruts = IdSet -- See Note [Binder swap on GlobalId scrutinees]
-----------------------------
-- OccEncl is used to control whether to inline into constructor arguments
-- For example:
-- x = (p,q) -- Don't inline p or q
-- y = /\a -> (p a, q a) -- Still don't inline p or q
-- z = f (p,q) -- Do inline p,q; it may make a rule fire
-- So OccEncl tells enought about the context to know what to do when
-- we encounter a contructor application or PAP.
data OccEncl
= OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
-- Don't inline into constructor args here
| OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
-- Do inline into constructor args here
instance Outputable OccEncl where
ppr OccRhs = ptext (sLit "occRhs")
ppr OccVanilla = ptext (sLit "occVanilla")
type OneShots = [OneShotInfo]
-- [] No info
--
-- one_shot_info:ctxt Analysing a function-valued expression that
-- will be applied as described by one_shot_info
initOccEnv :: (Activation -> Bool) -> OccEnv
initOccEnv active_rule
= OccEnv { occ_encl = OccVanilla
, occ_one_shots = []
, occ_gbl_scrut = emptyVarSet -- PE emptyVarEnv emptyVarSet
, occ_rule_act = active_rule
, occ_binder_swap = True }
vanillaCtxt :: OccEnv -> OccEnv
vanillaCtxt env = env { occ_encl = OccVanilla, occ_one_shots = [] }
rhsCtxt :: OccEnv -> OccEnv
rhsCtxt env = env { occ_encl = OccRhs, occ_one_shots = [] }
argCtxt :: OccEnv -> [OneShots] -> (OccEnv, [OneShots])
argCtxt env []
= (env { occ_encl = OccVanilla, occ_one_shots = [] }, [])
argCtxt env (one_shots:one_shots_s)
= (env { occ_encl = OccVanilla, occ_one_shots = one_shots }, one_shots_s)
isRhsEnv :: OccEnv -> Bool
isRhsEnv (OccEnv { occ_encl = OccRhs }) = True
isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
oneShotGroup :: OccEnv -> [CoreBndr]
-> ( OccEnv
, [CoreBndr] )
-- The result binders have one-shot-ness set that they might not have had originally.
-- This happens in (build (\cn -> e)). Here the occurrence analyser
-- linearity context knows that c,n are one-shot, and it records that fact in
-- the binder. This is useful to guide subsequent float-in/float-out tranformations
oneShotGroup env@(OccEnv { occ_one_shots = ctxt }) bndrs
= go ctxt bndrs []
where
go ctxt [] rev_bndrs
= ( env { occ_one_shots = ctxt, occ_encl = OccVanilla }
, reverse rev_bndrs )
go [] bndrs rev_bndrs
= ( env { occ_one_shots = [], occ_encl = OccVanilla }
, reverse rev_bndrs ++ bndrs )
go ctxt (bndr:bndrs) rev_bndrs
| isId bndr
= case ctxt of
[] -> go [] bndrs (bndr : rev_bndrs)
(one_shot : ctxt) -> go ctxt bndrs (bndr': rev_bndrs)
where
bndr' = updOneShotInfo bndr one_shot
| otherwise
= go ctxt bndrs (bndr:rev_bndrs)
addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
addAppCtxt env@(OccEnv { occ_one_shots = ctxt }) args
= env { occ_one_shots = replicate (valArgCount args) OneShotLam ++ ctxt }
\end{code}
\begin{code}
transClosureFV :: UniqFM VarSet -> UniqFM VarSet
-- If (f,g), (g,h) are in the input, then (f,h) is in the output
-- as well as (f,g), (g,h)
transClosureFV env
| no_change = env
| otherwise = transClosureFV (listToUFM new_fv_list)
where
(no_change, new_fv_list) = mapAccumL bump True (ufmToList env)
bump no_change (b,fvs)
| no_change_here = (no_change, (b,fvs))
| otherwise = (False, (b,new_fvs))
where
(new_fvs, no_change_here) = extendFvs env fvs
-------------
extendFvs_ :: UniqFM VarSet -> VarSet -> VarSet
extendFvs_ env s = fst (extendFvs env s) -- Discard the Bool flag
extendFvs :: UniqFM VarSet -> VarSet -> (VarSet, Bool)
-- (extendFVs env s) returns
-- (s `union` env(s), env(s) `subset` s)
extendFvs env s
| isNullUFM env
= (s, True)
| otherwise
= (s `unionVarSet` extras, extras `subVarSet` s)
where
extras :: VarSet -- env(s)
extras = foldUFM unionVarSet emptyVarSet $
intersectUFM_C (\x _ -> x) env s
\end{code}
%************************************************************************
%* *
Binder swap
%* *
%************************************************************************
Note [Binder swap]
~~~~~~~~~~~~~~~~~~
We do these two transformations right here:
(1) case x of b { pi -> ri }
==>
case x of b { pi -> let x=b in ri }
(2) case (x |> co) of b { pi -> ri }
==>
case (x |> co) of b { pi -> let x = b |> sym co in ri }
Why (2)? See Note [Case of cast]
In both cases, in a particular alternative (pi -> ri), we only
add the binding if
(a) x occurs free in (pi -> ri)
(ie it occurs in ri, but is not bound in pi)
(b) the pi does not bind b (or the free vars of co)
We need (a) and (b) for the inserted binding to be correct.
For the alternatives where we inject the binding, we can transfer
all x's OccInfo to b. And that is the point.
Notice that
* The deliberate shadowing of 'x'.
* That (a) rapidly becomes false, so no bindings are injected.
The reason for doing these transformations here is because it allows
us to adjust the OccInfo for 'x' and 'b' as we go.
* Suppose the only occurrences of 'x' are the scrutinee and in the
ri; then this transformation makes it occur just once, and hence
get inlined right away.
* If we do this in the Simplifier, we don't know whether 'x' is used
in ri, so we are forced to pessimistically zap b's OccInfo even
though it is typically dead (ie neither it nor x appear in the
ri). There's nothing actually wrong with zapping it, except that
it's kind of nice to know which variables are dead. My nose
tells me to keep this information as robustly as possible.
The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
{x=b}; it's Nothing if the binder-swap doesn't happen.
There is a danger though. Consider
let v = x +# y
in case (f v) of w -> ...v...v...
And suppose that (f v) expands to just v. Then we'd like to
use 'w' instead of 'v' in the alternative. But it may be too
late; we may have substituted the (cheap) x+#y for v in the
same simplifier pass that reduced (f v) to v.
I think this is just too bad. CSE will recover some of it.
Note [Case of cast]
~~~~~~~~~~~~~~~~~~~
Consider case (x `cast` co) of b { I# ->
... (case (x `cast` co) of {...}) ...
We'd like to eliminate the inner case. That is the motivation for
equation (2) in Note [Binder swap]. When we get to the inner case, we
inline x, cancel the casts, and away we go.
Note [Binder swap on GlobalId scrutinees]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the scrutinee is a GlobalId we must take care in two ways
i) In order to *know* whether 'x' occurs free in the RHS, we need its
occurrence info. BUT, we don't gather occurrence info for
GlobalIds. That's the reason for the (small) occ_gbl_scrut env in
OccEnv is for: it says "gather occurrence info for these".
ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
has an External Name. See, for example, SimplEnv Note [Global Ids in
the substitution].
Note [Zap case binders in proxy bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From the original
case x of cb(dead) { p -> ...x... }
we will get
case x of cb(live) { p -> let x = cb in ...x... }
Core Lint never expects to find an *occurrence* of an Id marked
as Dead, so we must zap the OccInfo on cb before making the
binding x = cb. See Trac #5028.
Historical note [no-case-of-case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We *used* to suppress the binder-swap in case expressions when
-fno-case-of-case is on. Old remarks:
"This happens in the first simplifier pass,
and enhances full laziness. Here's the bad case:
f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
If we eliminate the inner case, we trap it inside the I# v -> arm,
which might prevent some full laziness happening. I've seen this
in action in spectral/cichelli/Prog.hs:
[(m,n) | m <- [1..max], n <- [1..max]]
Hence the check for NoCaseOfCase."
However, now the full-laziness pass itself reverses the binder-swap, so this
check is no longer necessary.
Historical note [Suppressing the case binder-swap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This old note describes a problem that is also fixed by doing the
binder-swap in OccAnal:
There is another situation when it might make sense to suppress the
case-expression binde-swap. If we have
case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
...other cases .... }
We'll perform the binder-swap for the outer case, giving
case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
...other cases .... }
But there is no point in doing it for the inner case, because w1 can't
be inlined anyway. Furthermore, doing the case-swapping involves
zapping w2's occurrence info (see paragraphs that follow), and that
forces us to bind w2 when doing case merging. So we get
case x of w1 { A -> let w2 = w1 in e1
B -> let w2 = w1 in e2
...other cases .... }
This is plain silly in the common case where w2 is dead.
Even so, I can't see a good way to implement this idea. I tried
not doing the binder-swap if the scrutinee was already evaluated
but that failed big-time:
data T = MkT !Int
case v of w { MkT x ->
case x of x1 { I# y1 ->
case x of x2 { I# y2 -> ...
Notice that because MkT is strict, x is marked "evaluated". But to
eliminate the last case, we must either make sure that x (as well as
x1) has unfolding MkT y1. THe straightforward thing to do is to do
the binder-swap. So this whole note is a no-op.
It's fixed by doing the binder-swap in OccAnal because we can do the
binder-swap unconditionally and still get occurrence analysis
information right.
\begin{code}
mkAltEnv :: OccEnv -> CoreExpr -> Id -> (OccEnv, Maybe (Id, CoreExpr))
-- Does two things: a) makes the occ_one_shots = OccVanilla
-- b) extends the GlobalScruts if possible
-- c) returns a proxy mapping, binding the scrutinee
-- to the case binder, if possible
mkAltEnv env@(OccEnv { occ_gbl_scrut = pe }) scrut case_bndr
= case scrut of
Var v -> add_scrut v case_bndr'
Cast (Var v) co -> add_scrut v (Cast case_bndr' (mkSymCo co))
-- See Note [Case of cast]
_ -> (env { occ_encl = OccVanilla }, Nothing)
where
add_scrut v rhs = ( env { occ_encl = OccVanilla, occ_gbl_scrut = pe `extendVarSet` v }
, Just (localise v, rhs) )
case_bndr' = Var (zapIdOccInfo case_bndr) -- See Note [Zap case binders in proxy bindings]
localise scrut_var = mkLocalId (localiseName (idName scrut_var)) (idType scrut_var)
-- Localise the scrut_var before shadowing it; we're making a
-- new binding for it, and it might have an External Name, or
-- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
-- Also we don't want any INLINE or NOINLINE pragmas!
\end{code}
%************************************************************************
%* *
\subsection[OccurAnal-types]{OccEnv}
%* *
%************************************************************************
\begin{code}
type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
-- INVARIANT: never IAmDead
-- (Deadness is signalled by not being in the map at all)
(+++), combineAltsUsageDetails
:: UsageDetails -> UsageDetails -> UsageDetails
(+++) usage1 usage2
= plusVarEnv_C addOccInfo usage1 usage2
combineAltsUsageDetails usage1 usage2
= plusVarEnv_C orOccInfo usage1 usage2
addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
addOneOcc usage id info
= plusVarEnv_C addOccInfo usage (unitVarEnv id info)
-- ToDo: make this more efficient
emptyDetails :: UsageDetails
emptyDetails = (emptyVarEnv :: UsageDetails)
usedIn :: Id -> UsageDetails -> Bool
v `usedIn` details = isExportedId v || v `elemVarEnv` details
type IdWithOccInfo = Id
tagLamBinders :: UsageDetails -- Of scope
-> [Id] -- Binders
-> (UsageDetails, -- Details with binders removed
[IdWithOccInfo]) -- Tagged binders
-- Used for lambda and case binders
-- It copes with the fact that lambda bindings can have a
-- stable unfolding, used for join points
tagLamBinders usage binders = usage' `seq` (usage', bndrs')
where
(usage', bndrs') = mapAccumR tag_lam usage binders
tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
where
usage1 = usage `delVarEnv` bndr
usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
| otherwise = usage1
tagBinder :: UsageDetails -- Of scope
-> Id -- Binders
-> (UsageDetails, -- Details with binders removed
IdWithOccInfo) -- Tagged binders
tagBinder usage binder
= let
usage' = usage `delVarEnv` binder
binder' = setBinderOcc usage binder
in
usage' `seq` (usage', binder')
setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
setBinderOcc usage bndr
| isTyVar bndr = bndr
| isExportedId bndr = case idOccInfo bndr of
NoOccInfo -> bndr
_ -> setIdOccInfo bndr NoOccInfo
-- Don't use local usage info for visible-elsewhere things
-- BUT *do* erase any IAmALoopBreaker annotation, because we're
-- about to re-generate it and it shouldn't be "sticky"
| otherwise = setIdOccInfo bndr occ_info
where
occ_info = lookupVarEnv usage bndr `orElse` IAmDead
\end{code}
%************************************************************************
%* *
\subsection{Operations over OccInfo}
%* *
%************************************************************************
\begin{code}
mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
mkOneOcc env id int_cxt
| isLocalId id
= unitVarEnv id (OneOcc False True int_cxt)
| id `elemVarEnv` occ_gbl_scrut env
= unitVarEnv id NoOccInfo
| otherwise
= emptyDetails
markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
markMany _ = NoOccInfo
markInsideSCC occ = markInsideLam occ
-- inside an SCC, we can inline lambdas only.
markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
markInsideLam occ = occ
addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
addOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
NoOccInfo -- Both branches are at least One
-- (Argument is never IAmDead)
-- (orOccInfo orig new) is used
-- when combining occurrence info from branches of a case
orOccInfo (OneOcc in_lam1 _ int_cxt1)
(OneOcc in_lam2 _ int_cxt2)
= OneOcc (in_lam1 || in_lam2)
False -- False, because it occurs in both branches
(int_cxt1 && int_cxt2)
orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
NoOccInfo
\end{code}
| high | 0.395537 | 366 |
// (c) Copyright 1995-2017 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
// IP VLNV: k88k:user:my_multiplier:1.0
// IP Revision: 2
// The following must be inserted into your Verilog file for this
// core to be instantiated. Change the instance name and port connections
// (in parentheses) to your own signal names.
//----------- Begin Cut here for INSTANTIATION Template ---// INST_TAG
top_my_multiplier_0_0 your_instance_name (
.s00_axi_awaddr(s00_axi_awaddr), // input wire [3 : 0] s00_axi_awaddr
.s00_axi_awprot(s00_axi_awprot), // input wire [2 : 0] s00_axi_awprot
.s00_axi_awvalid(s00_axi_awvalid), // input wire s00_axi_awvalid
.s00_axi_awready(s00_axi_awready), // output wire s00_axi_awready
.s00_axi_wdata(s00_axi_wdata), // input wire [31 : 0] s00_axi_wdata
.s00_axi_wstrb(s00_axi_wstrb), // input wire [3 : 0] s00_axi_wstrb
.s00_axi_wvalid(s00_axi_wvalid), // input wire s00_axi_wvalid
.s00_axi_wready(s00_axi_wready), // output wire s00_axi_wready
.s00_axi_bresp(s00_axi_bresp), // output wire [1 : 0] s00_axi_bresp
.s00_axi_bvalid(s00_axi_bvalid), // output wire s00_axi_bvalid
.s00_axi_bready(s00_axi_bready), // input wire s00_axi_bready
.s00_axi_araddr(s00_axi_araddr), // input wire [3 : 0] s00_axi_araddr
.s00_axi_arprot(s00_axi_arprot), // input wire [2 : 0] s00_axi_arprot
.s00_axi_arvalid(s00_axi_arvalid), // input wire s00_axi_arvalid
.s00_axi_arready(s00_axi_arready), // output wire s00_axi_arready
.s00_axi_rdata(s00_axi_rdata), // output wire [31 : 0] s00_axi_rdata
.s00_axi_rresp(s00_axi_rresp), // output wire [1 : 0] s00_axi_rresp
.s00_axi_rvalid(s00_axi_rvalid), // output wire s00_axi_rvalid
.s00_axi_rready(s00_axi_rready), // input wire s00_axi_rready
.s00_axi_aclk(s00_axi_aclk), // input wire s00_axi_aclk
.s00_axi_aresetn(s00_axi_aresetn) // input wire s00_axi_aresetn
);
// INST_TAG_END ------ End INSTANTIATION Template ---------
| low | 0.706342 | 367 |
/* NHEA total spending by payer, 2002-2010
FAM Total spending, 2009-???
*/
clear all
set more off
include ../../fem_env.do
local tbl NHEA
insheet using "$nhea_dir/2010_Age_and_Gender/age and gender.csv", names
rename v5 y2002
rename v6 y2004
rename v7 y2006
rename v8 y2008
rename v9 y2010
forvalues x = 2002 (2) 2010 {
label var y`x' "`x' Spending (mil.)"
}
* For now, only interested in Total Personal Health Care
keep if service == "Total Personal Health Care"
drop service
* Only interested in both sexes
keep if gender == "Total"
drop gender
* Age groups are 0-18, 19-44, 45-64, 65-84, 85+, and "total" Only look at 45-64, 65-84, and 85+ for now
keep if inlist(agegroup,"19-44","45-64","65-84","85+")
outsheet using table`tbl'.csv, comma replace
export excel using techappendix.xlsx, sheetreplace sheet("Table `tbl'") firstrow(varlabels)
local tbl 10_14
* Baseline simulation results
use $output_dir/psid_baseline/psid_baseline_summary, replace
keep if year < 2050
local grp 2544 4564 6584 85p
local medvar t_totmd t_mcare t_caidmd
local i : word count `grp'
local j : word count `medvar'
forvalues x = 1/`j' {
forvalues y = 1/`i' {
local a : word `x' of `medvar'
local b : word `y' of `grp'
local c `a'_`b'
local vars `vars' `c'
}
}
foreach var of local vars {
replace `var' = `var'/1e6
}
keep year `vars'
outsheet using table`tbl'.csv, comma replace
export excel using techappendix.xlsx, sheetreplace sheet("Table `tbl'") firstrow(varlabels)
capture log close
| low | 0.205519 | 368 |
\begin{code}
module Scoped.Extrication where
\end{code}
\begin{code}
open import Data.Nat
open import Data.Nat.Properties
open import Data.Fin
open import Data.Vec
open import Function using (_∘_)
open import Data.Sum using (inj₁;inj₂)
open import Data.Product renaming (_,_ to _,,_)
open import Utils
open import Type
open import Type.BetaNormal
open import Type.BetaNBE.RenamingSubstitution
open import Algorithmic as A
open import Scoped
open import Builtin
import Builtin.Constant.Type Ctx⋆ (_⊢Nf⋆ *) as T
import Builtin.Constant.Type ℕ ScopedTy as S
open import Builtin.Constant.Term Ctx⋆ Kind * _⊢Nf⋆_ con as B
open import Type.BetaNormal
open import Type.RenamingSubstitution as T
\end{code}
type level
\begin{code}
len⋆ : Ctx⋆ → ℕ
len⋆ ∅ = zero
len⋆ (Γ ,⋆ K) = suc (len⋆ Γ)
extricateVar⋆ : ∀{Γ K}(A : Γ ∋⋆ K) → Fin (len⋆ Γ)
extricateVar⋆ Z = zero
extricateVar⋆ (S α) = suc (extricateVar⋆ α)
extricateNf⋆ : ∀{Γ K}(A : Γ ⊢Nf⋆ K) → ScopedTy (len⋆ Γ)
extricateNe⋆ : ∀{Γ K}(A : Γ ⊢Ne⋆ K) → ScopedTy (len⋆ Γ)
extricateTyConNf⋆ : ∀{Γ}(A : T.TyCon Γ) → S.TyCon (len⋆ Γ)
-- intrinsically typed terms should also carry user chosen names as
-- instructions to the pretty printer
extricateTyConNf⋆ T.integer = S.integer
extricateTyConNf⋆ T.bytestring = S.bytestring
extricateTyConNf⋆ T.string = S.string
extricateTyConNf⋆ T.unit = S.unit
extricateTyConNf⋆ T.bool = S.bool
extricateTyConNf⋆ (T.list A) = S.list (extricateNf⋆ A)
extricateTyConNf⋆ (T.pair A B) = S.pair (extricateNf⋆ A) (extricateNf⋆ B)
extricateTyConNf⋆ T.Data = S.Data
extricateNf⋆ (Π {K = K} A) = Π K (extricateNf⋆ A)
extricateNf⋆ (A ⇒ B) = extricateNf⋆ A ⇒ extricateNf⋆ B
extricateNf⋆ (ƛ {K = K} A) = ƛ K (extricateNf⋆ A)
extricateNf⋆ (ne n) = extricateNe⋆ n
extricateNf⋆ (con c) = con (extricateTyConNf⋆ c)
extricateNf⋆ (μ A B) = μ (extricateNf⋆ A) (extricateNf⋆ B)
extricateNe⋆ (` α) = ` (extricateVar⋆ α)
extricateNe⋆ (n · n') = extricateNe⋆ n · extricateNf⋆ n'
\end{code}
\begin{code}
len : ∀{Φ} → Ctx Φ → Weirdℕ (len⋆ Φ)
len ∅ = Z
len (Γ ,⋆ K) = T (len Γ)
len (Γ , A) = S (len Γ)
open import Relation.Binary.PropositionalEquality as Eq
extricateVar : ∀{Φ Γ}{A : Φ ⊢Nf⋆ *} → Γ ∋ A → WeirdFin (len Γ)
extricateVar Z = Z
extricateVar (S x) = S (extricateVar x)
extricateVar (T x) = T (extricateVar x)
extricateC : ∀{Γ}{A : Γ ⊢Nf⋆ *} → B.TermCon A → Utils.TermCon
extricateC (integer i) = integer i
extricateC (bytestring b) = bytestring b
extricateC (string s) = string s
extricateC (bool b) = bool b
extricateC unit = unit
extricateC (Data d) = Data d
open import Data.Product as P
open import Function hiding (_∋_)
extricateSub : ∀ {Γ Δ} → (∀ {J} → Δ ∋⋆ J → Γ ⊢Nf⋆ J)
→ Scoped.Tel⋆ (len⋆ Γ) (len⋆ Δ)
extricateSub {Δ = ∅} σ = []
extricateSub {Γ}{Δ ,⋆ K} σ =
Eq.subst (Scoped.Tel⋆ (len⋆ Γ))
(+-comm (len⋆ Δ) 1)
(extricateSub {Δ = Δ} (σ ∘ S) ++ Data.Vec.[ extricateNf⋆ (σ Z) ])
open import Data.List
lemma⋆ : ∀ b → len⋆ (proj₁ (ISIG b)) ≡ arity⋆ b
lemma⋆ addInteger = refl
lemma⋆ subtractInteger = refl
lemma⋆ multiplyInteger = refl
lemma⋆ divideInteger = refl
lemma⋆ quotientInteger = refl
lemma⋆ remainderInteger = refl
lemma⋆ modInteger = refl
lemma⋆ lessThanInteger = refl
lemma⋆ lessThanEqualsInteger = refl
lemma⋆ equalsInteger = refl
lemma⋆ appendByteString = refl
lemma⋆ lessThanByteString = refl
lemma⋆ lessThanEqualsByteString = refl
lemma⋆ sha2-256 = refl
lemma⋆ sha3-256 = refl
lemma⋆ verifySignature = refl
lemma⋆ equalsByteString = refl
lemma⋆ ifThenElse = refl
lemma⋆ appendString = refl
lemma⋆ trace = refl
lemma⋆ equalsString = refl
lemma⋆ encodeUtf8 = refl
lemma⋆ decodeUtf8 = refl
lemma⋆ fstPair = refl
lemma⋆ sndPair = refl
lemma⋆ nullList = refl
lemma⋆ headList = refl
lemma⋆ tailList = refl
lemma⋆ chooseList = refl
lemma⋆ constrData = refl
lemma⋆ mapData = refl
lemma⋆ listData = refl
lemma⋆ iData = refl
lemma⋆ bData = refl
lemma⋆ unConstrData = refl
lemma⋆ unMapData = refl
lemma⋆ unListData = refl
lemma⋆ unIData = refl
lemma⋆ unBData = refl
lemma⋆ equalsData = refl
lemma⋆ chooseData = refl
lemma⋆ chooseUnit = refl
lemma⋆ mkPairData = refl
lemma⋆ mkNilData = refl
lemma⋆ mkNilPairData = refl
lemma⋆ mkCons = refl
lemma⋆ consByteString = refl
lemma⋆ sliceByteString = refl
lemma⋆ lengthOfByteString = refl
lemma⋆ indexByteString = refl
lemma⋆ blake2b-256 = refl
lemma : ∀ b → wtoℕTm (len (proj₁ (proj₂ (ISIG b)))) ≡ Scoped.arity b
lemma addInteger = refl
lemma subtractInteger = refl
lemma multiplyInteger = refl
lemma divideInteger = refl
lemma quotientInteger = refl
lemma remainderInteger = refl
lemma modInteger = refl
lemma lessThanInteger = refl
lemma lessThanEqualsInteger = refl
lemma equalsInteger = refl
lemma appendByteString = refl
lemma lessThanByteString = refl
lemma lessThanEqualsByteString = refl
lemma sha2-256 = refl
lemma sha3-256 = refl
lemma verifySignature = refl
lemma equalsByteString = refl
lemma ifThenElse = refl
lemma appendString = refl
lemma trace = refl
lemma equalsString = refl
lemma encodeUtf8 = refl
lemma decodeUtf8 = refl
lemma fstPair = refl
lemma sndPair = refl
lemma nullList = refl
lemma headList = refl
lemma tailList = refl
lemma chooseList = refl
lemma constrData = refl
lemma mapData = refl
lemma listData = refl
lemma iData = refl
lemma bData = refl
lemma unConstrData = refl
lemma unMapData = refl
lemma unListData = refl
lemma unIData = refl
lemma unBData = refl
lemma equalsData = refl
lemma chooseData = refl
lemma chooseUnit = refl
lemma mkPairData = refl
lemma mkNilData = refl
lemma mkNilPairData = refl
lemma mkCons = refl
lemma consByteString = refl
lemma sliceByteString = refl
lemma lengthOfByteString = refl
lemma indexByteString = refl
lemma blake2b-256 = refl
≡2≤‴ : ∀{m n} → m ≡ n → m ≤‴ n
≡2≤‴ refl = ≤‴-refl
extricate : ∀{Φ Γ}{A : Φ ⊢Nf⋆ *} → Γ ⊢ A → ScopedTm (len Γ)
extricate (` x) = ` (extricateVar x)
extricate {Φ}{Γ} (ƛ {A = A} t) = ƛ (extricateNf⋆ A) (extricate t)
extricate (t · u) = extricate t · extricate u
extricate (Λ {K = K} t) = Λ K (extricate t)
extricate {Φ}{Γ} (_·⋆_ t A) = extricate t ScopedTm.·⋆ extricateNf⋆ A
extricate {Φ}{Γ} (wrap pat arg t) = wrap (extricateNf⋆ pat) (extricateNf⋆ arg)
(extricate t)
extricate (unwrap t) = unwrap (extricate t)
extricate (con c) = con (extricateC c)
extricate (ibuiltin b) = ibuiltin b
extricate {Φ}{Γ} (error A) = error (extricateNf⋆ A)
\end{code}
| high | 0.300623 | 369 |
/*
a 2 bit adder daisy chaining 2
1 bit adders
*/
module adder_2(a, b, c_in, sum, c_out);
input wire [1:0] a, b;
input wire c_in;
output logic [1:0] sum;
output logic c_out;
wire carry;
adder_1 ADDER_A(
.a(a[0]),
.b(b[0]),
.c_in(c_in),
.sum(sum[0]),
.c_out(carry)
);
adder_1 ADDER_B(
.a(a[1]),
.b(b[1]),
.c_in(carry),
.sum(sum[1]),
.c_out(c_out)
);
endmodule
| high | 0.490991 | 370 |
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:tuple/tuple.dart';
import '../models/documents/attribute.dart';
import '../models/documents/document.dart';
import '../models/documents/nodes/block.dart';
import '../models/documents/nodes/line.dart';
import 'controller.dart';
import 'cursor.dart';
import 'default_styles.dart';
import 'delegate.dart';
import 'editor.dart';
import 'keyboard_listener.dart';
import 'proxy.dart';
import 'raw_editor/raw_editor_state_keyboard_mixin.dart';
import 'raw_editor/raw_editor_state_selection_delegate_mixin.dart';
import 'raw_editor/raw_editor_state_text_input_client_mixin.dart';
import 'text_block.dart';
import 'text_line.dart';
import 'text_selection.dart';
class RawEditor extends StatefulWidget {
const RawEditor(
Key key,
this.controller,
this.focusNode,
this.scrollController,
this.scrollable,
this.scrollBottomInset,
this.padding,
this.readOnly,
this.placeholder,
this.onLaunchUrl,
this.toolbarOptions,
this.showSelectionHandles,
bool? showCursor,
this.cursorStyle,
this.textCapitalization,
this.maxHeight,
this.minHeight,
this.customStyles,
this.expands,
this.autoFocus,
this.selectionColor,
this.selectionCtrls,
this.keyboardAppearance,
this.enableInteractiveSelection,
this.scrollPhysics,
this.embedBuilder,
) : assert(maxHeight == null || maxHeight > 0, 'maxHeight cannot be null'),
assert(minHeight == null || minHeight >= 0, 'minHeight cannot be null'),
assert(maxHeight == null || minHeight == null || maxHeight >= minHeight,
'maxHeight cannot be null'),
showCursor = showCursor ?? true,
super(key: key);
final QuillController controller;
final FocusNode focusNode;
final ScrollController scrollController;
final bool scrollable;
final double scrollBottomInset;
final EdgeInsetsGeometry padding;
final bool readOnly;
final String? placeholder;
final ValueChanged<String>? onLaunchUrl;
final ToolbarOptions toolbarOptions;
final bool showSelectionHandles;
final bool showCursor;
final CursorStyle cursorStyle;
final TextCapitalization textCapitalization;
final double? maxHeight;
final double? minHeight;
final DefaultStyles? customStyles;
final bool expands;
final bool autoFocus;
final Color selectionColor;
final TextSelectionControls selectionCtrls;
final Brightness keyboardAppearance;
final bool enableInteractiveSelection;
final ScrollPhysics? scrollPhysics;
final EmbedBuilder embedBuilder;
@override
State<StatefulWidget> createState() => RawEditorState();
}
class RawEditorState extends EditorState
with
AutomaticKeepAliveClientMixin<RawEditor>,
WidgetsBindingObserver,
TickerProviderStateMixin<RawEditor>,
RawEditorStateKeyboardMixin,
RawEditorStateTextInputClientMixin,
RawEditorStateSelectionDelegateMixin {
final GlobalKey _editorKey = GlobalKey();
// Keyboard
late KeyboardListener _keyboardListener;
KeyboardVisibilityController? _keyboardVisibilityController;
StreamSubscription<bool>? _keyboardVisibilitySubscription;
bool _keyboardVisible = false;
// Selection overlay
@override
EditorTextSelectionOverlay? getSelectionOverlay() => _selectionOverlay;
EditorTextSelectionOverlay? _selectionOverlay;
ScrollController? _scrollController;
late CursorCont _cursorCont;
// Focus
bool _didAutoFocus = false;
FocusAttachment? _focusAttachment;
bool get _hasFocus => widget.focusNode.hasFocus;
DefaultStyles? _styles;
final ClipboardStatusNotifier _clipboardStatus = ClipboardStatusNotifier();
final LayerLink _toolbarLayerLink = LayerLink();
final LayerLink _startHandleLayerLink = LayerLink();
final LayerLink _endHandleLayerLink = LayerLink();
TextDirection get _textDirection => Directionality.of(context);
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
_focusAttachment!.reparent();
super.build(context);
var _doc = widget.controller.document;
if (_doc.isEmpty() &&
!widget.focusNode.hasFocus &&
widget.placeholder != null) {
_doc = Document.fromJson(jsonDecode(
'[{"attributes":{"placeholder":true},"insert":"${widget.placeholder}\\n"}]'));
}
Widget child = CompositedTransformTarget(
link: _toolbarLayerLink,
child: Semantics(
child: _Editor(
key: _editorKey,
document: _doc,
selection: widget.controller.selection,
hasFocus: _hasFocus,
textDirection: _textDirection,
startHandleLayerLink: _startHandleLayerLink,
endHandleLayerLink: _endHandleLayerLink,
onSelectionChanged: _handleSelectionChanged,
scrollBottomInset: widget.scrollBottomInset,
padding: widget.padding,
children: _buildChildren(_doc, context),
),
),
);
if (widget.scrollable) {
final baselinePadding =
EdgeInsets.only(top: _styles!.paragraph!.verticalSpacing.item1);
child = BaselineProxy(
textStyle: _styles!.paragraph!.style,
padding: baselinePadding,
child: SingleChildScrollView(
controller: _scrollController,
physics: widget.scrollPhysics,
child: child,
),
);
}
final constraints = widget.expands
? const BoxConstraints.expand()
: BoxConstraints(
minHeight: widget.minHeight ?? 0.0,
maxHeight: widget.maxHeight ?? double.infinity);
return QuillStyles(
data: _styles!,
child: MouseRegion(
cursor: SystemMouseCursors.text,
child: Container(
constraints: constraints,
child: child,
),
),
);
}
void _handleSelectionChanged(
TextSelection selection, SelectionChangedCause cause) {
widget.controller.updateSelection(selection, ChangeSource.LOCAL);
_selectionOverlay?.handlesVisible = _shouldShowSelectionHandles();
if (!_keyboardVisible) {
requestKeyboard();
}
}
/// Updates the checkbox positioned at [offset] in document
/// by changing its attribute according to [value].
void _handleCheckboxTap(int offset, bool value) {
if (!widget.readOnly) {
if (value) {
widget.controller.formatText(offset, 0, Attribute.checked);
} else {
widget.controller.formatText(offset, 0, Attribute.unchecked);
}
}
}
List<Widget> _buildChildren(Document doc, BuildContext context) {
final result = <Widget>[];
final indentLevelCounts = <int, int>{};
for (final node in doc.root.children) {
if (node is Line) {
final editableTextLine = _getEditableTextLineFromNode(node, context);
result.add(editableTextLine);
} else if (node is Block) {
final attrs = node.style.attributes;
final editableTextBlock = EditableTextBlock(
node,
_textDirection,
widget.scrollBottomInset,
_getVerticalSpacingForBlock(node, _styles),
widget.controller.selection,
widget.selectionColor,
_styles,
widget.enableInteractiveSelection,
_hasFocus,
attrs.containsKey(Attribute.codeBlock.key)
? const EdgeInsets.all(16)
: null,
widget.embedBuilder,
_cursorCont,
indentLevelCounts,
_handleCheckboxTap,
);
result.add(editableTextBlock);
} else {
throw StateError('Unreachable.');
}
}
return result;
}
EditableTextLine _getEditableTextLineFromNode(
Line node, BuildContext context) {
final textLine = TextLine(
line: node,
textDirection: _textDirection,
embedBuilder: widget.embedBuilder,
styles: _styles!,
);
final editableTextLine = EditableTextLine(
node,
null,
textLine,
0,
_getVerticalSpacingForLine(node, _styles),
_textDirection,
widget.controller.selection,
widget.selectionColor,
widget.enableInteractiveSelection,
_hasFocus,
MediaQuery.of(context).devicePixelRatio,
_cursorCont);
return editableTextLine;
}
Tuple2<double, double> _getVerticalSpacingForLine(
Line line, DefaultStyles? defaultStyles) {
final attrs = line.style.attributes;
if (attrs.containsKey(Attribute.header.key)) {
final int? level = attrs[Attribute.header.key]!.value;
switch (level) {
case 1:
return defaultStyles!.h1!.verticalSpacing;
case 2:
return defaultStyles!.h2!.verticalSpacing;
case 3:
return defaultStyles!.h3!.verticalSpacing;
default:
throw 'Invalid level $level';
}
}
return defaultStyles!.paragraph!.verticalSpacing;
}
Tuple2<double, double> _getVerticalSpacingForBlock(
Block node, DefaultStyles? defaultStyles) {
final attrs = node.style.attributes;
if (attrs.containsKey(Attribute.blockQuote.key)) {
return defaultStyles!.quote!.verticalSpacing;
} else if (attrs.containsKey(Attribute.codeBlock.key)) {
return defaultStyles!.code!.verticalSpacing;
} else if (attrs.containsKey(Attribute.indent.key)) {
return defaultStyles!.indent!.verticalSpacing;
}
return defaultStyles!.lists!.verticalSpacing;
}
@override
void initState() {
super.initState();
_clipboardStatus.addListener(_onChangedClipboardStatus);
widget.controller.addListener(() {
_didChangeTextEditingValue(widget.controller.ignoreFocusOnTextChange);
});
_scrollController = widget.scrollController;
_scrollController!.addListener(_updateSelectionOverlayForScroll);
_cursorCont = CursorCont(
show: ValueNotifier<bool>(widget.showCursor),
style: widget.cursorStyle,
tickerProvider: this,
);
_keyboardListener = KeyboardListener(
handleCursorMovement,
handleShortcut,
handleDelete,
);
if (defaultTargetPlatform == TargetPlatform.windows ||
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.linux ||
defaultTargetPlatform == TargetPlatform.fuchsia) {
_keyboardVisible = true;
} else {
_keyboardVisibilityController = KeyboardVisibilityController();
_keyboardVisible = _keyboardVisibilityController!.isVisible;
_keyboardVisibilitySubscription =
_keyboardVisibilityController?.onChange.listen((visible) {
_keyboardVisible = visible;
if (visible) {
_onChangeTextEditingValue();
}
});
}
_focusAttachment = widget.focusNode.attach(context,
onKey: (node, event) => _keyboardListener.handleRawKeyEvent(event));
widget.focusNode.addListener(_handleFocusChanged);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final parentStyles = QuillStyles.getStyles(context, true);
final defaultStyles = DefaultStyles.getInstance(context);
_styles = (parentStyles != null)
? defaultStyles.merge(parentStyles)
: defaultStyles;
if (widget.customStyles != null) {
_styles = _styles!.merge(widget.customStyles!);
}
if (!_didAutoFocus && widget.autoFocus) {
FocusScope.of(context).autofocus(widget.focusNode);
_didAutoFocus = true;
}
}
@override
void didUpdateWidget(RawEditor oldWidget) {
super.didUpdateWidget(oldWidget);
_cursorCont.show.value = widget.showCursor;
_cursorCont.style = widget.cursorStyle;
if (widget.controller != oldWidget.controller) {
oldWidget.controller.removeListener(_didChangeTextEditingValue);
widget.controller.addListener(_didChangeTextEditingValue);
updateRemoteValueIfNeeded();
}
if (widget.scrollController != _scrollController) {
_scrollController!.removeListener(_updateSelectionOverlayForScroll);
_scrollController = widget.scrollController;
_scrollController!.addListener(_updateSelectionOverlayForScroll);
}
if (widget.focusNode != oldWidget.focusNode) {
oldWidget.focusNode.removeListener(_handleFocusChanged);
_focusAttachment?.detach();
_focusAttachment = widget.focusNode.attach(context,
onKey: (node, event) => _keyboardListener.handleRawKeyEvent(event));
widget.focusNode.addListener(_handleFocusChanged);
updateKeepAlive();
}
if (widget.controller.selection != oldWidget.controller.selection) {
_selectionOverlay?.update(textEditingValue);
}
_selectionOverlay?.handlesVisible = _shouldShowSelectionHandles();
if (!shouldCreateInputConnection) {
closeConnectionIfNeeded();
} else {
if (oldWidget.readOnly && _hasFocus) {
openConnectionIfNeeded();
}
}
}
bool _shouldShowSelectionHandles() {
return widget.showSelectionHandles &&
!widget.controller.selection.isCollapsed;
}
@override
void dispose() {
closeConnectionIfNeeded();
_keyboardVisibilitySubscription?.cancel();
assert(!hasConnection);
_selectionOverlay?.dispose();
_selectionOverlay = null;
widget.controller.removeListener(_didChangeTextEditingValue);
widget.focusNode.removeListener(_handleFocusChanged);
_focusAttachment!.detach();
_cursorCont.dispose();
_clipboardStatus
..removeListener(_onChangedClipboardStatus)
..dispose();
super.dispose();
}
void _updateSelectionOverlayForScroll() {
_selectionOverlay?.markNeedsBuild();
}
void _didChangeTextEditingValue([bool ignoreFocus = false]) {
if (kIsWeb) {
_onChangeTextEditingValue(ignoreFocus);
if (!ignoreFocus) {
requestKeyboard();
}
return;
}
if (ignoreFocus || _keyboardVisible) {
_onChangeTextEditingValue(ignoreFocus);
} else {
requestKeyboard();
if (mounted) {
setState(() {
// Use widget.controller.value in build()
// Trigger build and updateChildren
});
}
}
}
void _onChangeTextEditingValue([bool ignoreCaret = false]) {
updateRemoteValueIfNeeded();
if (ignoreCaret) {
return;
}
_showCaretOnScreen();
_cursorCont.startOrStopCursorTimerIfNeeded(
_hasFocus, widget.controller.selection);
if (hasConnection) {
_cursorCont
..stopCursorTimer(resetCharTicks: false)
..startCursorTimer();
}
SchedulerBinding.instance!.addPostFrameCallback(
(_) => _updateOrDisposeSelectionOverlayIfNeeded());
if (mounted) {
setState(() {
// Use widget.controller.value in build()
// Trigger build and updateChildren
});
}
}
void _updateOrDisposeSelectionOverlayIfNeeded() {
if (_selectionOverlay != null) {
if (_hasFocus) {
_selectionOverlay!.update(textEditingValue);
} else {
_selectionOverlay!.dispose();
_selectionOverlay = null;
}
} else if (_hasFocus) {
_selectionOverlay?.hide();
_selectionOverlay = null;
_selectionOverlay = EditorTextSelectionOverlay(
textEditingValue,
false,
context,
widget,
_toolbarLayerLink,
_startHandleLayerLink,
_endHandleLayerLink,
getRenderEditor(),
widget.selectionCtrls,
this,
DragStartBehavior.start,
null,
_clipboardStatus,
);
_selectionOverlay!.handlesVisible = _shouldShowSelectionHandles();
_selectionOverlay!.showHandles();
}
}
void _handleFocusChanged() {
openOrCloseConnection();
_cursorCont.startOrStopCursorTimerIfNeeded(
_hasFocus, widget.controller.selection);
_updateOrDisposeSelectionOverlayIfNeeded();
if (_hasFocus) {
WidgetsBinding.instance!.addObserver(this);
_showCaretOnScreen();
} else {
WidgetsBinding.instance!.removeObserver(this);
}
updateKeepAlive();
}
void _onChangedClipboardStatus() {
if (!mounted) return;
setState(() {
// Inform the widget that the value of clipboardStatus has changed.
// Trigger build and updateChildren
});
}
bool _showCaretOnScreenScheduled = false;
void _showCaretOnScreen() {
if (!widget.showCursor || _showCaretOnScreenScheduled) {
return;
}
_showCaretOnScreenScheduled = true;
SchedulerBinding.instance!.addPostFrameCallback((_) {
if (widget.scrollable) {
_showCaretOnScreenScheduled = false;
final viewport = RenderAbstractViewport.of(getRenderEditor());
final editorOffset = getRenderEditor()!
.localToGlobal(const Offset(0, 0), ancestor: viewport);
final offsetInViewport = _scrollController!.offset + editorOffset.dy;
final offset = getRenderEditor()!.getOffsetToRevealCursor(
_scrollController!.position.viewportDimension,
_scrollController!.offset,
offsetInViewport,
);
if (offset != null) {
_scrollController!.animateTo(
offset,
duration: const Duration(milliseconds: 100),
curve: Curves.fastOutSlowIn,
);
}
}
});
}
@override
RenderEditor? getRenderEditor() {
return _editorKey.currentContext!.findRenderObject() as RenderEditor?;
}
@override
TextEditingValue getTextEditingValue() {
return widget.controller.plainTextEditingValue;
}
@override
void requestKeyboard() {
if (_hasFocus) {
openConnectionIfNeeded();
} else {
widget.focusNode.requestFocus();
}
}
@override
void setTextEditingValue(TextEditingValue value) {
if (value.text == textEditingValue.text) {
widget.controller.updateSelection(value.selection, ChangeSource.LOCAL);
} else {
__setEditingValue(value);
}
}
Future<void> __setEditingValue(TextEditingValue value) async {
if (await __isItCut(value)) {
widget.controller.replaceText(
textEditingValue.selection.start,
textEditingValue.text.length - value.text.length,
'',
value.selection,
);
} else {
final value = textEditingValue;
final data = await Clipboard.getData(Clipboard.kTextPlain);
if (data != null) {
final length =
textEditingValue.selection.end - textEditingValue.selection.start;
widget.controller.replaceText(
value.selection.start,
length,
data.text,
value.selection,
);
// move cursor to the end of pasted text selection
widget.controller.updateSelection(
TextSelection.collapsed(
offset: value.selection.start + data.text!.length),
ChangeSource.LOCAL);
}
}
}
Future<bool> __isItCut(TextEditingValue value) async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
if (data == null) {
return false;
}
return textEditingValue.text.length - value.text.length ==
data.text!.length;
}
@override
bool showToolbar() {
// Web is using native dom elements to enable clipboard functionality of the
// toolbar: copy, paste, select, cut. It might also provide additional
// functionality depending on the browser (such as translate). Due to this
// we should not show a Flutter toolbar for the editable text elements.
if (kIsWeb) {
return false;
}
if (_selectionOverlay == null || _selectionOverlay!.toolbar != null) {
return false;
}
_selectionOverlay!.update(textEditingValue);
_selectionOverlay!.showToolbar();
return true;
}
@override
bool get wantKeepAlive => widget.focusNode.hasFocus;
@override
void userUpdateTextEditingValue(
TextEditingValue value, SelectionChangedCause cause) {
// TODO: implement userUpdateTextEditingValue
}
}
class _Editor extends MultiChildRenderObjectWidget {
_Editor({
required Key key,
required List<Widget> children,
required this.document,
required this.textDirection,
required this.hasFocus,
required this.selection,
required this.startHandleLayerLink,
required this.endHandleLayerLink,
required this.onSelectionChanged,
required this.scrollBottomInset,
this.padding = EdgeInsets.zero,
}) : super(key: key, children: children);
final Document document;
final TextDirection textDirection;
final bool hasFocus;
final TextSelection selection;
final LayerLink startHandleLayerLink;
final LayerLink endHandleLayerLink;
final TextSelectionChangedHandler onSelectionChanged;
final double scrollBottomInset;
final EdgeInsetsGeometry padding;
@override
RenderEditor createRenderObject(BuildContext context) {
return RenderEditor(
null,
textDirection,
scrollBottomInset,
padding,
document,
selection,
hasFocus,
onSelectionChanged,
startHandleLayerLink,
endHandleLayerLink,
const EdgeInsets.fromLTRB(4, 4, 4, 5),
);
}
@override
void updateRenderObject(
BuildContext context, covariant RenderEditor renderObject) {
renderObject
..document = document
..setContainer(document.root)
..textDirection = textDirection
..setHasFocus(hasFocus)
..setSelection(selection)
..setStartHandleLayerLink(startHandleLayerLink)
..setEndHandleLayerLink(endHandleLayerLink)
..onSelectionChanged = onSelectionChanged
..setScrollBottomInset(scrollBottomInset)
..setPadding(padding);
}
}
| high | 0.711783 | 371 |
namespace Indigo;
interface
uses
System.Drawing,
System.Collections,
System.Collections.Generic,
System.Linq,
System.Windows.Forms,
System.ComponentModel,
System.ServiceModel, System.ServiceModel.Description;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = partial class(System.Windows.Forms.Form)
private
method bGetServerTime_Click(sender: System.Object; e: System.EventArgs);
method bArithm_Click(sender: System.Object; e: System.EventArgs);
method InitChannel();
var
factory : ChannelFactory<IndigoServiceChannel>;
proxy : IndigoServiceChannel;
endpointChanged : Boolean;
method comboBoxEndpoints_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
protected
method Dispose(disposing: Boolean); override;
public
constructor;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
comboBoxEndpoints.SelectedIndex := 0;
end;
method MainForm.Dispose(disposing: Boolean);
begin
if disposing then begin
if assigned(components) then
components.Dispose();
//
// TODO: Add custom disposition code here
//
end;
inherited Dispose(disposing);
end;
{$ENDREGION}
method MainForm.bGetServerTime_Click(sender: System.Object; e: System.EventArgs);
begin
InitChannel;
MessageBox.Show("Server time is: " + proxy.GetServerTime().ToString() + Environment.NewLine + "Invoked endpoint: " + factory.Endpoint.Name);
end;
method MainForm.bArithm_Click(sender: System.Object; e: System.EventArgs);
var responce : CalculationMessage := new CalculationMessage();
operation : Char; Res : Decimal;
begin
if (radioButtonPlus.Checked) then operation := '+'
else
if (radioButtonMinus.Checked) then operation := '-'
else
if (radioButtonMult.Checked) then operation := '*'
else
if (radioButtonDiv.Checked) then operation := '/';
var numbers : Operands := new Operands;
numbers.operand1 := nudA.Value; numbers.operand2 := nudB.Value;
var request : CalculationMessage := new CalculationMessage(operation, numbers, Res);
InitChannel;
responce := proxy.Calculate(request);
MessageBox.Show("Result: " + responce.Res.ToString() + Environment.NewLine + "Invoked endpoint: " + factory.Endpoint.Name);
end;
method MainForm.InitChannel;
begin
if (endpointChanged) then
begin
factory := new ChannelFactory<IndigoServiceChannel>(comboBoxEndpoints.SelectedItem.ToString);
proxy := factory.CreateChannel();
endpointChanged := false;
end;
end;
method MainForm.comboBoxEndpoints_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
begin
endpointChanged := true;
end;
end. | medium | 0.472976 | 372 |
#!/bin/tcsh
cd $WEEKLYBLD
# this scripts starts the main gbib VM on hgwdev, creates an ssh key on it, adds this key to the build account
# the triggers an update on the box using the build account
# it finally cleans the VM, stops and zips it into gbibBeta.zip
# make sure that the keys are always removed if this script somehow breaks
echo cleaning keys;
sed -i '/browserbox/d' ~/.ssh/authorized_keys
# start the box
echo "start the box"
set runCount=`VBoxManage list runningvms | grep -c '"browserbox"'`
#echo "runCount=$runCount"
if ( "$runCount" == "0" ) then
#VBoxHeadless -s browserbox &
VBoxManage startvm "browserbox" --type headless
sleep 15
while ( 1 )
set runCount=`VBoxManage list runningvms | grep -c '"browserbox"'`
#echo "runCount=$runCount"
if ( "$runCount" == "1" ) then
break
endif
echo "waiting for vm browserbox to start"
sleep 15
end
endif
echo logging into box and creating new public key
ssh box 'sudo shred -n 1 -zu /root/.ssh/{id_dsa,id_dsa.pub}; cat /dev/zero | sudo ssh-keygen -t dsa -f /root/.ssh/id_dsa -N ""'
echo adding the new key to the build key file on hgwdev
ssh box sudo cat /root/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys
#check if an rsync update is still running
# because after starting up the box it
# may automatically rsync if it has not been run for weeks.
while ( 1 )
set rsyncCount=`ssh box ps -ef | grep -c rsync`
#echo "rsyncCount=$rsyncCount"
if ( "$rsyncCount" == "0" ) then
break
endif
sleep 15
end
echo logging into box and starting the update process via the build account
ssh box sudo /root/updateBrowser.sh hgwdev build beta
echo removing key from build key file and from box
ssh box 'sudo shred -n 1 -zu /root/.ssh/{id_dsa,id_dsa.pub}'
sed -i '/browserbox/d' ~/.ssh/authorized_keys
echo running boxRelease
./boxRelease.csh beta
echo copying gbibBeta.zip to gbibV${BRANCHNN}.zip
cp -p /usr/local/apache/htdocs/gbib/gbibBeta.zip /hive/groups/browser/vBox/gbibV${BRANCHNN}.zip
| low | 0.520225 | 373 |
{
"id": "9fae3c8e-76b5-46df-8ac9-2a4725280d7c",
"modelName": "GMNotes",
"mvc": "1.0",
"name": "Limitations"
} | low | 0.812178 | 374 |
rem start with "cscript Mandelbrot.vbs"
start = Timer
disp_width = 800 + 1
disp_height = 250 + 1
scale_real = 3.0 / disp_width
scale_imag = 3.0 / disp_height
matrix = ""
line = ""
for j = 1 to disp_height
y = (j * scale_imag) - 1.5
line = ""
for i = 1 to disp_width
x = (i * scale_real) - 1.8
u = 0.0
v = 0.0
u2 = 0.0
v2 = 0.0
iter = 0
while (u2 + v2 < 4.0) And (iter < 100)
v = 2 * v * u + y
u = u2 - v2 + x
u2 = u*u
v2 = v*v
iter = iter + 1
wend
if 80 < iter then
c = "*"
else
if 50 < iter then
c = "0"
else
if 20 < iter then
c = "."
else
c = " "
end if
end if
end if
line = line & c
next
'Matrix = Matrix + line + vbCrLf
line = ""
next
ende = Timer
'Wscript.Echo Matrix + vbCrLf + "Laufzeit : " & ende - start
pixel_per_s = (disp_width-1) * (disp_height-1) / ((ende - start)*1000)
msgbox "Laufzeit : " & ende - start & "; " & pixel_per_s & "KPixel/s"
| high | 0.278482 | 375 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* This file was auto-generated using specs and scripts in the db-schema
* repository. DO NOT EDIT DIRECTLY.
*/
package com.microsoft.research.karya.database.daos
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import com.microsoft.research.karya.database.models.PolicyRecord
@Dao
interface PolicyDao : BasicDao<PolicyRecord> {
@Query("SELECT * FROM policy")
suspend fun getAll(): List<PolicyRecord>
@Query("SELECT * FROM policy WHERE id == :id")
suspend fun getById(id: Int): PolicyRecord
/**
* Upsert a [record] in the table
*/
@Transaction
suspend fun upsert(record: PolicyRecord) {
insertForUpsert(record)
updateForUpsert(record)
}
/**
* Upsert a list of [records] in the table
*/
@Transaction
suspend fun upsert(records: List<PolicyRecord>) {
insertForUpsert(records)
updateForUpsert(records)
}
}
| high | 0.797766 | 376 |
%% LyX 2.1.4 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{jfp1}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{babel}
\usepackage{varioref}
\usepackage{textcomp}
\usepackage{graphicx}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
\usepackage{amsfonts}
\usepackage{bm}
\usepackage{mathptmx}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\usepackage{verbatim}
\newenvironment{code}{\verbatim}{\endverbatim}
%include polycode.fmt
\makeatother
\begin{document}
\author{David Spies}
\title{A list-based Sieve of Eratosthenes}
\maketitle
\begin{abstract}
We introduce a Sieve of Eratosthenes in Haskell which produces an
infinite list of prime numbers, and achieves $O\left(n\log n\log\log n\right)$
performance without making use of \emph{any} data structure besides
infinite lists.
\end{abstract}
\section{Introduction}
In ``The Genuine Sieve of Eratosthenes'' \cite{o2009genuine}, they
refute the claim that a well-known Haskell one-liner for generating
a list of prime numbers is an implementation of the Sieve of Eratosthenes
and show that its computaitonal behavior is fundamentally different
(not to mention significantly slower). They then go on to produce
an actual implementation making use first of binary-tree-based maps
and later of queues claiming:
\begin{quote}
An implementation of the actual sieve has its own elegance, showing
the utility of well-known data structures over the simplicity of lists
{[}...{]} choosing the right data structure for the problem at hand
{[}can make{]} an order of magnitude performance difference.
\end{quote}
Here, we produce an implementation of the Sieve of Eratosthenes which
\emph{is} computationally similar to O'Neill's in that it has the
same big-$O$ performance and ultimately works by merging together
streams of composites and then excluding them from a base-list. But
it does so without ever making explicit use of any data-structure
besides infinite lists. The heap which merges together lists of composites
is implicitly built into the way the function calls which generate
these lists are structured rather than being encoded explicitly as
data.
\subsection{Literate Haskell}
This document (or rather \texttt{primes.lhs}, the \LaTeX{} file used
to generate this document) is literate Haskell. It has been tested
on GHC 8.2.2. To compile it we will need a main method. We can take
a positive number $n$ as the sole command line argument print out
the $n^{\mbox{th}}$ prime by indexing into the infinite list of primes,\texttt{
primes }\vpageref{primescomposites}: \label{sub:main-method}
\begin{code}
import System.Environment (getArgs)
main :: IO ()
main = do
[ind] <- map read <$> getArgs
print $ primes !! (ind - 1)
\end{code}
To run it, try:
\begin{verbatim}
$ ghc -O2 primes.lhs
$ ./primes 1000000
15485863
\end{verbatim}
Finding the millionth prime takes about 7 seconds on an Intel Core\texttrademark{}
i5-4200M CPU.
Additionally, ``\texttt{ghci -i primes.lhs}'' can be used to otherwise
play with the various functions and structures defined in this paper.
\section{Merging Lists}
All lists used in this document are infinite and sorted. All lists
of lists are infinite and sorted on their heads. When dealing with
sorted lists, it is useful to have a merge function.
\begin{code}
merge :: Ord a => [a] -> [a] -> [a]
merge (x : xs) (y : ys)
| y < x = y : merge (x : xs) ys
| otherwise = x : merge xs (y : ys)
\end{code}
This takes two sorted lists and merges them into a single sorted list.
Note that evaluating the head of the result triggers the evaluation
of both arguments' heads. Instead of this merge function, we will
need one which prepends the head of the left list before merging the
remainder with the right list. If we can prove via some \emph{other}
means that the head of the left input is less than the head of the
right, then this will return the same result as just calling \texttt{merge}.
But obtaining the head of the result won't require any evaluation
of the right argument.
\begin{code}
fmerge :: Ord a => [a] -> [a] -> [a]
fmerge (x : xs) ys = x : merge xs ys
\end{code}
To see how this might be useful, here is an ordered list of all numbers
whose only prime factors are 2 and 3:
\begin{code}
twosThreesOnly :: [Integer]
twosThreesOnly = fmerge (iterate (2 *) 1) [3 * x | x <- twosThreesOnly]
\end{code}
Were we to define it using \texttt{merge} rather than \texttt{fmerge},
attempting to evaluate \texttt{twosThreesOnly} would simply cause
our program to loop forever unable to determine the recursively-defined
first element.
\texttt{fmerge} can \emph{also} be used to merge an infinite list
of sorted lists, provided we know the heads of the lists are already
sorted.
\begin{code}
fmergeAllNaive :: Ord a => [[a]] -> [a]
fmergeAllNaive (x : xs) = fmerge x (fmergeAllNaive xs)
\end{code}
This works and uses an impressively small amount of code, but theoretically
is not very performant. In the worst case, evaluating the $k$th element
can require $\Omega\left(k\right)$ running time. To see why this
is, take a look at what structure results from evaluating \texttt{fmergeAllNaive}
on a list. Suppose we have the list:
\begin{verbatim}
xs = x1 : x2 : x3 : x4 : ...
\end{verbatim}
When we call \texttt{fmergeAllNaive xs}, the resulting structure looks
something like Figure \ref{fig:fmergeallnaive}.
\begin{figure}
\caption{\label{fig:fmergeallnaive}Structure of \texttt{fmergeAllNaive}}
\includegraphics[height=0.3\textheight]{images/fig1}
\end{figure}
If an element belongs to list $x_{k}$, then to ``bubble up'' to
the top of our evaluation structure, it must be compared against the
first element of $x_{k-1}$, followed by the first element of $x_{k-2}$
etc. until finally being compared against $x_{1}$.
To rectify this, we will first create a helper function for efficiently
merging \emph{just the length-$k$ prefix} of a list of lists (where
$k>0$). The \texttt{fmergePrefix} function returns both the merged
prefix and the unmerged remainder. As before, we assume the heads
of the lists are themselves already sorted.
\begin{code}
fmergePrefix :: Ord a => Int -> [[a]] -> ([a], [[a]])
fmergePrefix 1 (x : xs) = (x, xs)
fmergePrefix k xs = (fmerge y z, zs)
where
(y, ys) = fmergePrefix (k `quot` 2) xs
(z, zs) = fmergePrefix ((k + 1) `quot` 2) ys
\end{code}
This should look familliarly like a standard merge-sort, except that
we're using \texttt{fmerge} rather than \texttt{merge} (and all our
lists are infinite).
Notice that evaluating the first $n$ elements of the resulting merged
prefix requires at most $O\left(n\log k\right)$ steps as any element
needs to be compared with at most $\log_{2}k$ others to bubble to
the top. Now here is a more efficient \texttt{fmergeAll} implementation
which makes use of \texttt{fmergePrefix}.
\begin{code}
fmergeAll :: Ord a => [[a]] -> [a]
fmergeAll = go 1
where
go k xs = let (ys, zs) = fmergePrefix k xs in fmerge ys (go (k * 2) zs)
\end{code}
\texttt{fmergeAll} is quite similar to \texttt{fmergeAllNaive} except
that instead of merging lists together one at a time, we merge them
in batches of exponentially growing size. Each batch is efficiently
merged using \texttt{fmergePrefix}. A consequence is that any element
from the $k^{\mbox{th}}$ list needs to be compared with at most $O\left(\log k\right)$
elements to bubble to the top of the resulting structure of thunks
(see Figure \ref{fig:fmergeall}).
\begin{figure}
\caption{\label{fig:fmergeall}Structure of \texttt{fmergeAll}}
\includegraphics[height=0.3\textheight]{images/fig2}
\end{figure}
\section{Excluding From a List}
In addition to merging lists, it will also be useful to \emph{exclude}
elements from a list. The implementation is straightforward.
\begin{code}
excluding :: Ord a => [a] -> [a] -> [a]
(x : xs) `excluding` (y : ys) = case compare x y of
LT -> x : (xs `excluding` (y : ys))
EQ -> xs `excluding` ys
GT -> (x : xs) `excluding` ys
\end{code}
\section{Primes and Composites}
With this in hand, we can mutually recursively define two lists: \texttt{primes}
and \texttt{composites} which respectively are lists of all the prime
and composite integers. The composites are the merged multiples of
the prime numbers. Note that if we start from the square of each prime,
then any composite number $n$ will occur once in the composites list
for each of its prime factors $p\le\sqrt{n}$ (every composite number
must have such a factor). The primes are then just the list of all
numbers larger than $1$ excluding the composites. The number $2$
is explicitly given as the head of the list to avoid infinite looping
to find the head of the list at runtime. \label{primescomposites}
\begin{code}
primes :: [Integer]
primes = 2 : ([3..] `excluding` composites)
composites :: [Integer]
composites = fmergeAll [[p * p, p * (p + 1)..] | p <- primes]
\end{code}
Since the list of primes is in ascending order and the operation of
squaring is monotonic on positive integers, we can be sure that the
heads of the composite lists to be merged are also in ascending order.
Thus it is safe to use \texttt{fmergeAll} here for merging together
all the lists of composites.
\section{Rolling The Wheel}
In \cite{o2009genuine} they additionally show how to build a ``wheel''
sieve by skipping multiples of the smallest (and hence most common)
primes. We can do the same with the list-based version. First, observe
how we can ignore all the even numbers in our computation:
\begin{code}
oddPrimes :: [Integer]
oddPrimes = 3 : ([5,7..] `excluding` oddComposites)
oddComposites :: [Integer]
oddComposites = fmergeAll [[p * p, p * (p + 2)..] | p <- primes]
primes2 :: [Integer]
primes2 = 2 : oddPrimes
\end{code}
Re-running with \texttt{primes} changed to \texttt{primes2} in the
main method \vpageref{sub:main-method} gives us the millionth prime
in only 3.5 seconds. Nearly exactly half of what it costs using the
straightforward sieve.
To ignore multiples of 3 as well, we start with the list of prime
\texttt{candidates} and then filter out the composites based on those.
\begin{code}
wheelCandidates :: [Integer]
wheelCandidates = 5 : concat [[n + 1, n + 5] | n <- [6, 12..]]
wheelPrimes :: [Integer]
wheelPrimes = 5 : (tail wheelCandidates) `excluding` wheelComposites
wheelComposites :: [Integer]
wheelComposites =
fmergeAll [[p * k | k <- dropWhile (< p) wheelCandidates]
| p <- wheelPrimes]
primes3 :: [Integer]
primes3 = 2 : 3 : wheelPrimes
\end{code}
And by changing \texttt{primes} to \texttt{primes3} we observe an
almost-negligible speedup from 3.5 to 3.3 seconds to find the millionth
prime. Perhaps a greater speedup could be obtained by replacing the
\texttt{dropWhile} above with a direct computation of the first term
for each list or by finding a way to generate successive composites
by addition rather than multiplication as is done in the \texttt{primes}
and \texttt{primes2} case.
\bibliographystyle{jfp}
\bibliography{primes}
\end{document}
| high | 0.899482 | 377 |
transformed data {
array[2] vector[2] y;
vector[2] mu0;
matrix[2, 2] sigma;
y[1, 1] = 40000.0;
y[1, 2] = 30000.0;
y[2, 1] = 30000.0;
y[2, 2] = 20000.0;
mu0[1] = 0.0;
mu0[2] = 0.0;
sigma[1, 1] = 10000.0;
sigma[1, 2] = 00000.0;
sigma[2, 1] = 00000.0;
sigma[2, 2] = 10000.0;
}
parameters {
vector[2] mu;
}
model {
mu ~ multi_normal(mu0, sigma);
for (n in 1 : 2)
y[n] ~ multi_normal(mu, sigma);
}
| high | 0.302152 | 378 |
html{font-size:16px}#banner img{max-width:70%}#banner .titulo{margin-top:0;width:auto;margin-left:0}#banner .folha{top:52%}#conheca{background-image:url(./assets/img/bg-malha.png);background-repeat:no-repeat;background-position:calc(50% - 1050px) 700px}#conheca .familia{margin-top:0}#conheca h2{margin-top:0}#conheca .ico-casa{max-width:28rem;font-size:1rem}#conheca .vista-aerea{margin-top:-4rem}#conheca .vista-aerea .selo{width:11.5rem}#conheca .vista-aerea .foto{border:1rem #fff solid}#conheca .folha{left:-1%}#natureza{padding-bottom:5rem}#natureza h2{font-size:1.6rem}#natureza h2 span{font-size:4.5rem;left:8.4rem;top:calc(100% + 1.9rem)}#natureza .conteudo{margin-top:2rem;margin-left:-3rem;font-size:1rem}#natureza .btn{margin-top:2rem}#natureza .folha{top:50%;left:85%;width:15%}#mapa{margin-top:-8rem}#mapa .conteudo{width:auto;padding:0;font-size:1.5rem;line-height:auto;margin:0;margin-top:11rem}#mapa .conteudo span{font-size:4.6rem;left:0}#itens .bloco{width:30%}#itens .bloco img{bottom:-4.5rem}#contato .folha{top:-10rem;left:-35%;width:439px;height:390px;background-position:right top;background-image:url(./assets/img/folha-04.png)} | high | 0.315317 | 379 |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import getpass
import socket
import datetime
import logging
import subprocess
from collections import defaultdict
import pprint
import fnmatch
import concurrent.futures
import six
import pytest
import requests
from _pytest.runner import pytest_runtest_makereport as _makereport
LOGGER = logging.getLogger("elk-reporter")
def pytest_runtest_makereport(item, call):
report = _makereport(item, call)
report.keywords = list([m.name for m in item.iter_markers()])
return report
def pytest_addoption(parser):
group = parser.getgroup("elk-reporter")
group.addoption(
"--es-address",
action="store",
dest="es_address",
default=None,
help="Elasticsearch address",
)
group.addoption(
"--es-username",
action="store",
dest="es_username",
default=None,
help="Elasticsearch username",
)
group.addoption(
"--es-password",
action="store",
dest="es_password",
default=None,
help="Elasticsearch password",
)
group.addoption(
"--es-timeout",
action="store",
dest="es_timeout",
default=10,
help="Elasticsearch connection timeout",
)
group.addoption(
"--es-slices",
action="store_true",
dest="es_slices",
default=False,
help="Splice collected tests base on history data",
)
group.addoption(
"--es-max-splice-time",
action="store",
type=float,
dest="es_max_splice_time",
default=60,
help="Max duration of each splice, in minutes",
)
group.addoption(
"--es-default-test-time",
action="store",
type=float,
dest="es_default_test_time",
default=120,
help="Default time for a test, if history isn't found for it, in seconds",
)
parser.addini("es_address", help="Elasticsearch address", default=None)
parser.addini("es_username", help="Elasticsearch username", default=None)
parser.addini("es_password", help="Elasticsearch password", default=None)
parser.addini(
"es_index_name",
help="name of the elasticsearch index to save results to",
default="test_data",
)
def pytest_configure(config):
# prevent opening elk-reporter on slave nodes (xdist)
if not hasattr(config, "slaveinput"):
config.elk = ElkReporter(config)
config.elk.es_index_name = config.getini("es_index_name")
config.pluginmanager.register(config.elk, "elk-reporter-runtime")
def pytest_unconfigure(config):
elk = getattr(config, "elk", None)
if elk:
del config.elk
config.pluginmanager.unregister(elk)
def get_username():
try:
return getpass.getuser()
except ImportError:
try:
return os.getlogin()
except Exception: # pylint: disable=broad-except
# seems like there are case we can't get the name of the user that is currently running
LOGGER.warning(
"couldn't figure out which user is currently running setting to 'unknown'"
)
LOGGER.warning(
"see https://docs.python.org/3/library/getpass.html#getpass.getuser, "
"if you want to configure it correctly"
)
return "unknown"
class ElkReporter(object): # pylint: disable=too-many-instance-attributes
def __init__(self, config):
self.es_address = config.getoption("es_address") or config.getini("es_address")
self.es_username = config.getoption("es_username") or config.getini(
"es_username"
)
self.es_password = config.getoption("es_password") or config.getini(
"es_password"
)
self.es_index_name = config.getini("es_index_name")
self.es_timeout = config.getoption("es_timeout")
self.es_max_splice_time = config.getoption("es_max_splice_time")
self.es_default_test_time = config.getoption("es_default_test_time")
self.slices_query_fmt = '(name:"{}") AND (outcome: passed)'
self.stats = dict.fromkeys(
[
"error",
"passed",
"failure",
"skipped",
"xfailed",
"xpass",
"passed & error",
"failure & error",
"skipped & error",
"error & error",
],
0,
)
self.session_data = dict(username=get_username(), hostname=socket.gethostname())
self.test_data = defaultdict(dict)
self.reports = {}
self.config = config
@property
def es_auth(self):
return self.es_username, self.es_password
@property
def es_url(self):
if self.es_address.startswith("http"):
return "{0.es_address}".format(self)
return "http://{0.es_address}".format(self)
def append_test_data(self, request, test_data):
self.test_data[request.node.nodeid].update(**test_data)
def cache_report(self, report_item, outcome):
nodeid = getattr(report_item, "nodeid", report_item)
# local hack to handle xdist report order
slavenode = getattr(report_item, "node", None)
self.reports[nodeid, slavenode] = (report_item, outcome)
def get_report(self, report_item):
nodeid = getattr(report_item, "nodeid", report_item)
# local hack to handle xdist report order
slavenode = getattr(report_item, "node", None)
return self.reports.get((nodeid, slavenode), None)
@staticmethod
def get_failure_messge(item_report):
if hasattr(item_report, "longreprtext"):
message = item_report.longreprtext
elif hasattr(item_report.longrepr, "reprcrash"):
message = item_report.longrepr.reprcrash.message
elif isinstance(item_report.longrepr, six.string_types):
message = item_report.longrepr
else:
message = str(item_report.longrepr)
return message
def get_worker_id(self):
# based on https://github.com/pytest-dev/pytest-xdist/pull/505
# (to support older version of xdist)
worker_id = "default"
if hasattr(self.config, "workerinput"):
worker_id = self.config.workerinput["workerid"]
if (
not hasattr(self.config, "workerinput")
and getattr(self.config.option, "dist", "no") != "no"
):
worker_id = "master"
return worker_id
def pytest_runtest_logreport(self, report):
# pylint: disable=too-many-branches
if report.passed:
if report.when == "call":
if hasattr(report, "wasxfail"):
self.cache_report(report, "xpass")
else:
self.cache_report(report, "passed")
elif report.failed:
if report.when == "call":
self.cache_report(report, "failure")
elif report.when == "setup":
self.cache_report(report, "error")
elif report.skipped:
if hasattr(report, "wasxfail"):
self.cache_report(report, "xfailed")
else:
self.cache_report(report, "skipped")
if report.when == "teardown":
# in xdist, report only on worker nodes
if self.get_worker_id() != "master":
old_report = self.get_report(report)
if report.passed and old_report:
self.report_test(old_report[0], old_report[1])
if report.failed and old_report:
self.report_test(
report, old_report[1] + " & error", old_report=old_report[0]
)
if report.skipped:
self.report_test(report, "skipped")
def report_test(self, item_report, outcome, old_report=None):
self.stats[outcome] += 1
test_data = dict(
item_report.user_properties,
timestamp=datetime.datetime.utcnow().isoformat(),
name=item_report.nodeid,
outcome=outcome,
duration=item_report.duration,
markers=item_report.keywords,
**self.session_data,
)
test_data.update(self.test_data[item_report.nodeid])
del self.test_data[item_report.nodeid]
message = self.get_failure_messge(item_report)
if old_report:
message += self.get_failure_messge(old_report)
if message:
test_data.update(failure_message=message)
self.post_to_elasticsearch(test_data)
def pytest_sessionstart(self):
self.session_data["session_start_time"] = datetime.datetime.utcnow().isoformat()
def pytest_sessionfinish(self):
if not self.config.getoption("collectonly"):
test_data = dict(summery=True, stats=self.stats, **self.session_data)
self.post_to_elasticsearch(test_data)
def pytest_terminal_summary(self, terminalreporter):
verbose = terminalreporter.config.getvalue("verbose")
if not self.config.getoption("collectonly") and verbose < 2 and self.es_address:
terminalreporter.write_sep(
"-",
"stats posted to elasticsearch [%s]: %s"
% (self.es_address, self.stats),
)
def pytest_internalerror(self, excrepr):
test_data = dict(
timestamp=datetime.datetime.utcnow().isoformat(),
outcome="internal-error",
faiure_message=excrepr,
**self.session_data,
)
self.post_to_elasticsearch(test_data)
def post_to_elasticsearch(self, test_data):
if self.es_address:
try:
url = "{0.es_url}/{0.es_index_name}/_doc".format(self)
res = requests.post(
url, json=test_data, auth=self.es_auth, timeout=self.es_timeout
)
res.raise_for_status()
except Exception as ex: # pylint: disable=broad-except
LOGGER.warning("Failed to POST to elasticsearch: [%s]", str(ex))
def fetch_test_duration(
self, collected_test_list, default_time_sec=120.0, max_workers=20
):
"""
fetch test 95 percentile duration of a list of tests
:param collected_test_list: the names of the test to lookup
:param default_time_sec: the time to return when no history data found
:param max_workers: number of threads to use for concurrency
:returns: map from test_id to 95 percentile duration
"""
test_durations = []
session = requests.Session()
def get_test_stats(test_id):
url = "{0.es_url}/{0.es_index_name}/_search?size=0".format(self)
body = {
"query": {
"query_string": {"query": self.slices_query_fmt.format(test_id)}
},
"aggs": {
"percentiles_duration": {
"percentiles": {"field": "duration", "percents": [90, 95, 99]}
},
},
}
try:
res = session.post(
url, json=body, auth=self.es_auth, timeout=self.es_timeout
)
res.raise_for_status()
return dict(
test_name=test_id,
duration=res.json()["aggregations"]["percentiles_duration"][
"values"
]["95.0"],
)
except (requests.exceptions.ReadTimeout, requests.exceptions.HTTPError):
return dict(test_name=test_id, duration=None)
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_test_id = {
executor.submit(get_test_stats, test_id): test_id
for test_id in collected_test_list
}
for future in concurrent.futures.as_completed(future_to_test_id):
test_id = future_to_test_id[future]
try:
test_durations.append(future.result())
except Exception: # pylint: disable=broad-except
LOGGER.exception("'%s' generated an exception", test_id)
for test in test_durations:
if not test["duration"]:
test["duration"] = default_time_sec
test_durations.sort(key=lambda x: x["duration"])
LOGGER.debug(pprint.pformat(test_durations))
return test_durations
@staticmethod
def clear_old_exclude_files(outputdir):
print("clear old exclude files")
# Get a list of all files in directory
for root_dir, _, filenames in os.walk(outputdir):
# Find the files that matches the given pattern
for filename in fnmatch.filter(filenames, "include_*.txt"):
try:
os.remove(os.path.join(root_dir, filename))
except OSError:
print(f"Error while deleting file {filename}")
@staticmethod
def split_files_test_list(outputdir, slices):
for i, current_slice in enumerate(slices):
print(
f"{i}: {datetime.timedelta(0, current_slice['total'])} "
f"- {len(current_slice['tests'])} - {current_slice['tests']}"
)
include_filename = os.path.join(outputdir, "include_%03d.txt" % i)
with open(include_filename, "w") as slice_file:
for case in current_slice["tests"]:
slice_file.write(case + "\n")
@staticmethod
def make_test_slices(test_data, max_slice_duration):
slices = []
while test_data:
current_test = test_data.pop(0)
for current_slice in slices:
if (
current_slice["total"] + float(current_test["duration"])
> max_slice_duration
):
continue
current_slice["total"] += float(current_test["duration"])
current_slice["tests"] += [current_test["test_name"]]
break
else:
slices += [dict(total=0.0, tests=[])]
current_slice = slices[-1]
current_slice["total"] += float(current_test["duration"])
current_slice["tests"] += [current_test["test_name"]]
return slices
def pytest_collection_finish(self, session):
if self.config.getoption("es_slices"):
assert (
self.es_default_test_time and self.es_max_splice_time
), "'--es-max-splice-time' and '--es-default-test-time' should be positive numbers"
test_history_data = self.fetch_test_duration(
[item.nodeid.replace("::()", "") for item in session.items],
default_time_sec=self.es_default_test_time,
)
slices = self.make_test_slices(
test_history_data, max_slice_duration=self.es_max_splice_time * 60
)
LOGGER.debug(pprint.pformat(slices))
self.clear_old_exclude_files(outputdir=".")
self.split_files_test_list(outputdir=".", slices=slices)
@pytest.fixture(scope="session")
def elk_reporter(request):
return request.config.pluginmanager.get_plugin("elk-reporter-runtime")
@pytest.fixture(scope="session", autouse=True)
def jenkins_data(request):
"""
Append jenkins job and user data into results session
"""
# TODO: maybe filter some, like password/token and such ?
jenkins_env = {
k.lower(): v for k, v in os.environ.items() if k.startswith("JENKINS_")
}
elk = request.config.pluginmanager.get_plugin("elk-reporter-runtime")
elk.session_data.update(**jenkins_env)
@pytest.fixture(scope="session", autouse=True)
def circle_data(request):
"""
Append circle ci job and user data into results session
"""
if os.environ.get("CIRCLECI", False) == "true":
# TODO: maybe filter some, like password/token and such ?
circle_env = {
k.lower(): v for k, v in os.environ.items() if k.startswith("CIRCLE_")
}
elk = request.config.pluginmanager.get_plugin("elk-reporter-runtime")
elk.session_data.update(**circle_env)
@pytest.fixture(scope="session", autouse=True)
def travis_data(request):
"""
Append travis ci job and user data into results session
"""
if os.environ.get("TRAVIS", False) == "true":
travis_env = {
k.lower(): v for k, v in os.environ.items() if k.startswith("TRAVIS_")
}
elk = request.config.pluginmanager.get_plugin("elk-reporter-runtime")
elk.session_data.update(**travis_env)
@pytest.fixture(scope="session", autouse=True)
def github_data(request):
"""
Append github ci job and user data into results session
"""
if os.environ.get("GITHUB_ACTIONS", False) == "true":
github_env = {
k.lower(): v for k, v in os.environ.items() if k.startswith("GITHUB_")
}
elk = request.config.pluginmanager.get_plugin("elk-reporter-runtime")
elk.session_data.update(**github_env)
@pytest.fixture(scope="session", autouse=True)
def git_data(request):
"""
Append git information into results session
"""
git_info = dict()
cmds = (
("git_commit_oneline", "git log --oneline -1 --no-decorate"),
("git_commit_full", "git log -1 --no-decorate"),
("git_commit_sha", "git rev-parse HEAD"),
("git_commit_sha_short", "git rev-parse --short HEAD"),
("git_branch", "git rev-parse --abbrev-ref HEAD"),
("git_repo", "git config --get remote.origin.url"),
)
for key, command in cmds:
try:
git_info[key] = (
subprocess.check_output(command, shell=True, stderr=subprocess.DEVNULL)
.decode("utf-8")
.strip()
)
except subprocess.CalledProcessError:
pass
elk = request.config.pluginmanager.get_plugin("elk-reporter-runtime")
elk.session_data.update(**git_info)
| high | 0.665716 | 380 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.13;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function transfer(address to, uint256 value) external returns (bool);
}
| high | 0.475342 | 381 |
{
"id": "6d0fa11c-47d2-4a70-87f2-d969a5adbda2",
"modelName": "GMScript",
"mvc": "1.0",
"name": "spart_type_orientation",
"IsCompatibility": false,
"IsDnD": false
} | low | 0.454161 | 382 |
/* "Chapter 6 Splitting Sorted Data via Hash with DELETE Method.sas" from the SAS Press book
Data Management Solutions Using SAS Hash Table Operations:
A Business Intelligence Case Study
*/
data _null_ ;
* if _n_ = 1 then do ;
/*Create operation code block*/
dcl hash h (ordered:"A") ;
h.defineKey ("unique_key") ;
h.defineData ("League", "Team_SK", "Team_Name") ;
h.defineDone () ;
* end ;
do unique_key = 1 by 1 until (last.League) ;
set bizarro.Teams ;
by League ;
h.add() ;
end ;
h.output (dataset: catx ("_", "work.League", League)) ;
* h.clear() ;
/*Delete the instance of object H*/
h.delete() ;
run ;
| low | 0.362369 | 383 |
package ratelimit
import (
"strings"
"sync"
pb "github.com/envoyproxy/go-control-plane/envoy/service/ratelimit/v3"
"github.com/envoyproxy/ratelimit/src/assert"
"github.com/envoyproxy/ratelimit/src/config"
"github.com/envoyproxy/ratelimit/src/limiter"
"github.com/envoyproxy/ratelimit/src/redis"
"github.com/lyft/goruntime/loader"
stats "github.com/lyft/gostats"
logger "github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
type shouldRateLimitStats struct {
redisError stats.Counter
serviceError stats.Counter
}
func newShouldRateLimitStats(scope stats.Scope) shouldRateLimitStats {
ret := shouldRateLimitStats{}
ret.redisError = scope.NewCounter("redis_error")
ret.serviceError = scope.NewCounter("service_error")
return ret
}
type serviceStats struct {
configLoadSuccess stats.Counter
configLoadError stats.Counter
shouldRateLimit shouldRateLimitStats
}
func newServiceStats(scope stats.Scope) serviceStats {
ret := serviceStats{}
ret.configLoadSuccess = scope.NewCounter("config_load_success")
ret.configLoadError = scope.NewCounter("config_load_error")
ret.shouldRateLimit = newShouldRateLimitStats(scope.Scope("call.should_rate_limit"))
return ret
}
type RateLimitServiceServer interface {
pb.RateLimitServiceServer
GetCurrentConfig() config.RateLimitConfig
GetLegacyService() RateLimitLegacyServiceServer
}
type service struct {
runtime loader.IFace
configLock sync.RWMutex
configLoader config.RateLimitConfigLoader
config config.RateLimitConfig
runtimeUpdateEvent chan int
cache limiter.RateLimitCache
stats serviceStats
rlStatsScope stats.Scope
legacy *legacyService
runtimeWatchRoot bool
}
func (this *service) reloadConfig() {
defer func() {
if e := recover(); e != nil {
configError, ok := e.(config.RateLimitConfigError)
if !ok {
panic(e)
}
this.stats.configLoadError.Inc()
logger.Errorf("error loading new configuration from runtime: %s", configError.Error())
}
}()
files := []config.RateLimitConfigToLoad{}
snapshot := this.runtime.Snapshot()
for _, key := range snapshot.Keys() {
if this.runtimeWatchRoot && !strings.HasPrefix(key, "config.") {
continue
}
files = append(files, config.RateLimitConfigToLoad{key, snapshot.Get(key)})
}
newConfig := this.configLoader.Load(files, this.rlStatsScope)
this.stats.configLoadSuccess.Inc()
this.configLock.Lock()
this.config = newConfig
this.configLock.Unlock()
}
type serviceError string
func (e serviceError) Error() string {
return string(e)
}
func checkServiceErr(something bool, msg string) {
if !something {
panic(serviceError(msg))
}
}
func (this *service) shouldRateLimitWorker(
ctx context.Context, request *pb.RateLimitRequest) *pb.RateLimitResponse {
checkServiceErr(request.Domain != "", "rate limit domain must not be empty")
checkServiceErr(len(request.Descriptors) != 0, "rate limit descriptor list must not be empty")
snappedConfig := this.GetCurrentConfig()
checkServiceErr(snappedConfig != nil, "no rate limit configuration loaded")
limitsToCheck := make([]*config.RateLimit, len(request.Descriptors))
for i, descriptor := range request.Descriptors {
limitsToCheck[i] = snappedConfig.GetLimit(ctx, request.Domain, descriptor)
}
responseDescriptorStatuses := this.cache.DoLimit(ctx, request, limitsToCheck)
assert.Assert(len(limitsToCheck) == len(responseDescriptorStatuses))
response := &pb.RateLimitResponse{}
response.Statuses = make([]*pb.RateLimitResponse_DescriptorStatus, len(request.Descriptors))
finalCode := pb.RateLimitResponse_OK
for i, descriptorStatus := range responseDescriptorStatuses {
response.Statuses[i] = descriptorStatus
if descriptorStatus.Code == pb.RateLimitResponse_OVER_LIMIT {
finalCode = descriptorStatus.Code
}
}
response.OverallCode = finalCode
return response
}
func (this *service) ShouldRateLimit(
ctx context.Context,
request *pb.RateLimitRequest) (finalResponse *pb.RateLimitResponse, finalError error) {
defer func() {
err := recover()
if err == nil {
return
}
logger.Debugf("caught error during call")
finalResponse = nil
switch t := err.(type) {
case redis.RedisError:
{
this.stats.shouldRateLimit.redisError.Inc()
finalError = t
}
case serviceError:
{
this.stats.shouldRateLimit.serviceError.Inc()
finalError = t
}
default:
panic(err)
}
}()
response := this.shouldRateLimitWorker(ctx, request)
logger.Debugf("returning normal response")
return response, nil
}
func (this *service) GetLegacyService() RateLimitLegacyServiceServer {
return this.legacy
}
func (this *service) GetCurrentConfig() config.RateLimitConfig {
this.configLock.RLock()
defer this.configLock.RUnlock()
return this.config
}
func NewService(runtime loader.IFace, cache limiter.RateLimitCache,
configLoader config.RateLimitConfigLoader, stats stats.Scope, runtimeWatchRoot bool) RateLimitServiceServer {
newService := &service{
runtime: runtime,
configLock: sync.RWMutex{},
configLoader: configLoader,
config: nil,
runtimeUpdateEvent: make(chan int),
cache: cache,
stats: newServiceStats(stats),
rlStatsScope: stats.Scope("rate_limit"),
runtimeWatchRoot: runtimeWatchRoot,
}
newService.legacy = &legacyService{
s: newService,
shouldRateLimitLegacyStats: newShouldRateLimitLegacyStats(stats),
}
runtime.AddUpdateCallback(newService.runtimeUpdateEvent)
newService.reloadConfig()
go func() {
// No exit right now.
for {
logger.Debugf("waiting for runtime update")
<-newService.runtimeUpdateEvent
logger.Debugf("got runtime update and reloading config")
newService.reloadConfig()
}
}()
return newService
}
| high | 0.672312 | 384 |
open main
pred idABFy8JDHtETW53CpZ_prop5 {
some f: File | eventually (f in Trash)
}
pred __repair { idABFy8JDHtETW53CpZ_prop5 }
check __repair { idABFy8JDHtETW53CpZ_prop5 <=> prop5o } | low | 0.750689 | 385 |
SUBROUTINE heading(extension, time_slice, iseq_count, lmac,
1 lscreen)
USE vmec_main, ONLY: rprec
USE vparams, ONLY: nthreed, nmac
USE vmec_params, ONLY: version_
USE date_and_computer
IMPLICIT NONE
C-----------------------------------------------
C D u m m y A r g u m e n t s
C-----------------------------------------------
INTEGER :: iseq_count
REAL(rprec) :: time_slice
CHARACTER(LEN=*) :: extension
LOGICAL :: lmac, lscreen
C-----------------------------------------------
C L o c a l P a r a m e t e r s
C-----------------------------------------------
CHARACTER(LEN=50), PARAMETER ::
1 banner = ' THIS IS VMEC2000, A 3D EQUILIBRIUM CODE, VERSION '
CHARACTER(LEN=*), PARAMETER :: VersionID1 =
1 ' Lambda: Full Radial Mesh. L-Force: hybrid full/half.'
C-----------------------------------------------
C L o c a l V a r i a b l e s
C-----------------------------------------------
INTEGER :: imon, nout
CHARACTER(LEN=10) :: date0, time0, zone0
CHARACTER(LEN=50) :: dateloc, Version
LOGICAL :: lfirst
C-----------------------------------------------
!
! Open output files
!
CALL open_output_files (extension, iseq_count, lmac, lscreen,
1 lfirst)
IF (.not.lfirst) RETURN
c FORTRAN-90 ROUTINE
CALL DATE_AND_TIME(date0,time0,zone0)
READ(date0(5:6),'(i2)')imon
WRITE(dateloc,100)months(imon),date0(7:8),date0(1:4),
1 time0(1:2),time0(3:4),time0(5:6)
100 FORMAT('DATE = ',a3,' ',a2,',',a4,' ',' TIME = ',2(a2,':'),a2)
CALL GetComputerInfo
IF (lscreen .and. lfirst) WRITE (*,'(a,i4,a,1p,e12.4/2a)')
1 ' SEQ = ', iseq_count+1,
2 ' TIME SLICE',time_slice,' PROCESSING INPUT.', TRIM(extension)
Version = TRIM(ADJUSTL(version_))
WRITE(nthreed,'(a,1x,a,/,a,//,3(2a,2x),a)') TRIM(banner),
1 TRIM(Version), TRIM(VersionID1),
2 ' COMPUTER: ', TRIM(computer), ' OS: ', TRIM(os),
3 ' RELEASE: ', TRIM(os_release), TRIM(dateloc)
IF (lscreen .and. lfirst)
1 WRITE (*,'(1x,a,1x,a,/,1x,a,//,1x,3(2a,2x),a)') TRIM(banner),
2 TRIM(Version), TRIM(VersionID1),
3 ' COMPUTER: ', TRIM(computer), ' OS: ', TRIM(os),
4 ' RELEASE: ', TRIM(os_release), TRIM(dateloc)
DO nout = nthreed, nthreed+1
imon = nout
IF (imon .eq. nthreed+1) imon = nmac
IF (imon.eq.nmac .and. .not.lmac) CYCLE
WRITE (imon,3) TRIM(extension),iseq_count,time_slice
ENDDO
3 FORMAT(' SHOT ID.: ',a,2x,'SEQ. NO.:',i4,/,
1 ' TIME SLICE = ',f5.0,' ms')
END SUBROUTINE heading
| medium | 0.528709 | 386 |
%{
package parse
import (
"github.com/talktonpc/nakama/v3/internal/gopher-lua/ast"
)
%}
%type<stmts> chunk
%type<stmts> chunk1
%type<stmts> block
%type<stmt> stat
%type<stmts> elseifs
%type<stmt> laststat
%type<funcname> funcname
%type<funcname> funcname1
%type<exprlist> varlist
%type<expr> var
%type<namelist> namelist
%type<exprlist> exprlist
%type<expr> expr
%type<expr> string
%type<expr> prefixexp
%type<expr> functioncall
%type<expr> afunctioncall
%type<exprlist> args
%type<expr> function
%type<funcexpr> funcbody
%type<parlist> parlist
%type<expr> tableconstructor
%type<fieldlist> fieldlist
%type<field> field
%type<fieldsep> fieldsep
%union {
token ast.Token
stmts []ast.Stmt
stmt ast.Stmt
funcname *ast.FuncName
funcexpr *ast.FunctionExpr
exprlist []ast.Expr
expr ast.Expr
fieldlist []*ast.Field
field *ast.Field
fieldsep string
namelist []string
parlist *ast.ParList
}
/* Reserved words */
%token<token> TAnd TBreak TDo TElse TElseIf TEnd TFalse TFor TFunction TIf TIn TLocal TNil TNot TOr TReturn TRepeat TThen TTrue TUntil TWhile
/* Literals */
%token<token> TEqeq TNeq TLte TGte T2Comma T3Comma TIdent TNumber TString '{' '('
/* Operators */
%left TOr
%left TAnd
%left '>' '<' TGte TLte TEqeq TNeq
%right T2Comma
%left '+' '-'
%left '*' '/' '%'
%right UNARY /* not # -(unary) */
%right '^'
%%
chunk:
chunk1 {
$$ = $1
if l, ok := yylex.(*Lexer); ok {
l.Stmts = $$
}
} |
chunk1 laststat {
$$ = append($1, $2)
if l, ok := yylex.(*Lexer); ok {
l.Stmts = $$
}
} |
chunk1 laststat ';' {
$$ = append($1, $2)
if l, ok := yylex.(*Lexer); ok {
l.Stmts = $$
}
}
chunk1:
{
$$ = []ast.Stmt{}
} |
chunk1 stat {
$$ = append($1, $2)
} |
chunk1 ';' {
$$ = $1
}
block:
chunk {
$$ = $1
}
stat:
varlist '=' exprlist {
$$ = &ast.AssignStmt{Lhs: $1, Rhs: $3}
$$.SetLine($1[0].Line())
} |
/* 'stat = functioncal' causes a reduce/reduce conflict */
prefixexp {
if _, ok := $1.(*ast.FuncCallExpr); !ok {
yylex.(*Lexer).Error("parse error")
} else {
$$ = &ast.FuncCallStmt{Expr: $1}
$$.SetLine($1.Line())
}
} |
TDo block TEnd {
$$ = &ast.DoBlockStmt{Stmts: $2}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($3.Pos.Line)
} |
TWhile expr TDo block TEnd {
$$ = &ast.WhileStmt{Condition: $2, Stmts: $4}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($5.Pos.Line)
} |
TRepeat block TUntil expr {
$$ = &ast.RepeatStmt{Condition: $4, Stmts: $2}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($4.Line())
} |
TIf expr TThen block elseifs TEnd {
$$ = &ast.IfStmt{Condition: $2, Then: $4}
cur := $$
for _, elseif := range $5 {
cur.(*ast.IfStmt).Else = []ast.Stmt{elseif}
cur = elseif
}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($6.Pos.Line)
} |
TIf expr TThen block elseifs TElse block TEnd {
$$ = &ast.IfStmt{Condition: $2, Then: $4}
cur := $$
for _, elseif := range $5 {
cur.(*ast.IfStmt).Else = []ast.Stmt{elseif}
cur = elseif
}
cur.(*ast.IfStmt).Else = $7
$$.SetLine($1.Pos.Line)
$$.SetLastLine($8.Pos.Line)
} |
TFor TIdent '=' expr ',' expr TDo block TEnd {
$$ = &ast.NumberForStmt{Name: $2.Str, Init: $4, Limit: $6, Stmts: $8}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($9.Pos.Line)
} |
TFor TIdent '=' expr ',' expr ',' expr TDo block TEnd {
$$ = &ast.NumberForStmt{Name: $2.Str, Init: $4, Limit: $6, Step:$8, Stmts: $10}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($11.Pos.Line)
} |
TFor namelist TIn exprlist TDo block TEnd {
$$ = &ast.GenericForStmt{Names:$2, Exprs:$4, Stmts: $6}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($7.Pos.Line)
} |
TFunction funcname funcbody {
$$ = &ast.FuncDefStmt{Name: $2, Func: $3}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($3.LastLine())
} |
TLocal TFunction TIdent funcbody {
$$ = &ast.LocalAssignStmt{Names:[]string{$3.Str}, Exprs: []ast.Expr{$4}}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($4.LastLine())
} |
TLocal namelist '=' exprlist {
$$ = &ast.LocalAssignStmt{Names: $2, Exprs:$4}
$$.SetLine($1.Pos.Line)
} |
TLocal namelist {
$$ = &ast.LocalAssignStmt{Names: $2, Exprs:[]ast.Expr{}}
$$.SetLine($1.Pos.Line)
}
elseifs:
{
$$ = []ast.Stmt{}
} |
elseifs TElseIf expr TThen block {
$$ = append($1, &ast.IfStmt{Condition: $3, Then: $5})
$$[len($$)-1].SetLine($2.Pos.Line)
}
laststat:
TReturn {
$$ = &ast.ReturnStmt{Exprs:nil}
$$.SetLine($1.Pos.Line)
} |
TReturn exprlist {
$$ = &ast.ReturnStmt{Exprs:$2}
$$.SetLine($1.Pos.Line)
} |
TBreak {
$$ = &ast.BreakStmt{}
$$.SetLine($1.Pos.Line)
}
funcname:
funcname1 {
$$ = $1
} |
funcname1 ':' TIdent {
$$ = &ast.FuncName{Func:nil, Receiver:$1.Func, Method: $3.Str}
}
funcname1:
TIdent {
$$ = &ast.FuncName{Func: &ast.IdentExpr{Value:$1.Str}}
$$.Func.SetLine($1.Pos.Line)
} |
funcname1 '.' TIdent {
key:= &ast.StringExpr{Value:$3.Str}
key.SetLine($3.Pos.Line)
fn := &ast.AttrGetExpr{Object: $1.Func, Key: key}
fn.SetLine($3.Pos.Line)
$$ = &ast.FuncName{Func: fn}
}
varlist:
var {
$$ = []ast.Expr{$1}
} |
varlist ',' var {
$$ = append($1, $3)
}
var:
TIdent {
$$ = &ast.IdentExpr{Value:$1.Str}
$$.SetLine($1.Pos.Line)
} |
prefixexp '[' expr ']' {
$$ = &ast.AttrGetExpr{Object: $1, Key: $3}
$$.SetLine($1.Line())
} |
prefixexp '.' TIdent {
key := &ast.StringExpr{Value:$3.Str}
key.SetLine($3.Pos.Line)
$$ = &ast.AttrGetExpr{Object: $1, Key: key}
$$.SetLine($1.Line())
}
namelist:
TIdent {
$$ = []string{$1.Str}
} |
namelist ',' TIdent {
$$ = append($1, $3.Str)
}
exprlist:
expr {
$$ = []ast.Expr{$1}
} |
exprlist ',' expr {
$$ = append($1, $3)
}
expr:
TNil {
$$ = &ast.NilExpr{}
$$.SetLine($1.Pos.Line)
} |
TFalse {
$$ = &ast.FalseExpr{}
$$.SetLine($1.Pos.Line)
} |
TTrue {
$$ = &ast.TrueExpr{}
$$.SetLine($1.Pos.Line)
} |
TNumber {
$$ = &ast.NumberExpr{Value: $1.Str}
$$.SetLine($1.Pos.Line)
} |
T3Comma {
$$ = &ast.Comma3Expr{}
$$.SetLine($1.Pos.Line)
} |
function {
$$ = $1
} |
prefixexp {
$$ = $1
} |
string {
$$ = $1
} |
tableconstructor {
$$ = $1
} |
expr TOr expr {
$$ = &ast.LogicalOpExpr{Lhs: $1, Operator: "or", Rhs: $3}
$$.SetLine($1.Line())
} |
expr TAnd expr {
$$ = &ast.LogicalOpExpr{Lhs: $1, Operator: "and", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '>' expr {
$$ = &ast.RelationalOpExpr{Lhs: $1, Operator: ">", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '<' expr {
$$ = &ast.RelationalOpExpr{Lhs: $1, Operator: "<", Rhs: $3}
$$.SetLine($1.Line())
} |
expr TGte expr {
$$ = &ast.RelationalOpExpr{Lhs: $1, Operator: ">=", Rhs: $3}
$$.SetLine($1.Line())
} |
expr TLte expr {
$$ = &ast.RelationalOpExpr{Lhs: $1, Operator: "<=", Rhs: $3}
$$.SetLine($1.Line())
} |
expr TEqeq expr {
$$ = &ast.RelationalOpExpr{Lhs: $1, Operator: "==", Rhs: $3}
$$.SetLine($1.Line())
} |
expr TNeq expr {
$$ = &ast.RelationalOpExpr{Lhs: $1, Operator: "~=", Rhs: $3}
$$.SetLine($1.Line())
} |
expr T2Comma expr {
$$ = &ast.StringConcatOpExpr{Lhs: $1, Rhs: $3}
$$.SetLine($1.Line())
} |
expr '+' expr {
$$ = &ast.ArithmeticOpExpr{Lhs: $1, Operator: "+", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '-' expr {
$$ = &ast.ArithmeticOpExpr{Lhs: $1, Operator: "-", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '*' expr {
$$ = &ast.ArithmeticOpExpr{Lhs: $1, Operator: "*", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '/' expr {
$$ = &ast.ArithmeticOpExpr{Lhs: $1, Operator: "/", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '%' expr {
$$ = &ast.ArithmeticOpExpr{Lhs: $1, Operator: "%", Rhs: $3}
$$.SetLine($1.Line())
} |
expr '^' expr {
$$ = &ast.ArithmeticOpExpr{Lhs: $1, Operator: "^", Rhs: $3}
$$.SetLine($1.Line())
} |
'-' expr %prec UNARY {
$$ = &ast.UnaryMinusOpExpr{Expr: $2}
$$.SetLine($2.Line())
} |
TNot expr %prec UNARY {
$$ = &ast.UnaryNotOpExpr{Expr: $2}
$$.SetLine($2.Line())
} |
'#' expr %prec UNARY {
$$ = &ast.UnaryLenOpExpr{Expr: $2}
$$.SetLine($2.Line())
}
string:
TString {
$$ = &ast.StringExpr{Value: $1.Str}
$$.SetLine($1.Pos.Line)
}
prefixexp:
var {
$$ = $1
} |
afunctioncall {
$$ = $1
} |
functioncall {
$$ = $1
} |
'(' expr ')' {
$$ = $2
$$.SetLine($1.Pos.Line)
}
afunctioncall:
'(' functioncall ')' {
$2.(*ast.FuncCallExpr).AdjustRet = true
$$ = $2
}
functioncall:
prefixexp args {
$$ = &ast.FuncCallExpr{Func: $1, Args: $2}
$$.SetLine($1.Line())
} |
prefixexp ':' TIdent args {
$$ = &ast.FuncCallExpr{Method: $3.Str, Receiver: $1, Args: $4}
$$.SetLine($1.Line())
}
args:
'(' ')' {
if yylex.(*Lexer).PNewLine {
yylex.(*Lexer).TokenError($1, "ambiguous syntax (function call x new statement)")
}
$$ = []ast.Expr{}
} |
'(' exprlist ')' {
if yylex.(*Lexer).PNewLine {
yylex.(*Lexer).TokenError($1, "ambiguous syntax (function call x new statement)")
}
$$ = $2
} |
tableconstructor {
$$ = []ast.Expr{$1}
} |
string {
$$ = []ast.Expr{$1}
}
function:
TFunction funcbody {
$$ = &ast.FunctionExpr{ParList:$2.ParList, Stmts: $2.Stmts}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($2.LastLine())
}
funcbody:
'(' parlist ')' block TEnd {
$$ = &ast.FunctionExpr{ParList: $2, Stmts: $4}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($5.Pos.Line)
} |
'(' ')' block TEnd {
$$ = &ast.FunctionExpr{ParList: &ast.ParList{HasVargs: false, Names: []string{}}, Stmts: $3}
$$.SetLine($1.Pos.Line)
$$.SetLastLine($4.Pos.Line)
}
parlist:
T3Comma {
$$ = &ast.ParList{HasVargs: true, Names: []string{}}
} |
namelist {
$$ = &ast.ParList{HasVargs: false, Names: []string{}}
$$.Names = append($$.Names, $1...)
} |
namelist ',' T3Comma {
$$ = &ast.ParList{HasVargs: true, Names: []string{}}
$$.Names = append($$.Names, $1...)
}
tableconstructor:
'{' '}' {
$$ = &ast.TableExpr{Fields: []*ast.Field{}}
$$.SetLine($1.Pos.Line)
} |
'{' fieldlist '}' {
$$ = &ast.TableExpr{Fields: $2}
$$.SetLine($1.Pos.Line)
}
fieldlist:
field {
$$ = []*ast.Field{$1}
} |
fieldlist fieldsep field {
$$ = append($1, $3)
} |
fieldlist fieldsep {
$$ = $1
}
field:
TIdent '=' expr {
$$ = &ast.Field{Key: &ast.StringExpr{Value:$1.Str}, Value: $3}
$$.Key.SetLine($1.Pos.Line)
} |
'[' expr ']' '=' expr {
$$ = &ast.Field{Key: $2, Value: $5}
} |
expr {
$$ = &ast.Field{Value: $1}
}
fieldsep:
',' {
$$ = ","
} |
';' {
$$ = ";"
}
%%
func TokenName(c int) string {
if c >= TAnd && c-TAnd < len(yyToknames) {
if yyToknames[c-TAnd] != "" {
return yyToknames[c-TAnd]
}
}
return string([]byte{byte(c)})
}
| high | 0.819988 | 387 |
namespace java de.hska.iwi.bdelab.schema2
union UserID {
1: string user_id;
2: string ip;
}
union Page {
1: string url;
}
enum GenderType {
MALE = 1,
FEMALE = 2
}
union UserPropertyValue {
1: string full_name;
2: string email;
3: GenderType gender;
}
struct UserProperty {
1: required UserID id;
2: required UserPropertyValue property;
}
struct FriendEdge {
1: required UserID id1;
2: required UserID id2;
}
struct PageviewEdge {
1: required UserID user;
2: required Page page;
3: required i32 nonce;
}
struct Pedigree {
1: required i32 true_as_of_secs;
}
union DataUnit {
1: UserProperty user_property;
2: FriendEdge friend;
3: PageviewEdge pageview;
}
struct Data {
1: required Pedigree pedigree;
2: required DataUnit dataunit;
}
| high | 0.82615 | 388 |
Be the boss of your factors
========================================================
> JB: Still under development. Cannot decide if this is a tutorial, with a story, and fitting into a larger sequence of tutorials or is a topic/reference sort of thing.
```{r include = FALSE}
require(knitr)
## toggle to code tidying on/off
opts_chunk$set(tidy = FALSE)
```
### Optional getting started advice
*Ignore if you don't need this bit of support.*
This is one in a series of tutorials in which we explore basic data import, exploration and much more using data from the [Gapminder project](http://www.gapminder.org). Now is the time to make sure you are working in the appropriate directory on your computer, perhaps through the use of an [RStudio project](block01_basicsWorkspaceWorkingDirProject.html). To ensure a clean slate, you may wish to clean out your workspace and restart R (both available from the RStudio Session menu, among other methods). Confirm that the new R process has the desired working directory, for example, with the `getwd()` command or by glancing at the top of RStudio's Console pane.
Open a new R script (in RStudio, File > New > R Script). Develop and run your code from there (recommended) or periodicially copy "good" commands from the history. In due course, save this script with a name ending in .r or .R, containing no spaces or other funny stuff, and evoking "factor hygiene".
### Load the Gapminder data and `lattice` and `plyr`
Assuming the data can be found in the current working directory, this works:
```{r, eval=FALSE}
gDat <- read.delim("gapminderDataFiveYear.txt")
```
Plan B (I use here, because of where the source of this tutorial lives):
```{r}
## data import from URL
gdURL <- "http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt"
gDat <- read.delim(file = gdURL)
```
Basic sanity check that the import has gone well:
```{r}
str(gDat)
```
Load the `lattice` and `plyr` packages.
```{r}
library(lattice)
library(plyr)
```
### Factors are high maintenance variables
Factors are used to hold categorical variables in R. In Gapminder, the examples are `continent` and `country`, with `year` being a numeric variable that can be gracefully converted to a factor depending on context. Under the hood, factors are stored as integer codes, e.g., 1, 2, ... These integer codes are associated with a vector of character strings, the *levels*, which is what you will see much more often in the Console and in figures. If you read the documentation on `factor()` you'll see confusing crazy talk about another thing, `labels =`, which I've never understood and completely ignore.
```{r echo = FALSE}
data.frame(levels = levels(gDat$continent))
```
But don't ever, ever forget that factors are fundamentally numeric. Apply the functions `class()`, `mode()`, and `typeof()` to a factor if you need convincing.
```{r echo = FALSE}
data.frame(factor = c(class = class(gDat$country),
mode = mode(gDat$country),
typeof = typeof(gDat$country)))
```
Jenny's Law says that some great huge factor misunderstanding will eat up hours of valuable time in any given analysis. When you're beating your head against the wall, look very closely at your factors. Are you using them in a character context? Do you have factors you did not know about, e.g., variables you perceived as character but that are actually factors? `str()` is a mighty weapon.
### Factor avoidance: is this strategy for you?
Many people have gotten so frustrated with factors that they refuse to use them. While I'm sympathetic, it's a counterproductive overreaction. Factors are sufficiently powerful in data aggregation, modelling, and visualization to merit their use. Furthermore, factor-abstainers are a fringe minority in the R world which makes it harder to share and remix code from others.
<http://stackoverflow.com/questions/3445316/factors-in-r-more-than-an-annoyance>
### Factor avoidance: how to achieve, selectively
Most unwanted factors are created upon import with `read.table()`, which converts character variables to factors by default. The same default behavior also happens when you construct a data.frame explicitly with `data.frame()`.
* To turn off the behavior for the duration of an R session, submit this: `options(stringsAsFactors = FALSE)`
* To make that apply to all your R processes, put that in your `.Rprofile`. (I think this is going too far, though.)
Here are options to take control in a more refined fashion:
* To turn off the conversion for all variables within a specific `read.table()` or `data.frame()` call, add `stringsAsFactors = FALSE` to the call.
* To turn off conversion for specific variables in `read.table()`, specify them via `as.is =`: "its value is either a vector of logicals (values are recycled if necessary), or a vector of numeric or character indices which specify which columns should not be converted to factors." (In theory, one can also use `colClasses =` but this is miserable, due to the need to be exhaustive. Consider that a last resort.)
* To turn off conversion for a specific variable in `data.frame()`, protect it with `I()`.
Convert an existing factor to a character variable with `as.character()`.
### How to make, study, and unmake a factor
If you want to create a factor explicitly, use `factor()`. If you already have a reason and the knowledge to override the default alphabetical ordering of the factor levels, seize this opportunity to set them via the `levels =` argument.
To check the levels or count them, use `levels()` and `nlevels()`.
To tabulate a factor, use `table()`. Sometimes it's nice to post-process this table with `as.data.frame`, `prop.table()`, or `addmargins()`.
To get the underlying integer codes, use `unclass()`. Use this with great care.
### Specialty functions for making factors
`gl()`, `interaction()`, `lattice::make.groups()`
> Obviously not written yet.
### How to change factor levels: recoding
`recode()` from `car` package
<http://citizen-statistician.org/2012/10/20/recoding-variables-in-r-pedagogic-considerations/>
> Obviously not written yet.
### How to change factor levels: dropping a level
```{r eval = FALSE}
## drop Oceania
jDat <- droplevels(subset(gDat, continent != "Oceania"))
```
> There's more to say here but `droplevels()` is a great start.
### How to change factor levels: reordering
It's common and desirable to reorder factor levels rationally, as opposed to alphabetically. In fact, it should be more common! Typical scenario: order the levels of a factor so that a summary statistic of an associated quantitative variable is placed in rank order in data aggregation results or in a figure. This is much easier to see in examples. I'll walk through two and, far below, discuss the `reorder()` function itself.
Example from the [data aggregation tutorial](block04_dataAggregation.html). We fit a linear model of `lifeExp ~ year` for each country and packaged the estimated intercepts and slopes, along with `country` and `continent` factors, in a data.frame. It is sensible to reorder the `country` factor labels in this derived data.frame according to either the intercept or slope. I chose the intercept.
```{r tidy = FALSE}
yearMin <- min(gDat$year)
jFun <- function(x) {
estCoefs <- coef(lm(lifeExp ~ I(year - yearMin), x))
names(estCoefs) <- c("intercept", "slope")
return(estCoefs)
}
jCoefs <- ddply(gDat, ~ country + continent, jFun)
head(levels(jCoefs$country)) # alphabetical order
jCoefs <- within(jCoefs, country <- reorder(country, intercept))
head(levels(jCoefs$country)) # in increasing order of 1952 life expectancy
head(jCoefs)
```
Note that the __row order of `jCoefs` is not changed__ by reordering the factor levels. I could __choose__ to reorder the rows of the data.frame, based on the new, rational level order of `country`. I do below using `arrange()` from `plyr`, which is a nice wrapper around the built-in function `order()`.
```{r}
# assign the arrange() result back to jCoefs to make the new row order "stick"
head(arrange(jCoefs, country))
tail(arrange(jCoefs, country))
```
Example that reorders a factor temporarily "on the fly". This happens most often within a plotting call. Remember: you don't have to alter the factor's level order in the underlying data.frame itself. Building on the first example, let's make a stripplot of the intercepts, split out by continent, and overlay a connect-the-dots representation of the continent-specific averages. See figure on the left below. The erratic behavior of the overlay suggests that the continents are presented in a silly order, namely, alphabetical. It might make more sense to arrange the continents in increasing order of 1952 life expectancy. See figure on the right below.
> Sorry folks, experimenting with figure placement! Please tolerate any lack of side-by-side-ness and duplication for the moment.
```{r fig.show = 'hold', fig.width = 4.5, fig.height = 5}
stripplot(intercept ~ continent, jCoefs, type = c("p", "a"))
stripplot(intercept ~ reorder(continent, intercept), jCoefs, type = c("p", "a"))
```
```{r fig.show = 'hold', out.width = '49%'}
stripplot(intercept ~ continent, jCoefs, type = c("p", "a"))
stripplot(intercept ~ reorder(continent, intercept), jCoefs, type = c("p", "a"))
```
<!--- http://stackoverflow.com/questions/13685992/multiple-figures-with-rhtml-and-knitr --->
<!--- http://r.789695.n4.nabble.com/knitr-side-by-side-figures-in-R-markdown-td4669875.html --->
__You try__: make a similar pair of plots for the slopes.
```{r echo = FALSE, eval = FALSE}
stripplot(slope ~ continent, jCoefs, type = c("p", "a"))
stripplot(slope ~ reorder(continent, slope), jCoefs, type = c("p", "a"))
```
You will notice that the continents will be in a very different order, if you reorder by intercept vs. slope. There is no single definitive order for factor levels. It varies, depending on the quantitative variable and statistic driving the reordering. In a real data analysis, when you're producing a large number of related plots, I suggest you pick one factor level order and stick to it. In Gapminder, I would use this: Africa, Asia, America, Europe (and I'd drop Oceania). Sometimes a global commitment to constancy -- in factor level order and color usage especially -- must override optimization of any particular figure.
`reorder(x, X, FUN, ..., order)` is the main built-in function for reordering the levels of a factor `x` such that the summary statistics produced by applying `FUN` to the values of `X` -- when split out by the reordered factor `x` -- are in increasing order.`FUN` defaults to `mean()`, which is often just fine.
Mildly interesting: post-reordering, the factor `x` will have a `scores` attribute containing those summary statistics.
Footnote based on hard personal experience: The package `gdata` includes an explicit factor method for the `reorder()` generic, namely `reorder.factor()`. Unfortunately it is not "upwards compatible" with the built-in `reorder.default()` in `stats`. Specifically, `gdata`'s `reorder.factor()` has no default for `FUN` so, if called without an explicit value for `FUN`, *nothing happens*. No reordering. I have found it is rather easy for the package or at least this function to creep onto my search path without my knowledge, since quite a few packages require `gdata` or use functions from it. This underscores the importance of checking that reordering has indeed occured. If you're reordering 'on the fly' in a plot, check visually. Otherwise, explicitly inspect the new level order with `levels()` and/or inspect the `scores` attribute described above. To look for `gdata` on your search path, use `search()`. To force the use of the built-in `reorder()`, call `stats::reorder()`. Many have tripped up on this:
* <http://stackoverflow.com/questions/10939516/data-frame-transformation-gives-different-results-when-same-code-is-run-before-a>
* <http://stackoverflow.com/questions/13146567/transform-and-reorder>
* <http://stackoverflow.com/questions/11004018/how-can-a-non-imported-method-in-a-not-attached-package-be-found-by-calls-to-fun>
### How to grow factor objects
Try not to. But `rbind()`ing data.frames shockingly works better / more often than `c()`ing vectors. But this is a very delicate operation. WRITE MORE.
This is not as crazy/stupid as you might fear: convert to character, grow, convert back to factor.
> Obviously not written yet.
### References
[Data Manipulation with R](http://www.springerlink.com/content/t19776/?p=0ecea4f02a68458eb3d605ec3cdfc7ef%CF%80=0) by Phil Spector, Springer (2008) | [author webpage](http://www.stat.berkeley.edu/%7Espector/) | [GoogleBooks search](http://books.google.com/books?id=grfuq1twFe4C&lpg=PP1&dq=data%2520manipulation%2520spector&pg=PP1#v=onepage&q=&f=false)
* The main link above to SpringerLink will give full access to the book if you are on a UBC network (or any other network that confers accesss).
* See Chapter 5 (“Factors”)
Lattice: Multivariate Data Visualization with R [available via SpringerLink](http://ezproxy.library.ubc.ca/login?url=http://link.springer.com.ezproxy.library.ubc.ca/book/10.1007/978-0-387-75969-2/page/1) by Deepayan Sarkar, Springer (2008) | [all code from the book](http://lmdvr.r-forge.r-project.org/) | [GoogleBooks search](http://books.google.com/books?id=gXxKFWkE9h0C&lpg=PR2&dq=lattice%20sarkar%23v%3Donepage&pg=PR2#v=onepage&q=&f=false)
* Section 9.2.5 Dropping unused levels from groups
* Section 10.4.1 Dropping of factor levels (in the context of using `subset =`)
* Section 10.6 Ordering levels of categorical variables
<div class="footer">
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">CC BY-NC 3.0 Creative Commons License</a>.
</div> | high | 0.158541 | 389 |
{
"isDnD": false,
"isCompatibility": false,
"parent": {
"name": "Configuration - Please edit these!",
"path": "folders/Scribble/Configuration - Please edit these!.yy",
},
"resourceVersion": "1.0",
"name": "__scribble_config_colours",
"tags": [],
"resourceType": "GMScript",
} | high | 0.431163 | 390 |
/* macOS CS:GO base
* pwned#5530
*
*
* Notes
* - Use osxinj to inject
* - IMPL_HOOK just prints "hook_name hooked" to console
* - The print() function prints to console, args : string, color = Pastel pink, prefix = "debug"
* - Install the fonts into /Library/Fonts/ and not ~/Library/Fonts/
*
*
*
*
*
*/
#include "main.h"
#include "hooker.h"
int __attribute__((constructor)) main()
{
init_interfaces();
init_hooks();
hook_functions();
get_offsets();
init_settings();
return EXIT_SUCCESS;
}
| high | 0.508109 | 391 |
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" href="/resources/quantum-docs.css"></link><link rel="stylesheet" href="/resources/quantum-html.css"></link><link rel="stylesheet" href="/resources/quantum-code-highlight.css"></link><link rel="stylesheet" href="/resources/quantum-api.css"></link><link rel="stylesheet" href="/resources/quantum-api-javascript.css"></link><link rel="stylesheet" href="/resources/quantum-api-css.css"></link><link href="/resources/hexagon/1.4.1/hexagon.css" rel="stylesheet"></link><link href="https://fonts.googleapis.com/css?family=Open+Sans:100,400,700|Roboto+Slab:400,700|Source+Code+Pro:400,700" rel="stylesheet"></link><link href="/resources/font-awesome/css/all.min.css" rel="stylesheet"></link><link href="/resources/docs-new.css" rel="stylesheet"></link><link rel="apple-touch-icon" sizes="57x57" href="/resources/hexagon/docs/favicons/apple-touch-icon-57x57.png?v=0">
<link rel="apple-touch-icon" sizes="60x60" href="/resources/hexagon/docs/favicons/apple-touch-icon-60x60.png?v=0">
<link rel="apple-touch-icon" sizes="72x72" href="/resources/hexagon/docs/favicons/apple-touch-icon-72x72.png?v=0">
<link rel="apple-touch-icon" sizes="76x76" href="/resources/hexagon/docs/favicons/apple-touch-icon-76x76.png?v=0">
<link rel="apple-touch-icon" sizes="114x114" href="/resources/hexagon/docs/favicons/apple-touch-icon-114x114.png?v=0">
<link rel="apple-touch-icon" sizes="120x120" href="/resources/hexagon/docs/favicons/apple-touch-icon-120x120.png?v=0">
<link rel="apple-touch-icon" sizes="144x144" href="/resources/hexagon/docs/favicons/apple-touch-icon-144x144.png?v=0">
<link rel="apple-touch-icon" sizes="152x152" href="/resources/hexagon/docs/favicons/apple-touch-icon-152x152.png?v=0">
<link rel="apple-touch-icon" sizes="180x180" href="/resources/hexagon/docs/favicons/apple-touch-icon-180x180.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 414px) and (device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-1182x2208.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 414px) and (device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-1242x2148.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-1496x2048.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-1536x2008.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 1)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-320x460.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-640x1096.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-640x920.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 1)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-748x1024.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-750x1294.png?v=0">
<link rel="apple-touch-startup-image" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 1)" href="/resources/hexagon/docs/favicons/apple-touch-startup-image-768x1004.png?v=0">
<link rel="icon" type="image/png" sizes="32x32" href="/resources/hexagon/docs/favicons/favicon-32x32.png?v=0">
<link rel="icon" type="image/png" sizes="230x230" href="/resources/hexagon/docs/favicons/favicon-230x230.png?v=0">
<link rel="icon" type="image/png" sizes="96x96" href="/resources/hexagon/docs/favicons/favicon-96x96.png?v=0">
<link rel="icon" type="image/png" sizes="16x16" href="/resources/hexagon/docs/favicons/favicon-16x16.png?v=0">
<link rel="manifest" href="/resources/hexagon/docs/favicons/manifest.json">
<link rel="yandex-tableau-widget" href="/resources/hexagon/docs/favicons/yandex-browser-manifest.json">
<link rel="shortcut icon" type="image/x-icon" href="/resources/hexagon/docs/favicons/favicon.ico?v=0">
<meta property="og:image" content="/resources/hexagon/docs/favicons/open-graph.png?v=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="msapplication-TileColor" content="#FFF">
<meta name="msapplication-TileImage" content="/resources/hexagon/docs/favicons/mstile-144x144.png?v=0">
<meta name="theme-color" content="#FFF">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AutoComplete</title><meta name="viewport" content="width=device-width, initial-scale=1"></meta></head>
<body class="qm-body-font qm-docs-sidebar-page"><script src="/resources/hexagon/1.4.1/hexagon.js"></script><script src="/resources/hexagon/docs/hexagon.js"></script><script src="/resources/docs.js"></script><div class="qm-docs-header"><div class="qm-docs-centered"><div class="qm-docs-header-wrapper"><image class="qm-docs-header-logo" src="/resources/logo-mono-v1.svg"></image><div class="qm-docs-header-title qm-header-font">HexagonJS</div><div class="qm-docs-header-mobile-menu" id="nav.toggle.186D8751B7547EC7C0A1C957EFA1F0D6"><i class="qm-docs-header-mobile-menu-icon"></i></div><div class="qm-docs-header-links" id="nav.links.186D8751B7547EC7C0A1C957EFA1F0D6"></div></div></div></div><div class="qm-docs-sidebar-page"><div class="qm-docs-sidebar"><div class="qm-docs-navigation-menu-wrapper"><div class="qm-docs-navigation-menu"><div class="qm-docs-navigation-menu-section"><div class="qm-docs-navigation-menu-section-title">About</div><div class="qm-docs-navigation-menu-section-body"><a class="qm-docs-navigation-menu-page" href="/guide/installation">Installation</a><a class="qm-docs-navigation-menu-page" href="/guide/core-concepts">Core Concepts</a><a class="qm-docs-navigation-menu-page" href="/changelog">Changelog</a><a class="qm-docs-navigation-menu-page" href="/guide/migration">[Migration (1.x -> 2.x)]</a></div></div><div class="qm-docs-navigation-menu-section"><div class="qm-docs-navigation-menu-section-title">Tutorials</div><div class="qm-docs-navigation-menu-section-body"><a class="qm-docs-navigation-menu-page" href="/guide/getting-started">Getting Started</a><a class="qm-docs-navigation-menu-page" href="/guide/printing">Print Styles</a></div></div><div class="qm-docs-navigation-menu-section"><div class="qm-docs-navigation-menu-section-title">Demos</div><div class="qm-docs-navigation-menu-section-body"><a class="qm-docs-navigation-menu-page" href="/demo/">Component Demo Page</a></div></div><div class="qm-docs-navigation-menu-section"><div class="qm-docs-navigation-menu-section-title">Css Components</div><div class="qm-docs-navigation-menu-section-body"><a class="qm-docs-navigation-menu-page" href="/docs/base/">Base</a><a class="qm-docs-navigation-menu-page" href="/docs/button/">Button</a><a class="qm-docs-navigation-menu-page" href="/docs/badge/">Badge</a><a class="qm-docs-navigation-menu-page" href="/docs/error-pages/">Error Pages</a><a class="qm-docs-navigation-menu-page" href="/docs/form/">Form</a><a class="qm-docs-navigation-menu-page" href="/docs/input/">Inputs</a><a class="qm-docs-navigation-menu-page" href="/docs/input-group/">Input Group</a><a class="qm-docs-navigation-menu-page" href="/docs/label/">Label</a><a class="qm-docs-navigation-menu-page" href="/docs/layout/">Layout</a><a class="qm-docs-navigation-menu-page" href="/docs/logo/">Logo</a><a class="qm-docs-navigation-menu-page" href="/docs/notice/">Notice</a><a class="qm-docs-navigation-menu-page" href="/docs/spinner/">Spinner</a><a class="qm-docs-navigation-menu-page" href="/docs/table/">Table</a></div></div><div class="qm-docs-navigation-menu-section"><div class="qm-docs-navigation-menu-section-title">Js Components</div><div class="qm-docs-navigation-menu-section-body"><a class="qm-docs-navigation-menu-page" href="/docs/alert/">Alerts and Messages</a><a class="qm-docs-navigation-menu-page" href="/docs/autocomplete-picker/">Autocomplete Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/autocomplete/">Autocomplete</a><a class="qm-docs-navigation-menu-page" href="/docs/button-group/">Button Group</a><a class="qm-docs-navigation-menu-page" href="/docs/card/">Card</a><a class="qm-docs-navigation-menu-page" href="/docs/collapsible/">Collapsible</a><a class="qm-docs-navigation-menu-page" href="/docs/color-picker/">Color Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/crumbtrail/">Crumbtrail</a><a class="qm-docs-navigation-menu-page" href="/docs/data-table/">Data Table</a><a class="qm-docs-navigation-menu-page" href="/docs/date-picker/">Date Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/date-time-picker/">Date Time Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/drag-container/">Drag Container</a><a class="qm-docs-navigation-menu-page" href="/docs/drawing/">Drawing</a><a class="qm-docs-navigation-menu-page" href="/docs/dropdown/">Dropdown</a><a class="qm-docs-navigation-menu-page" href="/docs/dropdown-button/">Dropdown Button</a><a class="qm-docs-navigation-menu-page" href="/docs/extended-table/">Extended Table</a><a class="qm-docs-navigation-menu-page" href="/docs/file-input/">File Input</a><a class="qm-docs-navigation-menu-page" href="/docs/fluid/">Fluid</a><a class="qm-docs-navigation-menu-page" href="/docs/form-builder/">Form Builder</a><a class="qm-docs-navigation-menu-page" href="/docs/inline-editable/">Inline Editable</a><a class="qm-docs-navigation-menu-page" href="/docs/inline-picker/">Inline Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/inline-select/">Inline Select</a><a class="qm-docs-navigation-menu-page" href="/docs/menu/">Menu</a><a class="qm-docs-navigation-menu-page" href="/docs/meter/">Meter</a><a class="qm-docs-navigation-menu-page" href="/docs/modal/">Modal</a><a class="qm-docs-navigation-menu-page" href="/docs/more-button/">More Button</a><a class="qm-docs-navigation-menu-page" href="/docs/notify/">Notify</a><a class="qm-docs-navigation-menu-page" href="/docs/number-picker/">Number Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/paginator/">Paginator</a><a class="qm-docs-navigation-menu-page" href="/docs/picker/">Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/pivot-table/">Pivot Table</a><a class="qm-docs-navigation-menu-page" href="/docs/plot/">Plot</a><a class="qm-docs-navigation-menu-page" href="/docs/progress-bar/">Progress Bar</a><a class="qm-docs-navigation-menu-page" href="/docs/side-collapsible/">Side Collapsible</a><a class="qm-docs-navigation-menu-page" href="/docs/sidebar/">Sidebar</a><a class="qm-docs-navigation-menu-page" href="/docs/single-select/">Single Select</a><a class="qm-docs-navigation-menu-page" href="/docs/slider/">Slider</a><a class="qm-docs-navigation-menu-page" href="/docs/stepper/">Stepper</a><a class="qm-docs-navigation-menu-page" href="/docs/sticky-table-headers/">Sticky Table Headers</a><a class="qm-docs-navigation-menu-page" href="/docs/tabs/">Tabs</a><a class="qm-docs-navigation-menu-page" href="/docs/tag-input/">Tag Input</a><a class="qm-docs-navigation-menu-page" href="/docs/time-picker/">Time Picker</a><a class="qm-docs-navigation-menu-page" href="/docs/time-slider/">Time Slider</a><a class="qm-docs-navigation-menu-page" href="/docs/titlebar/">Titlebar</a><a class="qm-docs-navigation-menu-page" href="/docs/toggle-button/">Toggle Button</a><a class="qm-docs-navigation-menu-page" href="/docs/toggle/">Toggle</a><a class="qm-docs-navigation-menu-page" href="/docs/tooltip/">Tooltip</a><a class="qm-docs-navigation-menu-page" href="/docs/tree/">Tree</a><a class="qm-docs-navigation-menu-page" href="/docs/visualization-bar/">Visualization Bar</a></div></div><div class="qm-docs-navigation-menu-section"><div class="qm-docs-navigation-menu-section-title">Utilities</div><div class="qm-docs-navigation-menu-section-body"><a class="qm-docs-navigation-menu-page" href="/docs/animate/">Animate</a><a class="qm-docs-navigation-menu-page" href="/docs/click-detector/">Click Detector</a><a class="qm-docs-navigation-menu-page" href="/docs/color-scale/">Color Scale</a><a class="qm-docs-navigation-menu-page" href="/docs/color/">Color</a><a class="qm-docs-navigation-menu-page" href="/docs/component/">Component</a><a class="qm-docs-navigation-menu-page" href="/docs/event-emitter/">Event Emitter</a><a class="qm-docs-navigation-menu-page" href="/docs/fast-click/">Fast Click</a><a class="qm-docs-navigation-menu-page" href="/docs/filter/">Filter</a><a class="qm-docs-navigation-menu-page" href="/docs/format/">Format</a><a class="qm-docs-navigation-menu-page" href="/docs/interpolate/">Interpolate</a><a class="qm-docs-navigation-menu-page" href="/docs/list/">List</a><a class="qm-docs-navigation-menu-page" href="/docs/map/">Map</a><a class="qm-docs-navigation-menu-page" href="/docs/morph-section/">Morph Section</a><a class="qm-docs-navigation-menu-page" href="/docs/morphs/">Morphs</a><a class="qm-docs-navigation-menu-page" href="/docs/palette/">Palette</a><a class="qm-docs-navigation-menu-page" href="/docs/pointer-events/">Pointer Events</a><a class="qm-docs-navigation-menu-page" href="/docs/preferences/">Preferences</a><a class="qm-docs-navigation-menu-page" href="/docs/request/">Request</a><a class="qm-docs-navigation-menu-page" href="/docs/resize-events/">Resize Events</a><a class="qm-docs-navigation-menu-page" href="/docs/search-dom/">Search Dom</a><a class="qm-docs-navigation-menu-page" href="/docs/select/">Select</a><a class="qm-docs-navigation-menu-page" href="/docs/selection/">Selection</a><a class="qm-docs-navigation-menu-page" href="/docs/set/">Set</a><a class="qm-docs-navigation-menu-page" href="/docs/sort/">Sort</a><a class="qm-docs-navigation-menu-page" href="/docs/transition/">Transition</a><a class="qm-docs-navigation-menu-page" href="/docs/user-facing-text/">User Facing Text</a><a class="qm-docs-navigation-menu-page" href="/docs/util/">Util</a><a class="qm-docs-navigation-menu-page" href="/docs/view/">View</a></div></div></div></div></div><div class="qm-docs-content-section-container"><div class="qm-docs-top-section"><div class="qm-docs-top-section-centered qm-docs-top-section-banner"><a class="qm-docs-top-section-source" href="https://github.com/ocadotechnology/hexagonjs/tree/master/docs/content/docs/autocomplete/index.um">Edit Page</a><div class="qm-docs-top-section-title qm-header-font">AutoComplete</div><div class="qm-docs-top-section-description"><div class="qm-html-paragraph">Provides typeahead / suggestions for input fields </div></div></div></div><div class="qm-docs-content-section"><div class="qm-docs-topic"><div class="qm-docs-anchor" id="example"><div class="qm-docs-topic-header qm-header-font">Example<a class="qm-docs-anchor-icon" href="#example"></a></div></div><div class="qm-docs-topic-body"><div class="qm-html-paragraph"><div class="docs-examples"><div class="docs-example"><div class="docs-example-body"><input id="auto-complete" type="text"><script>var data = [
"Bob",
"Dave",
"Steve",
"Kate",
"Bill",
"Alejandro"
]
new hx.AutoComplete("#auto-complete", data)</script></div><div class="docs-example-code-body"><div class="example-code-section"><h3>HTML</h3><div class="qm-code-highlight-codeblock language-html"><pre><code class="qm-code-font"><span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"auto-complete"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>></span></code></pre></div></div><div class="example-code-section"><h3>JavaScript</h3><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-keyword">var</span> data = [
<span class="hljs-string">"Bob"</span>,
<span class="hljs-string">"Dave"</span>,
<span class="hljs-string">"Steve"</span>,
<span class="hljs-string">"Kate"</span>,
<span class="hljs-string">"Bill"</span>,
<span class="hljs-string">"Alejandro"</span>
]
<span class="hljs-keyword">new</span> hx.AutoComplete(<span class="hljs-string">"#auto-complete"</span>, data)</code></pre></div></div></div></div></div> </div></div></div><div class="qm-docs-topic"><div class="qm-docs-anchor" id="api"><div class="qm-docs-topic-header qm-header-font">Api<a class="qm-docs-anchor-icon" href="#api"></a></div></div><div class="qm-docs-topic-body"><div class="qm-html-paragraph"><a href="/docs/autocomplete/changelog">Change Log</a> </div><div class="qm-html-paragraph"><div class="qm-api"><div class="qm-api-group qm-api-prototype-group"><div class="qm-api-group-header qm-api-prototype-group-header qm-header-font">Prototypes</div><div class="qm-api-item qm-api-javascript-prototype qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-prototype"><span class="qm-api-javascript-header-prototype qm-api-header-details qm-code-font" id="hx.autocomplete"><span class="qm-api-javascript-prototype-name">hx.AutoComplete</span><span class="qm-api-javascript-prototype-extends">extends</span><span class="qm-api-javascript-prototype-extender"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/event-emitter/#eventemitter">EventEmitter</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The AutoComplete class can be used to add an auto complete suggestion dropdown to any input field. </div></div><div class="qm-api-group qm-api-constructor-group"><div class="qm-api-group-header qm-api-constructor-group-header qm-header-font">Constructors</div><div class="qm-api-item qm-api-javascript-constructor qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-constructor"><span class="qm-api-javascript-header-constructor-signature qm-api-header-details qm-code-font" id="hx.autocomplete"><span class="qm-api-javascript-header-constructor-name">hx.AutoComplete</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">selector</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a> / HTMLElement</span></span></span><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">items</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> / <a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a></span></span></span><span class="qm-api-javascript-header-function-arg qm-api-optional"><span class="qm-api-javascript-header-function-arg-name">options</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span></span></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Add an auto complete suggestions dropdown to an input box </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="selector"><span class="qm-api-javascript-header-property-name">selector</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a> / HTMLElement</span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description">The selector of the input box to add an auto complete to.</div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="items"><span class="qm-api-javascript-header-property-name">items</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> / <a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The items to use as suggestions for the input field. Data can be specified as an array of items or as a function that returns an array of items. </div><div class="qm-html-paragraph">The data must be in one of the following formats: </div><div class="qm-html-paragraph"><div class="qm-docs-subsection"><div class="qm-docs-subsection-header qm-header-font">Array</div><div class="qm-docs-subsection-body"><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-json"><pre><code class="qm-code-font">[
<span class="hljs-string">"Bob"</span>,
<span class="hljs-string">"Steve"</span>,
...
]</code></pre></div> </div><div class="qm-html-paragraph">By default, the data is expected as an array of string values. If object based data is passed in, an <code class="qm-code-highlight-code qm-code-font">inputMap</code> must be provided in the options: </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font">data = [
{
name <span class="hljs-string">"Bob"</span>,
<span class="hljs-attr">age</span>: <span class="hljs-number">21</span>
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">"Steve"</span>,
<span class="hljs-attr">age</span>: <span class="hljs-number">25</span>
}
]
options = {
<span class="hljs-attr">inputMap</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
<span class="hljs-keyword">return</span> item.name + <span class="hljs-string">', '</span> + item.age
}
}</code></pre></div> </div><div class="qm-html-paragraph">A <code class="qm-code-highlight-code qm-code-font">renderer</code> and <code class="qm-code-highlight-code qm-code-font">filterOptions.searchValues</code> can also be specified to change how the text is displayed and what data is searchable, independent of the <code class="qm-code-highlight-code qm-code-font">inputMap</code> </div></div></div>.
<div class="qm-docs-subsection"><div class="qm-docs-subsection-header qm-header-font">Function</div><div class="qm-docs-subsection-body"><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-keyword">var</span> data = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">term, callback</span>)</span>{
hx.json(<span class="hljs-string">'path/to/data?search='</span>+term, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e, r</span>) </span>{
callback(r.responseText)
})
}</code></pre></div> </div><div class="qm-html-paragraph">A 'Loading...' message will be shown whilst the AutoComplete waits for a response from this function. </div><div class="qm-html-paragraph">It can be used in conjunction with the internal matching or be used to match externally when setting the <code class="qm-code-highlight-code qm-code-font">matchType</code> to 'external': </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">data</span> (<span class="hljs-params">term, callback</span>) </span>{
<span class="hljs-keyword">if</span> (term.length > <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> callback(townAndCountyData.filter(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">d</span>) </span>{
<span class="hljs-keyword">var</span> d = townAndCountyData[_i]
<span class="hljs-keyword">var</span> name = d.name.toLowerCase()
<span class="hljs-keyword">var</span> term = term.toLowerCase()
<span class="hljs-keyword">var</span> county = d.county.toLowerCase()
<span class="hljs-keyword">return</span> name.indexOf(term) > <span class="hljs-number">-1</span> || county.indexOf(term) > <span class="hljs-number">-1</span>)
}))
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">return</span> callback([])
}
}
options.matchType = <span class="hljs-string">'external'</span></code></pre></div> </div><div class="qm-html-paragraph">The term passed in is the current value of the input field (for use as a search term). </div><div class="qm-html-paragraph">The callback is the function that should be called to pass the data back to the AutoComplete to display. </div><div class="qm-html-paragraph">The callback must be called for the AutoComplete to show. </div></div></div> </div></div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head qm-api-optional"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="options"><span class="qm-api-javascript-header-object-name">options</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-group qm-api-property-group"><div class="qm-api-group-header qm-api-property-group-header qm-header-font">Properties</div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="filter"><span class="qm-api-javascript-header-function-name">filter</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">array</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span></span><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">term</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The function to use when filtering internally. Should only be used when one of the <code class="qm-code-highlight-code qm-code-font">hx.filter</code> methods isn't suitable for filtering the data. </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="array"><span class="qm-api-javascript-header-property-name">array</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The array from the AutoComplete cache or data source </div></div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="term"><span class="qm-api-javascript-header-property-name">term</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The search term to use when filtering </div></div></div></div></div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="array"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The filtered data </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="filteroptions"><span class="qm-api-javascript-header-object-name">filterOptions</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The options to use when filtering internally. The available options can be found on the page. The default <code class="qm-code-highlight-code qm-code-font">searchValues</code> option uses the passed in input map to search on. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="inputmap"><span class="qm-api-javascript-header-function-name">inputMap</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">item</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type">Any</span></span></span></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A function used to convert objects or nested arrays passed to the AutoComplete data into searchable strings. </div><div class="qm-html-paragraph">Setting the inputMap defines what data should be shown in the dropdown and what should be searchable. </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-keyword">var</span> data = [
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span>
age: <span class="hljs-number">12</span>
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>
age: <span class="hljs-number">19</span>
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>
age: <span class="hljs-number">42</span>
}
]
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inputMap</span> (<span class="hljs-params">item</span>) </span>{
<span class="hljs-keyword">return</span> item.name + <span class="hljs-string">', '</span> + item.age
}</code></pre></div> </div><div class="qm-html-paragraph">The above inputMap would return 'Bob, 12' which would then be searchable and display as the text in the dropdown. </div><div class="qm-html-paragraph">A custom renderer can also be defined to change what displays in the dropdown. </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="item"><span class="qm-api-javascript-header-property-name">item</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type">Any</span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The data item passed from the AutoComplete data. </div></div></div></div></div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="string"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text string to display in the input field, the dropdown and to be searchable </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="matchtype"><span class="qm-api-javascript-header-property-name">matchType</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The type of filtering the AutoComplete should use when filtering internally </div><div class="qm-html-paragraph">The internal filter uses the <code class="qm-code-highlight-code qm-code-font">hx.filter</code> functions. All the filter types can be specified as the match type (e.g. 'startsWith', 'exact' or 'fuzzy') and the default value is 'contains'. </div><div class="qm-html-paragraph">In addition to the internal filter, external matching can be used (where the data returned from the callback is used directly and not sorted/filtered internally) by setting the match type to 'external' </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">'contains'</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="minlength"><span class="qm-api-javascript-header-property-name">minLength</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The minimum length of text input before suggestions will be shown. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">0</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="mustmatch"><span class="qm-api-javascript-header-property-name">mustMatch</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Whether the final value in the input field must match a value from the suggestions. </div><div class="qm-html-paragraph">If set to true, the input field will be updated to the first result of the filtered data when the user changes focus. If no matches are found, the input field is cleared. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">false</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="noresultsmessage"><span class="qm-api-javascript-header-property-name">noResultsMessage</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text to display when no results are found. If this is not defined or set to '' then the dropdown will not be shown when there are no results. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value"><code class="qm-code-highlight-code qm-code-font">hx.userFacingText('autocomplete', 'noResultsFound')</code></span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="otherresultsmessage"><span class="qm-api-javascript-header-property-name">otherResultsMessage</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text to display at the top of the other results when the <code class="qm-code-highlight-code qm-code-font">showOtherResults</code> option is true. </div><div class="qm-html-paragraph">The text must be set to a valid string, setting this option to <code class="qm-code-highlight-code qm-code-font">undefined</code> or <code class="qm-code-highlight-code qm-code-font">''</code> will not prevent the heading from showing as it acts as a divider between matching and non-matching results. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value"><code class="qm-code-highlight-code qm-code-font">hx.userFacingText('autocomplete', 'otherResults')</code></span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="placeholder"><span class="qm-api-javascript-header-property-name">placeholder</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The placeholder text for the input. If the placeholder is undefiend and a min-length is specified, a placeholder of 'Min length {x} characters' is used. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="pleaseentermincharactersmessage"><span class="qm-api-javascript-header-property-name">pleaseEnterMinCharactersMessage</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text to display when the user has not entered enough text. </div><div class="qm-html-paragraph">When setting this, the minimum number of characters can be substituted in using the <code class="qm-code-highlight-code qm-code-font">'$minLength'</code> variable, e.g. </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font">options = {
<span class="hljs-attr">minLength</span>: <span class="hljs-number">3</span>,
pleaseEnterMinCharactersMessage = <span class="hljs-string">'Please enter $minLength characters'</span>
}
<span class="hljs-comment">// Evaluates to 'Please enter 3 characters'</span></code></pre></div> </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value"><code class="qm-code-highlight-code qm-code-font">hx.userFacingText('autocomplete', 'pleaseEnterMinCharacters')</code></span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="renderer"><span class="qm-api-javascript-header-function-name">renderer</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">elem</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type">HTMLElement</span></span></span><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">item</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span></span></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A function used to render the items in the dropdown. </div><div class="qm-html-paragraph">The default renderer sets the html to the item value and the onclick sets the input value to the same value: </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">renderer</span> (<span class="hljs-params">elem, item</span>)</span>{
hx.select(elem)
.text(item)
}</code></pre></div> </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="elem"><span class="qm-api-javascript-header-property-name">elem</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type">HTMLElement</span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The HTMLElement to populate </div></div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="item"><span class="qm-api-javascript-header-object-name">item</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The data item to populate the element with. </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="showall"><span class="qm-api-javascript-header-property-name">showAll</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Determines whether all the data will be shown when no text is present and the user clicks on the input. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">true</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="showotherresults"><span class="qm-api-javascript-header-property-name">showOtherResults</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Determines whether to show results under an 'other results' heading that are in the data but don't match the input text. </div><div class="qm-html-paragraph">Only used when not using external matching. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">false</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="trimtrailingspaces"><span class="qm-api-javascript-header-property-name">trimTrailingSpaces</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">An option to enable whitespace trimming at the end of the input value if no results are found for that string. </div></div></div></div></div></div></div></div></div></div></div></div></div></div><div class="qm-api-group qm-api-event-group"><div class="qm-api-group-header qm-api-event-group-header qm-header-font">Events</div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="change"><span class="qm-api-javascript-header-property-name">change</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The event called whenever the input text is updated by the auto complete object. The data is the value of the input field. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="dropdown.change"><span class="qm-api-javascript-header-property-name">dropdown.change</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Emitted when the dropdown is shown or hidden. The data is a boolean indicating whether or not the dropdown is hidden. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="dropdown.hideend"><span class="qm-api-javascript-header-property-name">dropdown.hideend</span><span class="qm-api-javascript-header-property-type"></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Emitted when the dropdown animation ends. No data is sent with this event. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="dropdown.hidestart"><span class="qm-api-javascript-header-property-name">dropdown.hidestart</span><span class="qm-api-javascript-header-property-type"></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Emitted when the dropdown animation starts. No data is sent with this event. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="dropdown.showend"><span class="qm-api-javascript-header-property-name">dropdown.showend</span><span class="qm-api-javascript-header-property-type"></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Emitted when the dropdown animation finishes. No data is sent with this event. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="dropdown.showstart"><span class="qm-api-javascript-header-property-name">dropdown.showstart</span><span class="qm-api-javascript-header-property-type"></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Emitted when the dropdown animation starts. No data is sent with this event. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-event qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="highlight"><span class="qm-api-javascript-header-object-name">highlight</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The event emitted when an item is set as the active item. This can only be done by the keyboard or when the user clicks on an item </div></div><div class="qm-api-group qm-api-property-group"><div class="qm-api-group-header qm-api-property-group-header qm-header-font">Properties</div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="eventtype"><span class="qm-api-javascript-header-property-name">eventType</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The type of event that caused the selection: </div><div class="qm-html-paragraph"><ul class="qm-docs-list"><li><div class="qm-html-paragraph">'click' - User clicked </div></li><li><div class="qm-html-paragraph">'arrow' - User used the arrow keys </div></li></ul> </div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="item"><span class="qm-api-javascript-header-property-name">item</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a> / <a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description">The item as it was passed into the select.</div></div></div></div></div></div></div></div></div><div class="qm-api-group qm-api-method-group"><div class="qm-api-group-header qm-api-method-group-header qm-header-font">Methods</div><div class="qm-api-item qm-api-javascript-method qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="clearcache"><span class="qm-api-javascript-header-function-name">clearCache</span><span class="qm-api-javascript-header-function-args"></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A method to clear the cached data in the auto complete. </div><div class="qm-html-paragraph">It is called internally when the user changes focus (either by clicking outside the input box or by tabbing out of the box) but can be called manually if the data needs to be cleared more frequently (i.e. as the user types) </div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="autocomplete"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">This <span class="qm-api-type-standalone qm-code-font"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span> for chaining </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-method qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="hide"><span class="qm-api-javascript-header-function-name">hide</span><span class="qm-api-javascript-header-function-args"></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A method to hide the autocomplete menu. </div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="autocomplete"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">This <span class="qm-api-type-standalone qm-code-font"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span> for chaining </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-method qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="value"><span class="qm-api-javascript-header-function-name">value</span><span class="qm-api-javascript-header-function-args"></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Getting the value of the auto complete. </div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="string"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The input value </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-method qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="value"><span class="qm-api-javascript-header-function-name">value</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">value</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Setting the value of the auto complete. </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="value"><span class="qm-api-javascript-header-property-name">value</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The value to set the autocomplete to. </div></div></div></div></div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="autocomplete"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">This <span class="qm-api-type-standalone qm-code-font"><span class="qm-api-type"><a class="qm-api-type-link" href="/docs/autocomplete/#autocomplete">AutoComplete</a></span></span> for chaining </div></div></div></div></div></div></div></div></div></div></div></div></div></div><div class="qm-api-group qm-api-function-group"><div class="qm-api-group-header qm-api-function-group-header qm-header-font">Functions</div><div class="qm-api-item qm-api-javascript-function qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="hx.autocomplete"><span class="qm-api-javascript-header-function-name">hx.autoComplete</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">items</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> / <a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a></span></span></span><span class="qm-api-javascript-header-function-arg qm-api-optional"><span class="qm-api-javascript-header-function-arg-name">options</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span></span></span></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type">Selection</span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Creates a new AutoComplete set up on a detached element, wrapped in a selection </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="items"><span class="qm-api-javascript-header-property-name">items</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a> / <a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The items to use as suggestions for the input field. Data can be specified as an array of items or as a function that returns an array of items. </div><div class="qm-html-paragraph">The data must be in one of the following formats: </div><div class="qm-html-paragraph"><div class="qm-docs-subsection"><div class="qm-docs-subsection-header qm-header-font">Array</div><div class="qm-docs-subsection-body"><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-json"><pre><code class="qm-code-font">[
<span class="hljs-string">"Bob"</span>,
<span class="hljs-string">"Steve"</span>,
...
]</code></pre></div> </div><div class="qm-html-paragraph">By default, the data is expected as an array of string values. If object based data is passed in, an <code class="qm-code-highlight-code qm-code-font">inputMap</code> must be provided in the options: </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font">data = [
{
name <span class="hljs-string">"Bob"</span>,
<span class="hljs-attr">age</span>: <span class="hljs-number">21</span>
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">"Steve"</span>,
<span class="hljs-attr">age</span>: <span class="hljs-number">25</span>
}
]
options = {
<span class="hljs-attr">inputMap</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
<span class="hljs-keyword">return</span> item.name + <span class="hljs-string">', '</span> + item.age
}
}</code></pre></div> </div><div class="qm-html-paragraph">A <code class="qm-code-highlight-code qm-code-font">renderer</code> and <code class="qm-code-highlight-code qm-code-font">filterOptions.searchValues</code> can also be specified to change how the text is displayed and what data is searchable, independent of the <code class="qm-code-highlight-code qm-code-font">inputMap</code> </div></div></div>.
<div class="qm-docs-subsection"><div class="qm-docs-subsection-header qm-header-font">Function</div><div class="qm-docs-subsection-body"><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-keyword">var</span> data = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">term, callback</span>)</span>{
hx.json(<span class="hljs-string">'path/to/data?search='</span>+term, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e, r</span>) </span>{
callback(r.responseText)
})
}</code></pre></div> </div><div class="qm-html-paragraph">A 'Loading...' message will be shown whilst the AutoComplete waits for a response from this function. </div><div class="qm-html-paragraph">It can be used in conjunction with the internal matching or be used to match externally when setting the <code class="qm-code-highlight-code qm-code-font">matchType</code> to 'external': </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">data</span> (<span class="hljs-params">term, callback</span>) </span>{
<span class="hljs-keyword">if</span> (term.length > <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> callback(townAndCountyData.filter(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">d</span>) </span>{
<span class="hljs-keyword">var</span> d = townAndCountyData[_i]
<span class="hljs-keyword">var</span> name = d.name.toLowerCase()
<span class="hljs-keyword">var</span> term = term.toLowerCase()
<span class="hljs-keyword">var</span> county = d.county.toLowerCase()
<span class="hljs-keyword">return</span> name.indexOf(term) > <span class="hljs-number">-1</span> || county.indexOf(term) > <span class="hljs-number">-1</span>)
}))
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">return</span> callback([])
}
}
options.matchType = <span class="hljs-string">'external'</span></code></pre></div> </div><div class="qm-html-paragraph">The term passed in is the current value of the input field (for use as a search term). </div><div class="qm-html-paragraph">The callback is the function that should be called to pass the data back to the AutoComplete to display. </div><div class="qm-html-paragraph">The callback must be called for the AutoComplete to show. </div></div></div> </div></div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head qm-api-optional"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="options"><span class="qm-api-javascript-header-object-name">options</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-group qm-api-property-group"><div class="qm-api-group-header qm-api-property-group-header qm-header-font">Properties</div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="filter"><span class="qm-api-javascript-header-function-name">filter</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">array</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span></span><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">term</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The function to use when filtering internally. Should only be used when one of the <code class="qm-code-highlight-code qm-code-font">hx.filter</code> methods isn't suitable for filtering the data. </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="array"><span class="qm-api-javascript-header-property-name">array</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The array from the AutoComplete cache or data source </div></div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="term"><span class="qm-api-javascript-header-property-name">term</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The search term to use when filtering </div></div></div></div></div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="array"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The filtered data </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="filteroptions"><span class="qm-api-javascript-header-object-name">filterOptions</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The options to use when filtering internally. The available options can be found on the page. The default <code class="qm-code-highlight-code qm-code-font">searchValues</code> option uses the passed in input map to search on. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="inputmap"><span class="qm-api-javascript-header-function-name">inputMap</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">item</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type">Any</span></span></span></span><span class="qm-api-javascript-header-function-returns"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A function used to convert objects or nested arrays passed to the AutoComplete data into searchable strings. </div><div class="qm-html-paragraph">Setting the inputMap defines what data should be shown in the dropdown and what should be searchable. </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-keyword">var</span> data = [
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span>
age: <span class="hljs-number">12</span>
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>
age: <span class="hljs-number">19</span>
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>
age: <span class="hljs-number">42</span>
}
]
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inputMap</span> (<span class="hljs-params">item</span>) </span>{
<span class="hljs-keyword">return</span> item.name + <span class="hljs-string">', '</span> + item.age
}</code></pre></div> </div><div class="qm-html-paragraph">The above inputMap would return 'Bob, 12' which would then be searchable and display as the text in the dropdown. </div><div class="qm-html-paragraph">A custom renderer can also be defined to change what displays in the dropdown. </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="item"><span class="qm-api-javascript-header-property-name">item</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type">Any</span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The data item passed from the AutoComplete data. </div></div></div></div></div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="string"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text string to display in the input field, the dropdown and to be searchable </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="matchtype"><span class="qm-api-javascript-header-property-name">matchType</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The type of filtering the AutoComplete should use when filtering internally </div><div class="qm-html-paragraph">The internal filter uses the <code class="qm-code-highlight-code qm-code-font">hx.filter</code> functions. All the filter types can be specified as the match type (e.g. 'startsWith', 'exact' or 'fuzzy') and the default value is 'contains'. </div><div class="qm-html-paragraph">In addition to the internal filter, external matching can be used (where the data returned from the callback is used directly and not sorted/filtered internally) by setting the match type to 'external' </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">'contains'</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="minlength"><span class="qm-api-javascript-header-property-name">minLength</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The minimum length of text input before suggestions will be shown. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">0</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="mustmatch"><span class="qm-api-javascript-header-property-name">mustMatch</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Whether the final value in the input field must match a value from the suggestions. </div><div class="qm-html-paragraph">If set to true, the input field will be updated to the first result of the filtered data when the user changes focus. If no matches are found, the input field is cleared. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">false</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="noresultsmessage"><span class="qm-api-javascript-header-property-name">noResultsMessage</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text to display when no results are found. If this is not defined or set to '' then the dropdown will not be shown when there are no results. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value"><code class="qm-code-highlight-code qm-code-font">hx.userFacingText('autocomplete', 'noResultsFound')</code></span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="otherresultsmessage"><span class="qm-api-javascript-header-property-name">otherResultsMessage</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text to display at the top of the other results when the <code class="qm-code-highlight-code qm-code-font">showOtherResults</code> option is true. </div><div class="qm-html-paragraph">The text must be set to a valid string, setting this option to <code class="qm-code-highlight-code qm-code-font">undefined</code> or <code class="qm-code-highlight-code qm-code-font">''</code> will not prevent the heading from showing as it acts as a divider between matching and non-matching results. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value"><code class="qm-code-highlight-code qm-code-font">hx.userFacingText('autocomplete', 'otherResults')</code></span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="placeholder"><span class="qm-api-javascript-header-property-name">placeholder</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The placeholder text for the input. If the placeholder is undefiend and a min-length is specified, a placeholder of 'Min length {x} characters' is used. </div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="pleaseentermincharactersmessage"><span class="qm-api-javascript-header-property-name">pleaseEnterMinCharactersMessage</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The text to display when the user has not entered enough text. </div><div class="qm-html-paragraph">When setting this, the minimum number of characters can be substituted in using the <code class="qm-code-highlight-code qm-code-font">'$minLength'</code> variable, e.g. </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font">options = {
<span class="hljs-attr">minLength</span>: <span class="hljs-number">3</span>,
pleaseEnterMinCharactersMessage = <span class="hljs-string">'Please enter $minLength characters'</span>
}
<span class="hljs-comment">// Evaluates to 'Please enter 3 characters'</span></code></pre></div> </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value"><code class="qm-code-highlight-code qm-code-font">hx.userFacingText('autocomplete', 'pleaseEnterMinCharacters')</code></span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-function"><span class="qm-api-javascript-header-function-signature qm-api-header-details qm-code-font" id="renderer"><span class="qm-api-javascript-header-function-name">renderer</span><span class="qm-api-javascript-header-function-args"><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">elem</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type">HTMLElement</span></span></span><span class="qm-api-javascript-header-function-arg"><span class="qm-api-javascript-header-function-arg-name">item</span><span class="qm-api-javascript-header-function-arg-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span></span></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A function used to render the items in the dropdown. </div><div class="qm-html-paragraph">The default renderer sets the html to the item value and the onclick sets the input value to the same value: </div><div class="qm-html-paragraph"><div class="qm-code-highlight-codeblock language-js"><pre><code class="qm-code-font"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">renderer</span> (<span class="hljs-params">elem, item</span>)</span>{
hx.select(elem)
.text(item)
}</code></pre></div> </div></div><div class="qm-api-group qm-api-arg-group"><div class="qm-api-group-header qm-api-arg-group-header qm-header-font">Arguments</div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="elem"><span class="qm-api-javascript-header-property-name">elem</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type">HTMLElement</span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The HTMLElement to populate </div></div></div></div></div><div class="qm-api-item qm-api-javascript-arg qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-object"><span class="qm-api-javascript-header-object qm-api-header-details qm-code-font" id="item"><span class="qm-api-javascript-header-object-name">item</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">The data item to populate the element with. </div></div></div></div></div></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="showall"><span class="qm-api-javascript-header-property-name">showAll</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Determines whether all the data will be shown when no text is present and the user clicks on the input. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">true</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="showotherresults"><span class="qm-api-javascript-header-property-name">showOtherResults</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">Determines whether to show results under an 'other results' heading that are in the data but don't match the input text. </div><div class="qm-html-paragraph">Only used when not using external matching. </div></div><div class="qm-api-default"><span class="qm-api-default-key">Default: </span><span class="qm-api-default-value">false</span></div></div></div></div><div class="qm-api-item qm-api-javascript-property qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-property"><span class="qm-api-javascript-header-property qm-api-header-details qm-code-font" id="trimtrailingspaces"><span class="qm-api-javascript-header-property-name">trimTrailingSpaces</span><span class="qm-api-javascript-header-property-type"><span class="qm-api-type"><a class="qm-api-type-link" href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></span></span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">An option to enable whitespace trimming at the end of the input value if no results are found for that string. </div></div></div></div></div></div></div></div></div></div><div class="qm-api-group qm-api-returns-group"><div class="qm-api-group-header qm-api-returns-group-header qm-header-font">Returns</div><div class="qm-api-item qm-api-javascript-returns qm-api-collapsible"><div class="qm-api-collapsible-heading"><div class="qm-api-collapsible-toggle"><i class="qm-api-chevron-icon"></i></div><div class="qm-api-collapsible-head"><div class="qm-api-item-head"><div class="qm-api-item-header qm-api-item-header-type"><span class="qm-api-javascript-header-type qm-api-header-details qm-code-font" id="selection"><span class="qm-api-type">Selection</span></span><span class="qm-api-header-tags"></span></div></div></div></div><div class="qm-api-collapsible-content"><div class="qm-api-item-content"><div class="qm-api-description"><div class="qm-html-paragraph">A selection containing an element with an AutoComplete initialised on it </div></div></div></div></div></div></div></div></div></div></div> </div></div></div></div></div></div><script src="/resources/quantum-docs.js"></script><script src="/resources/quantum-api.js"></script><script>window.quantum.docs.createHeaderToggle("186D8751B7547EC7C0A1C957EFA1F0D6");</script></body></html> | high | 0.521076 | 392 |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools.Commands {
using DebuggerOptions = Microsoft.PythonTools.Debugger.Concord.DebuggerOptions;
internal class UsePythonStepping : DkmDebuggerCommand {
public UsePythonStepping(IServiceProvider serviceProvider)
: base(serviceProvider) {
}
public override int CommandId {
get { return (int)PkgCmdIDList.cmdidUsePythonStepping; }
}
protected override bool IsPythonDeveloperCommand {
get { return true; }
}
public override EventHandler BeforeQueryStatus {
get {
return (sender, args) => {
base.BeforeQueryStatus(sender, args);
var cmd = (OleMenuCommand)sender;
cmd.Checked = DebuggerOptions.UsePythonStepping;
};
}
}
public override void DoCommand(object sender, EventArgs args) {
DebuggerOptions.UsePythonStepping = !DebuggerOptions.UsePythonStepping;
}
}
}
| high | 0.556982 | 393 |
proc getEntityNames {} {
return [list kernel_system k0_ZTS9MMpara_v2,0]
} | high | 0.304773 | 394 |
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * 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. --
-- --
-- * Neither the name of the Vadim Godunko, IE 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 COPYRIGHT HOLDERS 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 COPYRIGHT --
-- HOLDER 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. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Generic_Collections;
package AMF.Standard_Profile_L3.Build_Components.Collections is
pragma Preelaborate;
package Standard_Profile_L3_Build_Component_Collections is
new AMF.Generic_Collections
(Standard_Profile_L3_Build_Component,
Standard_Profile_L3_Build_Component_Access);
type Set_Of_Standard_Profile_L3_Build_Component is
new Standard_Profile_L3_Build_Component_Collections.Set with null record;
Empty_Set_Of_Standard_Profile_L3_Build_Component : constant Set_Of_Standard_Profile_L3_Build_Component;
type Ordered_Set_Of_Standard_Profile_L3_Build_Component is
new Standard_Profile_L3_Build_Component_Collections.Ordered_Set with null record;
Empty_Ordered_Set_Of_Standard_Profile_L3_Build_Component : constant Ordered_Set_Of_Standard_Profile_L3_Build_Component;
type Bag_Of_Standard_Profile_L3_Build_Component is
new Standard_Profile_L3_Build_Component_Collections.Bag with null record;
Empty_Bag_Of_Standard_Profile_L3_Build_Component : constant Bag_Of_Standard_Profile_L3_Build_Component;
type Sequence_Of_Standard_Profile_L3_Build_Component is
new Standard_Profile_L3_Build_Component_Collections.Sequence with null record;
Empty_Sequence_Of_Standard_Profile_L3_Build_Component : constant Sequence_Of_Standard_Profile_L3_Build_Component;
private
Empty_Set_Of_Standard_Profile_L3_Build_Component : constant Set_Of_Standard_Profile_L3_Build_Component
:= (Standard_Profile_L3_Build_Component_Collections.Set with null record);
Empty_Ordered_Set_Of_Standard_Profile_L3_Build_Component : constant Ordered_Set_Of_Standard_Profile_L3_Build_Component
:= (Standard_Profile_L3_Build_Component_Collections.Ordered_Set with null record);
Empty_Bag_Of_Standard_Profile_L3_Build_Component : constant Bag_Of_Standard_Profile_L3_Build_Component
:= (Standard_Profile_L3_Build_Component_Collections.Bag with null record);
Empty_Sequence_Of_Standard_Profile_L3_Build_Component : constant Sequence_Of_Standard_Profile_L3_Build_Component
:= (Standard_Profile_L3_Build_Component_Collections.Sequence with null record);
end AMF.Standard_Profile_L3.Build_Components.Collections;
| high | 0.729279 | 395 |
data {
int d_int;
int r_int;
real d_real;
real r_real;
}
transformed data {
int transformed_data_int;
real transformed_data_real;
transformed_data_real = pow(d_real, r_real);
transformed_data_real = pow(d_int, r_real);
transformed_data_real = pow(d_real, d_int);
transformed_data_real = pow(r_int, d_int);
}
parameters {
real p_real;
real y_p;
}
transformed parameters {
real transformed_param_real;
transformed_param_real = pow(d_real, r_real);
transformed_param_real = pow(d_int , r_real);
transformed_param_real = pow(d_real, d_int);
transformed_param_real = pow(r_int, d_int);
transformed_param_real = pow(r_int, p_real);
transformed_param_real = pow(r_real,p_real);
transformed_param_real = pow(p_real,p_real);
transformed_param_real = pow(p_real,r_int);
transformed_param_real = pow(p_real,r_real);
}
model {
y_p ~ normal(0,1);
}
| high | 0.602454 | 396 |
# Activity 10/18/2021
## STAT 445 / 645 -- Section 1001 <br> Instructor: Colin Grudzien<br>
## Instructions:
We will work through the following series of activities as a group and hold small group work and discussions in Zoom Breakout Rooms. Follow the instructions in each sub-section when the instructor assigns you to a breakout room.
## Activities:
To perform some matrix operations, it can be helpful to use some non-base functions designed for this. We will require the library `matlab`
```{r}
require("matlab")
```
### Activity 1: Diagonalization
Suppose we are given the following matrix
```{r}
A <- matrix(seq(3, 27, by=3), nrow=3, ncol=3)
```
#### Question 1:
Compute the rank of the matrix `A` . Then compute the eigen values of the matrix `A`. How is the rank related to the eigenvalues of the matrix?
##### Solution:
We compute the rank as follows:
```{r}
qr(A)$rank
```
The eigen decomposition is computed as:
```{r}
eigen(A)
```
We see that the rank of the matrix `A` is 2, and that it has exactly 2 non-zero eigenvalues.
#### Question 2:
Use the eigen decomposition as follows: extract the matrix of the eigenvectors by calling the variable `$vectors` and assign these vectors to a matrix called `C`. Check if it is possible to invert this matrix and if so, define the inverse `C_inv`. Explain why this is possible or why not.
##### Solution:
We define the eigen decompostion and the matrix `C` as follows.
```{r}
e_decomp <- eigen(A)
C <- e_decomp$vectors
```
Notice,
```{r}
det(C)
```
so that it is invertible. We may look instead at
```{r}
eigen(C)
```
to notice that this has complex, non-zero eigenvalues.
Therefore, we assign `C_inv` as follows:
```{r}
C_inv <- solve(C)
```
#### Question 3:
Now try the following, multiply `A` by `C_inv` on the left and `C` on the right. What do you notice about the values off diagonal?
Try using the following comparison to see how close the elements are to the value zero,
```{r, eval=FALSE}
abs(product) <= ones(3) * 10e-14
```
Take the diagonal elements of the product above and find the absolute difference of these from the eigenvalues of `A`. What do you notice about the result.
##### Solution:
```{r}
product <- C_inv %*% A %*% C
product
abs(product) <= ones(3) * 10e-14
```
This is numerically a diagonal matrix, with a zero also in the last diagonal position.
If we take the absolute difference of the diagonal with the eigenvalues, we get
```{r}
abs(diag(product) - e_decomp$values)
```
We see that these are indeed the eigenvalues. Multiplying on the left and right as above gave a change of coordinates to the diagonal form of the transformation represented by `A`.
| medium | 0.387343 | 397 |
# Download and install the ASP.NET Core Hosting Bundle
mkdir C:\DotNet
Invoke-WebRequest -UseBasicParsing -Uri 'https://download.visualstudio.microsoft.com/download/pr/9b9f4a6e-aef8-41e0-90db-bae1b0cf4e34/4ab93354cdff8991d91a9f40d022d450/dotnet-hosting-3.1.6-win.exe' -OutFile C:\DotNet\aspdotnet-3.1-installer.exe
Start-Process -Wait C:\DotNet\aspdotnet-3.1-installer.exe -ArgumentList '/install','/quiet','/norestart'
# Download and install our application
mkdir C:\AppServer
Invoke-WebRequest -UseBasicParsing -Uri 'http://s3.amazonaws.com/us-east-1.andyhoppatamazon.com/samples/ASPNETCoreDemo.zip' -OutFile C:\AppServer\ASPNETCoreDemo.zip
Expand-Archive C:\AppServer\ASPNetCoreDemo.zip C:\AppServer\
# Register and start our service
New-Service ASPNetCoreDemo -BinaryPathName "C:\AppServer\ASPNETCoreDemo.exe --service --urls http://+:80"
Start-Service ASPNetCoreDemo
# Open the firewall to allow port 80
netsh advfirewall firewall add rule name="ASPNetCoreDemo" dir=in action=allow protocol=TCP localport=80
| high | 0.220248 | 398 |
FROM elasticsearch:5-alpine
COPY ./config/elasticsearch.yml /usr/share/elasticsearch/config/elasticsearch.yml
# 数据存储文件不在版本库中
VOLUME [ "/usr/share/elasticsearch/data" ] | high | 0.273924 | 399 |
/*
* Copyright 2021 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
*
* https://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 com.example.androiddevchallenge.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.androiddevchallenge.R
val RobotoFontFamily = FontFamily(
Font(R.font.roboto_bold, FontWeight.Bold),
Font(R.font.roboto_black, FontWeight.Black),
Font(R.font.roboto_regular)
)
// Set of Material typography styles to start with
val typography = Typography(
h1 = TextStyle(
color = primaryColor,
fontFamily = RobotoFontFamily,
fontWeight = FontWeight.Black,
fontSize = 200.sp,
letterSpacing = (-14).sp,
),
h2 = TextStyle(
color = secondaryColor,
fontFamily = RobotoFontFamily,
fontWeight = FontWeight.Black,
fontSize = 200.sp,
letterSpacing = (-14).sp
),
h3 = TextStyle(
color = primaryColorVariant,
fontFamily = RobotoFontFamily,
fontWeight = FontWeight.Black,
fontSize = 200.sp,
letterSpacing = (-14).sp
),
body1 = TextStyle(
color = textColor,
fontFamily = RobotoFontFamily,
fontSize = 14.sp,
),
body2 = TextStyle(
color = textColor,
fontFamily = RobotoFontFamily,
fontWeight = FontWeight.Black,
fontSize = 14.sp,
),
caption = TextStyle(
color = secondaryColor,
fontFamily = RobotoFontFamily,
fontWeight = FontWeight.Black,
fontSize = 100.sp,
letterSpacing = (-7).sp
)
)
| high | 0.836027 | 400 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.3.2 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
| high | 0.956735 | 401 |
#if defined paraboloid_point_shape
#extension GL_EXT_frag_depth : enable
#endif
precision highp float;
precision highp int;
uniform mat4 viewMatrix;
uniform mat4 uViewInv;
uniform mat4 uProjInv;
uniform vec3 cameraPosition;
uniform mat4 projectionMatrix;
uniform float uOpacity;
uniform float blendHardness;
uniform float blendDepthSupplement;
uniform float fov;
uniform float uSpacing;
uniform float near;
uniform float far;
uniform float uPCIndex;
uniform float uScreenWidth;
uniform float uScreenHeight;
varying vec3 vColor;
varying float vLogDepth;
varying vec3 vViewPosition;
varying float vRadius;
varying float vPointSize;
varying vec3 vPosition;
// CLOI
#if defined(use_cloi)
uniform float cloiValue;
varying float vImp;
#endif
float specularStrength = 1.0;
void main()
{
// gl_FragColor = vec4(vColor, 1.0);
vec3 color = vColor;
vec4 finalColor = vec4(color, 1.0);
float depth = gl_FragCoord.z;
#if defined(circle_point_shape) || defined(paraboloid_point_shape)
float u = 2.0 * gl_PointCoord.x - 1.0;
float v = 2.0 * gl_PointCoord.y - 1.0;
#endif
#if defined(circle_point_shape)
float cc = u * u + v * v;
if (cc > 1.0)
{
discard;
}
#endif
#if defined color_type_indices
finalColor = vec4(color, uPCIndex / 255.0);
#else
finalColor = vec4(color, uOpacity);
#endif
#if defined paraboloid_point_shape
float wi = 0.0 - (u * u + v * v);
vec4 pos = vec4(vViewPosition, 1.0);
pos.z += wi * vRadius;
float linearDepth = -pos.z;
pos = projectionMatrix * pos;
pos = pos / pos.w;
float expDepth = pos.z;
depth = (pos.z + 1.0) / 2.0;
gl_FragDepthEXT = depth;
#if defined(color_type_depth)
color.r = linearDepth;
color.g = expDepth;
#endif
#if defined(use_edl)
finalColor.a = log2(linearDepth);
#endif
#else
#if defined(use_edl)
finalColor.a = vLogDepth;
#endif
#endif
#if defined(weighted_splats)
float distance = 2.0 * length(gl_PointCoord.xy - 0.5);
float weight = max(0.0, 1.0 - distance);
weight = pow(weight, 1.5);
finalColor.a = weight;
finalColor.xyz = finalColor.xyz * weight;
#endif
// CLOI
#if defined(use_cloi)
finalColor.a = vImp;
#endif
// finalColor.a = cloiValue / 8.0;
gl_FragColor = finalColor;
// gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);
}
| high | 0.611258 | 402 |
# 4323:3561
if { [info exists n("3561:Seattle,WA")] == 0 } {
set n("3561:Seattle,WA") [$ns node] }
if { [info exists n("4323:PaloAlto,CA")] == 0 } {
set n("4323:PaloAlto,CA") [$ns node] }
if { [info exists n("3561:PaloAlto,CA")] == 0 } {
set n("3561:PaloAlto,CA") [$ns node] }
if { [info exists n("4323:Seattle,WA")] == 0 } {
set n("4323:Seattle,WA") [$ns node] }
#4323:Palo Alto, CA -> 3561:Palo Alto, CA 0
$ns duplex-link $n("4323:PaloAlto,CA") $n("3561:PaloAlto,CA") 10.0Gb 0ms DropTail
#4323:Seattle, WA -> 3561:Seattle, WA 0
$ns duplex-link $n("4323:Seattle,WA") $n("3561:Seattle,WA") 10.0Gb 0ms DropTail
| low | 0.557534 | 403 |
@font-face {
font-family: 'Verdana';
src: url('../fonts/vardana/Verdana.eot') format('embedded-opentype'), url('../fonts/vardana/Verdana.woff') format('woff');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Verdana-Bold';
src: url('../fonts/vardana/Verdana-Bold.eot') format('embedded-opentype'); src: url('../fonts/vardana/Verdana-Bold.woff') format('woff');
font-weight: normal;
font-style: normal;
}
body{ font-family: 'verdana';}
*{
margin:0px;
padding:0px;
}
@charset "utf-8";
/* CSS Document */
.page-header {
/*text-align:center;*/
border-bottom:0px solid #eee;
}
.page-header{
padding:0px;
margin:0px;
margin-top: 10px;
}
.content{
border-radius:4px;
padding:30px;
margin-top:35px;
text-align:center;
}
.text h4{
font-size:26px;
text-align:center;
color:#2d2d2d;
}
.text h2{
font-size:33px;
text-align:center;
color:#2d2d2d;
font-family: 'Verdana-Bold';
font-weight:bold;
margin-top:24px;
margin-bottom:22px;
}
.text p{
font-size:17px;
text-align:center;
color:#a6c320;
font-weight:bold;
margin-top:15px;
margin-bottom:30px;
}
.table_1 th {
margin-bottom:10px;
}
.table th{
color:#ffffff;
font-size:15px;
}
#no-more-tables th
{
color:#ffffff;
padding: 18px;
font-size:15px;
font-family: 'Verdana-Bold';
}
#no-more-tables td
{
padding:12px 9px;
font-size:12px;
}
.error, .card_num-error {
color: red;
font-size: 12px;
font-weight: normal;
}
.card_num-error{display: none;}
input#card_num{
width: 100px;
margin: 0 auto;
}
.table td{
font-size:12px;
color:#252525;
font-weight:normal;
}
.table-striped > tbody > tr:nth-of-type(2n+1){
background:#cdcdcd;
}
.ajax-loader {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-align: center;
display: none;
}
.ajax-loader img {
position: absolute;
top: 50%;
margin-top: -50px;
}
@media only screen and (max-width: 991px) {
/* Force table to not be like tables anymore */
#no-more-tables table,
#no-more-tables thead,
#no-more-tables tbody,
#no-more-tables th,
#no-more-tables td,
#no-more-tables tr {
font-weight:normal;
display: block;
}
/* Hide table headers (but not display: none;, for accessibility) */
#no-more-tables thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
#no-more-tables tr { border: 1px solid #ccc; }
#no-more-tables td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
white-space: normal;
text-align:left;
}
#no-more-tables td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
top: 6px;
left: 6px;
width: 45%;
padding-right: 10px;
white-space: nowrap;
text-align:left;
font-weight: bold;
}
/*
Label the data
*/
#no-more-tables td:before { content: attr(data-title); }
} | high | 0.574762 | 404 |