text
stringlengths 27
775k
|
---|
#!/usr/bin/perl
#
# Re-align the columns in insns.dat, and enforce case conventions
#
@cols = (0, 16, 48, 96);
while ($line = <STDIN>) {
chomp $line;
if ($line !~ /^\s*(\;.*|)$/) {
($ln = $line) =~ s/\s+$//;
if ($line =~ /^\s*(\S+)\s+(\S+)\s+(\S+|\[.*\])\s+(\S+)\s*$/) {
@fields = ($1, $2, $3, $4);
$fields[0] = "\U$fields[0]" unless ($fields[0] =~ /^[^a-z]+cc$/);
$fields[3] =~ s/\,+$//;
$fields[3] = "\U$fields[3]" unless ($fields[3] eq 'ignore');
$c = 0;
$line = '';
for ($i = 0; $i < scalar(@fields); $i++) {
if ($i > 0 && $c >= $cols[$i]) {
$line .= ' ';
$c++;
}
while ($c < $cols[$i]) {
$line .= "\t";
$c = ($c+8) & ~7;
}
$line .= $fields[$i];
for ($j = 0; $j < length($fields[$i]); $j++) {
if (substr($fields[$i], $j, 1) eq "\t") {
$c = ($c+8) & ~7;
} else {
$c++;
}
}
}
}
}
print $line, "\n";
}
|
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
)
const rootTemplate = `// DO NOT EDIT THIS FILE
// Code generated by mbed.go
// %v
package %v
var files = map[string][]byte{
%v
}
func GetFileBytes(path string) []byte {
return files[path]
}
func GetFileContent(path string) string {
return string(files[path])
}
func GetFiles() []string {
result := make([]string, len(files))
idx := 0
for key, _ := range files {
result[idx] = key
idx++
}
return result
}
`
const fileItemTemplate = `"%v": []byte("%v"),
`
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func listFiles(searchDir, inputFile string) (files []string, err error) {
files = []string{}
if inputFile != "" {
files = append(files, inputFile)
return
}
err = filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
files = append(files, path)
return nil
})
return
}
func getFlags() (inputDir, inputFile, outputFile, pkg string, err error) {
flag.StringVar(&inputDir, "d", "", "Input dir.")
flag.StringVar(&inputFile, "f", "", "Input file.")
flag.StringVar(&outputFile, "o", "", "Output file.")
flag.StringVar(&pkg, "p", "main", "Package.")
flag.Parse()
if inputDir == "" && inputFile == "" {
err = fmt.Errorf("input directory ot input file is required")
}
if outputFile == "" {
err = fmt.Errorf("output file is required")
}
return
}
func getFilesMap(files []string) string {
fileItems := ""
for _, file := range files {
info, err := os.Stat(file)
check(err)
if !info.IsDir() {
fileItems = fileItems + getFileItemLine(file)
}
}
return fileItems
}
func getFileItemLine(file string) string {
hexBytesString := getFileHexBytesString(file)
filename := file
filename = strings.Replace(filename, "\\", "/", -1)
return fmt.Sprintf(fileItemTemplate, filename, hexBytesString)
}
func getFileHexBytesString(file string) string {
data, err := ioutil.ReadFile(file)
check(err)
buffer := bytes.NewBufferString("")
for _, b := range data {
fmt.Fprintf(buffer, "\\x%02x", b)
}
return buffer.String()
}
func main() {
inputDir, inputFile, outputFile, pkg, err := getFlags()
check(err)
if _, err = os.Stat(outputFile); err == nil {
err = os.Remove(outputFile)
check(err)
}
files, err := listFiles(inputDir, inputFile)
check(err)
buffer := bytes.NewBufferString("")
fileItems := getFilesMap(files)
fmt.Fprintf(buffer, string(rootTemplate), time.Now().UTC(), pkg, fileItems)
err = ioutil.WriteFile(outputFile, buffer.Bytes(), 0666)
check(err)
}
|
SELECT
id,
token,
display_name AS name,
is_active AS active
FROM
OA_EVENT_SOURCE_GAME oesg
INNER JOIN OA_EVENT_SOURCE oes ON oesg.event_source_id = oes.id
WHERE
oesg.game_id = :gameId
AND
oes.is_active = 1 |
module Distribution.Client.Dependency.Modular.Index where
import Data.List as L
import Data.Map as M
import Prelude hiding (pi)
import Distribution.Client.Dependency.Modular.Dependency
import Distribution.Client.Dependency.Modular.Flag
import Distribution.Client.Dependency.Modular.Package
-- | An index contains information about package instances. This is a nested
-- dictionary. Package names are mapped to instances, which in turn is mapped
-- to info.
type Index = Map PN (Map I PInfo)
-- | Info associated with a package instance.
-- Currently, dependencies, flags and encapsulations.
data PInfo = PInfo (FlaggedDeps PN) FlagDefaults Encaps
deriving (Show)
-- | Encapsulations. A list of package names.
type Encaps = [PN]
mkIndex :: [(PN, I, PInfo)] -> Index
mkIndex xs = M.map M.fromList (groupMap (L.map (\ (pn, i, pi) -> (pn, (i, pi))) xs))
groupMap :: Ord a => [(a, b)] -> Map a [b]
groupMap xs = M.fromListWith (++) (L.map (\ (x, y) -> (x, [y])) xs)
|
package com.lurkerbot.gameTime
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import mu.KotlinLogging
class GameTimer(private val timerRepository: TimerRepository) {
private val logger = KotlinLogging.logger {}
private val beingTracked: MutableMap<String, TimeRecord> = mutableMapOf()
private val serverBeingTracked: MutableMap<String, String> = mutableMapOf()
private fun userIsBeingTracked(userId: String, guildId: String) =
beingTracked.containsKey(userId) && serverBeingTracked[userId] == guildId
fun beginLogging(
userId: String,
guildId: String,
record: TimeRecord
): Result<Unit, GameTimeError> =
if (beingTracked.containsKey(userId) && !serverBeingTracked.containsKey(guildId)) {
Err(GameIsAlreadyLogging(userId, beingTracked[userId]!!, record))
} else {
logger.info { "Began recording user: $userId in guild: $guildId" }
beingTracked[userId] = record
serverBeingTracked[userId] = guildId
Ok(Unit)
}
fun endLogging(
userId: String,
guildId: String,
at: LocalDateTime = LocalDateTime.now()
): Result<Unit, GameTimeError> {
if (userIsBeingTracked(userId, guildId)) {
beingTracked[userId]?.let {
val updatedEnd = it.copy(sessionEnd = at)
val timeElapsed =
ChronoUnit.MILLIS.between(updatedEnd.sessionBegin, updatedEnd.sessionEnd)
return if (timeElapsed > 500) {
// Remove first to eliminate possibility of data being sent to db
beingTracked.remove(userId)
serverBeingTracked.remove(userId)
timerRepository.saveTimeRecord(updatedEnd)
Ok(Unit)
} else {
logger.warn {
"Not logging for $userId. State change happened in $timeElapsed milliseconds"
}
Err(StateChangedTooFast(userId, updatedEnd))
}
}
}
return Err(NeverStartedLogging(userId, guildId))
}
}
|
import {TypeFacture} from '../type-facture/type-facture';
import {Mouvement} from '../mouvement/mouvement';
import {Tva} from '../tva/tva';
export class Facture extends Mouvement{
numeroFacture: string;
tva: Tva;
exonere: boolean;
montantFactureRegle: number;
dateEcheance: string;
typeFacture: TypeFacture;
}
|
package BIDMat
import scala.collection.mutable.HashMap
import java.lang.ref._
import jcuda.NativePointerObject
class Mat(nr:Int, nc:Int) {
val nrows = nr
val ncols = nc
def length = nr*nc
private var _GUID = Mat.myrand.nextLong
def setGUID(v:Long):Unit = {_GUID = v}
def GUID:Long = _GUID
def notImplemented0(s:String):Mat = {
throw new RuntimeException("operator "+s+" not implemented for "+this.mytype)
}
def notImplemented1(s:String,that:Mat):Mat = {
throw new RuntimeException("operator "+s+" not implemented for "+this.mytype+" and "+that.mytype)
}
def t = notImplemented0("t")
def dv:Double = throw new RuntimeException("operator dv not implemented for "+this.mytype)
def mytype = "Mat"
def copyTo(a:Mat) = notImplemented0("copyTo");
def copy = notImplemented0("copy");
def newcopy = notImplemented0("newcopy");
def set(v:Float) = notImplemented0("set")
def zeros(nr:Int, nc:Int) = notImplemented0("zeros");
def ones(nr:Int, nc:Int) = notImplemented0("ones");
def clearUpper(i:Int) = notImplemented0("clearUpper");
def clearLower(i:Int) = notImplemented0("clearLower");
def clearUpper = notImplemented0("clearUpper");
def clearLower = notImplemented0("clearLower");
def nnz:Int = {notImplemented0("nnz"); 0}
def clear = notImplemented0("clear");
def zeros(nr:Int, nc:Int, nnz:Int):Mat = zeros(nr, nc)
def recycle(nr:Int, nc:Int, nnz:Int):Mat = notImplemented0("recycle");
def contents:Mat = notImplemented0("contents");
def colslice(a:Int, b:Int, out:Mat):Mat = notImplemented0("colslice");
def colslice(a:Int, b:Int, out:Mat, c:Int):Mat = notImplemented0("colslice");
def rowslice(a:Int, b:Int, out:Mat):Mat = notImplemented0("rowslice");
def rowslice(a:Int, b:Int, out:Mat, c:Int):Mat = notImplemented0("rowslice");
def colslice(a:Int, b:Int):Mat = notImplemented0("colslice");
def rowslice(a:Int, b:Int):Mat = notImplemented0("rowslice");
def apply(a:IMat):Mat = notImplemented0("linear array access");
def apply(a:IMat, b:IMat):Mat = notImplemented0("block array access");
def apply(a:IMat, b:Int):Mat = notImplemented0("block array access");
def apply(a:Int, b:IMat):Mat = notImplemented0("block array access");
def update(a:IMat, b:Mat) = notImplemented0("linear update");
def update(a:IMat, b:IMat, m:Mat) = notImplemented0("block update");
def update(a:IMat, b:Int, m:Mat) = notImplemented0("block update");
def update(a:Int, b:IMat, m:Mat) = notImplemented0("block update");
def unary_-():Mat = notImplemented1("-", this)
def + (b : Mat):Mat = notImplemented1("+", b)
def - (b : Mat):Mat = notImplemented1("-", b)
def * (b : Mat):Mat = notImplemented1("*", b)
def *^ (b : Mat):Mat = notImplemented1("*^", b)
def xT (b : Mat):Mat = notImplemented1("*", b)
def Tx (b : Mat):Mat = notImplemented1("*", b)
def ^* (b : Mat):Mat = notImplemented1("*^", b)
def ** (b : Mat):Mat = notImplemented1("**", b)
def ⊗ (b : Mat):Mat = notImplemented1("⊗", b) // unicode 8855, 0x2297
def /< (b : Mat):Mat = notImplemented1("/<", b)
def ∘ (b : Mat):Mat = notImplemented1("∘", b) // unicode 8728, 0x2218
def *@ (b : Mat):Mat = notImplemented1("*@", b)
def / (b : Mat):Mat = notImplemented1("/", b)
def \\ (b : Mat):Mat = notImplemented1("\\\\", b)
def ^ (b : Mat):Mat = notImplemented1("^", b)
def ◁ (b : Mat):Mat = notImplemented1("◁", b) // unicode 9665, 0x25C1
def ▷ (b : Mat):Mat = notImplemented1("▷", b) // unicode 9666, 0x25C2
def dot (b : Mat):Mat = notImplemented1("dot", b)
def dotr (b : Mat):Mat = notImplemented1("dotr", b)
def ∙ (b : Mat):Mat = notImplemented1("dot", b) // unicode 8729, 0x2219
def ∙→ (b : Mat):Mat = notImplemented1("dotr", b) // unicode (8729, 8594) (0x2219, 0x2192)
def > (b : Mat):Mat = notImplemented1(">", b)
def < (b : Mat):Mat = notImplemented1("<", b)
def >= (b : Mat):Mat = notImplemented1(">=", b)
def <= (b : Mat):Mat = notImplemented1("<=", b)
def == (b : Mat):Mat = notImplemented1("==", b)
def === (b : Mat):Mat = notImplemented1("===", b)
def != (b : Mat):Mat = notImplemented1("!=", b)
def <-- (b : Mat):Mat = b.copyTo(this)
def \ (b : Mat):Mat = notImplemented1("\\", b)
def on (b : Mat):Mat = notImplemented1("on", b)
def ~ (b : Mat):Pair = b match {
case bb:FMat => new FPair(this, bb)
case bb:DMat => new DPair(this, bb)
case bb:IMat => new IPair(this, bb)
case bb:SMat => new SPair(this, bb)
// case bb:SDMat => new SDPair(this, bb)
case bb:CMat => new CPair(this, bb)
case bb:GMat => new GPair(this, bb)
}
def ddot (b : Mat):Double = {notImplemented1("ddot", b); 0}
def ∙∙ (b : Mat):Double = {notImplemented1("ddot", b); 0}
def ^* (b : DSPair):Mat = notImplemented0("^*")
def Tx (b : DSPair):Mat = notImplemented0("Tx")
def @@ (b : Mat):DSPair = (this, b) match {
case (aa:FMat, bb:SMat) => new FDSPair(aa, bb)
case (aa:GMat, bb:GSMat) => new GDSPair(aa, bb)
}
}
abstract class DSPair {}
abstract class Pair {
def notImplemented0(s:String):Mat = {
throw new RuntimeException("operator "+s+" not implemented for "+this)
}
def notImplemented1(s:String,that:Mat):Mat = {
throw new RuntimeException("operator "+s+" not implemented for "+this+" and "+that)
}
def t = notImplemented0("t")
def + (b : Mat):Mat = notImplemented1("+", b)
def - (b : Mat):Mat = notImplemented1("-", b)
def * (b : Mat):Mat = notImplemented1("*", b)
def xT (b : Mat):Mat = notImplemented1("xT", b)
def *^ (b : Mat):Mat = notImplemented1("*^", b)
def Tx (b : Mat):Mat = notImplemented1("Tx", b)
def ^* (b : Mat):Mat = notImplemented1("*^", b)
def /< (b : Mat):Mat = notImplemented1("/<", b)
def *@ (b : Mat):Mat = notImplemented1("*@", b)
def ∘ (b : Mat):Mat = notImplemented1("∘", b)
def / (b : Mat):Mat = notImplemented1("/", b)
def \\ (b : Mat):Mat = notImplemented1("\\\\", b)
def ^ (b : Mat):Mat = notImplemented1("^", b)
def ◁ (b : Mat):Mat = notImplemented1("◁", b)
def ▷ (b : Mat):Mat = notImplemented1("▷", b)
def dot (b : Mat):Mat = notImplemented1("dot", b)
def dotr (b : Mat):Mat = notImplemented1("dotr", b)
def ∙ (b : Mat):Mat = notImplemented1("dot", b)
def ∙→ (b : Mat):Mat = notImplemented1("dotr", b)
def ** (b : Mat):Mat = notImplemented1("**", b)
def ⊗ (b : Mat):Mat = notImplemented1("⊗", b)
def > (b : Mat):Mat = notImplemented1(">", b)
def < (b : Mat):Mat = notImplemented1("<", b)
def >= (b : Mat):Mat = notImplemented1(">=", b)
def <= (b : Mat):Mat = notImplemented1("<=", b)
def == (b : Mat):Mat = notImplemented1("==", b)
def === (b : Mat):Mat = notImplemented1("===", b)
def != (b : Mat):Mat = notImplemented1("!=", b)
def \ (b : Mat):Mat = notImplemented1("\\", b)
def on (b : Mat):Mat = notImplemented1("on", b)
def + (b : Float):Mat = notImplemented0("+")
def - (b : Float):Mat = notImplemented0("-")
def * (b : Float):Mat = notImplemented0("*")
def xT (b : Float):Mat = notImplemented0("xT")
def *^ (b : Float):Mat = notImplemented0("*^")
def Tx (b : Float):Mat = notImplemented0("Tx")
def ^* (b : Float):Mat = notImplemented0("*^")
def /< (b : Float):Mat = notImplemented0("/<")
def *@ (b : Float):Mat = notImplemented0("*@")
def ∘ (b : Float):Mat = notImplemented0("∘")
def / (b : Float):Mat = notImplemented0("/")
def \\ (b : Float):Mat = notImplemented0("\\\\")
def ^ (b : Float):Mat = notImplemented0("^")
def ◁ (b : Float):Mat = notImplemented0("◁")
def ▷ (b : Float):Mat = notImplemented0("▷")
def dot (b : Float):Mat = notImplemented0("dot")
def dotr (b : Float):Mat = notImplemented0("dotr")
def ∙ (b : Float):Mat = notImplemented0("dot")
def ∙→ (b : Float):Mat = notImplemented0("dotr")
def > (b : Float):Mat = notImplemented0(">")
def < (b : Float):Mat = notImplemented0("<")
def >= (b : Float):Mat = notImplemented0(">=")
def <= (b : Float):Mat = notImplemented0("<=")
def == (b : Float):Mat = notImplemented0("==")
def === (b : Float):Mat = notImplemented0("===")
def != (b : Float):Mat = notImplemented0("!=")
def \ (b : Float):Mat = notImplemented0("\\")
def on (b : Float):Mat = notImplemented0("on")
}
object Mat {
import Ordered._
import scala.tools.jline.TerminalFactory
var useCache = false // Use matrix caching
var recycleGrow = 1.2 // For caching, amount to grow re-allocated matrices
var hasCUDA = 0 // Number of available CUDA GPUs
var noMKL:Boolean = false // Dont use MKL libs
var debugMem = false // Debug GPU mem calls
var terminal = TerminalFactory.create
def terminalWidth = math.max(terminal.getWidth,80)
var compressType = 1 // For HDF5 I/O, 0=none, 1=zlib, 2=szip
var compressionLevel = 3 // for HDF5 zlib
var chunkSize = 1024*1024 // for HDF5 compression
var szipBlock = 32 // HDF5 szip block size
var numThreads = Runtime.getRuntime().availableProcessors();
var numOMPthreads = numThreads;
var nflops = 0L
var oneBased = 0 // Whether matrix indices are 0: zero-based (like C) or 1: one-based (like Matlab)
var ioneBased = 1 // Whether sparse matrix *internal* indices are zero 0: or one-based 1:
var useGPUsort = true
final val MSEED:Int = 1452462553
final val myrand = new java.util.Random(MSEED)
val opcodes = HashMap.empty[String, Int]
val _opcode = 1
var useStdio = (! System.getProperty("os.name").startsWith("Windows")) // HDF5 directive
private val _cache2 = HashMap.empty[Tuple2[Long,Int], Mat] // Matrix caches
private val _cache3 = HashMap.empty[Tuple3[Long,Long,Int], Mat]
private val _cache4 = HashMap.empty[Tuple4[Long,Long,Long,Int], Mat]
def cache2(key:Tuple2[Long,Int]):Mat = {
_cache2.synchronized {
if (_cache2.contains(key)) {
_cache2(key)
} else {
null
}
}
}
def cache3(key:Tuple3[Long,Long,Int]):Mat = {
_cache3.synchronized {
if (_cache3.contains(key)) {
_cache3(key)
} else {
null
}
}
}
def cache4(key:Tuple4[Long,Long,Long,Int]):Mat = {
_cache4.synchronized {
if (_cache4.contains(key)) {
_cache4(key)
} else {
null
}
}
}
def cache2put(key:Tuple2[Long,Int], m:Mat):Unit = {
_cache2.synchronized {
_cache2(key) = m
}
}
def cache3put(key:Tuple3[Long,Long,Int], m:Mat):Unit = {
_cache3.synchronized {
_cache3(key) = m
}
}
def cache4put(key:Tuple4[Long,Long,Long,Int], m:Mat):Unit = {
_cache4.synchronized {
_cache4(key) = m
}
}
def clearCaches = {
_cache2.clear
_cache3.clear
_cache4.clear
}
def trimCache2(ithread:Int) = {
_cache2.synchronized {
val keys = _cache2.keySet
keys.foreach((key:Tuple2[Long,Int]) => {
val toremove:Boolean = _cache2.get(key) match {
case aa:GMat => (aa.myGPU == ithread)
case aa:GSMat => (aa.myGPU == ithread)
case _ => false
}
if (toremove) _cache2.remove(key)
})
}
}
def trimCache3(ithread:Int) = {
_cache3.synchronized {
val keys = _cache3.keySet
keys.foreach((key:Tuple3[Long,Long,Int]) => {
val toremove:Boolean = _cache3.get(key) match {
case aa:GMat => (aa.myGPU == ithread)
case aa:GSMat => (aa.myGPU == ithread)
case _ => false
}
if (toremove) _cache3.remove(key)
})
}
}
def trimCache4(ithread:Int) = {
_cache3.synchronized {
val keys = _cache4.keySet
keys.foreach((key:Tuple4[Long,Long,Long,Int]) => {
val toremove:Boolean = _cache4.get(key) match {
case aa:GMat => (aa.myGPU == ithread)
case aa:GSMat => (aa.myGPU == ithread)
case _ => false
}
if (toremove) _cache4.remove(key)
})
}
}
def trimCaches(ithread:Int) = {
trimCache2(ithread)
trimCache3(ithread)
trimCache4(ithread)
}
def getJARdir:String = {
val path = Mat.getClass.getProtectionDomain().getCodeSource().getLocation().getPath()
val jstr = java.net.URLDecoder.decode(path, "UTF-8")
path.replace("BIDMat.jar","")
}
def checkMKL:Unit = {
if (!noMKL) {
try {
jcuda.LibUtils.loadLibrary("bidmatmkl")
jcuda.LibUtils.loadLibrary("jhdf5")
} catch {
case _ => {
println("Cant find native CPU libraries")
noMKL = true
}
}
}
}
def checkCUDA:Unit = {
if (hasCUDA == 0) {
val os = System.getProperty("os.name")
try {
if (os.equals("Linux") || os.equals("Mac OS X")) {
System.loadLibrary("cudart")
} else {
try{
System.loadLibrary("cudart64_50_35")
} catch {
case _ => try {
System.loadLibrary("cudart64_42_9")
}
}
}
jcuda.LibUtils.loadLibrary("JCudaRuntime")
} catch {
case _ => {
println("Cant find CUDA SDK or JCUDA")
hasCUDA = -1
}
}
}
if (hasCUDA >= 0) {
try {
var cudanum = new Array[Int](1)
jcuda.runtime.JCuda.cudaGetDeviceCount(cudanum)
hasCUDA = cudanum(0)
printf("%d CUDA device%s found", hasCUDA, if (hasCUDA == 1) "" else "s")
if (hasCUDA > 0) {
jcuda.runtime.JCuda.cudaRuntimeGetVersion(cudanum)
println(", CUDA version %d.%d" format (cudanum(0)/1000, (cudanum(0)%100) / 10))
} else {
println("")
}
} catch {
case e:NoClassDefFoundError => println("Couldn't load the JCUDA driver")
case e:Exception => println("Exception while initializing JCUDA driver")
case _ => println("Something went wrong while loading JCUDA driver")
}
if (hasCUDA > 0) {
try {
jcuda.LibUtils.loadLibrary("bidmatcuda")
} catch {
case _ => println("Something went wrong while loading BIDMat CUDA library")
}
}
}
}
def copyToIntArray[@specialized(Double, Float) T](data:Array[T], i0:Int, idata:Array[Int], d0:Int, n:Int)
(implicit numeric : Numeric[T]) = {
var i = 0
while (i < n) {
idata(i+d0) = numeric.toInt(data(i+i0));
i += 1
}
}
def copyToDoubleArray[@specialized(Int, Float) T](data:Array[T], i0:Int, ddata:Array[Double], d0:Int, n:Int)
(implicit numeric : Numeric[T]) = {
var i = 0
while (i < n) {
ddata(i+d0) = numeric.toDouble(data(i+i0));
i += 1
}
}
def copyToFloatArray[@specialized(Int, Double) T](data:Array[T], i0:Int, fdata:Array[Float], d0:Int, n:Int)
(implicit numeric : Numeric[T]) = {
var i = 0
while (i < n) {
fdata(i+d0) = numeric.toFloat(data(i+i0));
i += 1
}
}
def copyListToFloatArray[T](a:List[T], b:Array[Float])(implicit numeric : Numeric[T]) = {
var i = 0;
var todo = a.iterator
val alen = a.length
while (i < alen) {
val h = todo.next
b(i) = numeric.toFloat(h)
i += 1
}
}
def ibinsearch(v:Int, x:Array[Int], istartp:Int, iendp:Int):Int = {
var istart = istartp
var iend = iendp
while (iend - istart > 1) {
var mid:Int = (istart + iend)/2
if (v < x(mid)) iend = mid else istart = mid
}
if (v == x(istart)) istart else -1
}
def binsearch[T : Ordering](v:T, x:Array[T], istartp:Int, iendp:Int):Int = {
var istart = istartp
var iend = iendp
while (iend - istart > 1) {
var mid:Int = (istart + iend)/2
if (v < x(mid)) iend = mid else istart = mid
}
if (v == x(istart)) istart else -1
}
def lexsort[T :Ordering](a:List[Array[T]]):Array[Int] = {
val n = a(0).length
val ind = new Array[Int](n)
var i = 0; while(i < n) {ind(i) = i; i += 1}
def comp(i:Int, j:Int):Int = {
val alen = a.length;
val ip = ind(i)
val jp = ind(j)
var c0 = 0
var k = 0;
while (k < alen && c0 == 0) {
c0 = a(k)(ip) compare a(k)(jp)
k += 1
}
if (c0 != 0) {
c0
} else {
ip compare jp
}
}
def swap(i:Int, j:Int):Unit = {
val tmp = ind(i)
ind(i) = ind(j)
ind(j) = tmp
}
BIDMat.Sorting.quickSort(comp, swap, 0, n)
ind
}
def ilexsort(a:List[Array[Int]]):Array[Int] = {
val n = a(0).length
val ind = new Array[Int](n)
var i = 0; while(i < n) {ind(i) = i; i += 1}
def comp(i:Int, j:Int):Int = {
var k = 0;
val alen = a.length;
var c0 = 0
val ip = ind(i)
val jp = ind(j)
while (k < alen && c0 == 0) {
c0 = a(k)(ip) compare a(k)(jp)
k += 1
}
if (c0 != 0) {
c0
} else {
ip compare jp
}
}
def swap(i:Int, j:Int):Unit = {
val tmp = ind(i)
ind(i) = ind(j)
ind(j) = tmp
}
BIDMat.Sorting.quickSort(comp, swap, 0, n)
ind
}
def ilexsort2(a:Array[Int], b:Array[Int]):Array[Int] = {
val n = a.length
val ind = new Array[Int](n)
var i = 0; while(i < n) {ind(i) = i; i += 1}
def comp(i:Int, j:Int):Int = {
val c0 = a(i) compare a(j)
if (c0 != 0) {
c0
} else {
val c1 = b(i) compare b(j)
if (c1 != 0) {
c1
} else {
ind(i) compare ind(j)
}
}
}
def swap(i:Int, j:Int):Unit = {
val tmpa = a(i)
a(i) = a(j)
a(j) = tmpa
val tmpb = b(i)
b(i) = b(j)
b(j) = tmpb
val tmpi = ind(i)
ind(i) = ind(j)
ind(j) = tmpi
}
BIDMat.Sorting.quickSort(comp, swap, 0, n)
ind
}
def ilexsort3[T](a:Array[Int], b:Array[Int], c:Array[T]):Unit = {
val n = a.length
def comp(i:Int, j:Int):Int = {
val c0 = a(i) compare a(j)
if (c0 != 0) {
c0
} else {
b(i) compare b(j)
}
}
def swap(i:Int, j:Int):Unit = {
val tmpa = a(i)
a(i) = a(j)
a(j) = tmpa
val tmpb = b(i)
b(i) = b(j)
b(j) = tmpb
val tmpc = c(i)
c(i) = c(j)
c(j) = tmpc
}
BIDMat.Sorting.quickSort(comp, swap, 0, n)
}
def ilexsort(args:Array[Int]*):Array[Int] = {
ilexsort(args.toList)
}
def lexsort[T : Ordering](args:Array[T]*):Array[Int] = {
lexsort(args.toList)
}
}
|
## Overview
The files in this directory represent a cert hierarchy to test OCSP response stapling.
## CA
- ca_cert.pem
- ca_key.pem
Issuer for all of the other certs in the directory.
Since this is a test PKI, we do an intermediate for issuing leaf cert(s).
## OCSP
* ocsp_cert.pem
* ocsp_key.pem
Cert/key for the test OCSP responder. OCSP responses will be signed by the key.
The CN for this cert matches the URI in the Server Cert's "Authority Information Access" x509 extension.
## Server Cert
* server_cert.pem
* server_key.pem
The leaf cert/key. OCSP responses will be generated for this cert.
## OCSP response
* ocsp_response.der
DER formatted OCSP response for the Server Cert. This file will be configured in s2n for stapling.
## Generating a new OCSP response for the leaf cert
Should not be necessary. The current response expires in 100 years.
From the current directory:
### Run the server
```
# With nextUpdate
openssl ocsp -port 8889 -text -CA ca_cert.pem \ ocsp_test ✭ ✱ ◼
-index certs.txt \
-rkey ocsp_key.pem \
-rsigner ocsp_cert.pem \
-nrequest 1 \
-ndays $(( 365 * 100 ))
# Without nextUpdate
openssl ocsp -port 8890 -text -CA ca_cert.pem \ ocsp_test ✭ ✱ ◼
-index certs.txt \
-rkey ocsp_key.pem \
-rsigner ocsp_cert.pem \
-nrequest 1
```
### Run the client and save the result to file
```
# With nextUpdate
openssl ocsp -CAfile ca_cert.pem \ ocsp_test ✭ ✱ ◼
-url http://127.0.0.1:8889 \
-issuer ca_cert.pem \
-verify_other ocsp_cert.pem \
-cert server_cert.pem -respout ocsp_response.der
# Without nextUpdate
openssl ocsp -CAfile ca_cert.pem \ ocsp_test ✭ ✱ ◼
-url http://127.0.0.1:8890 \
-issuer ca_cert.pem \
-verify_other ocsp_cert.pem \
-cert server_cert.pem -respout ocsp_response_no_next_update.der
```
|
module Relevance
module Tarantula
class InvalidHtmlHandler
include Relevance::Tarantula
def handle(result)
response = result.response
unless response.html?
log "Skipping #{self.class} on url: #{result.url} because response is not html."
return
end
begin
body = HTML::Document.new(response.body, true)
rescue Exception => e
error_result = result.dup
error_result.success = false
error_result.description = "Bad HTML (Scanner)"
error_result.data = e.message
error_result
else
nil
end
end
end
end
end
|
#pragma once
#include <cassert>
#include <cstring>
#include <limits>
#include <optional>
#include <string_view>
#include "lmdb.h"
#include "lmdb/enum_helper.h"
#include "lmdb/error.h"
namespace lmdb {
template <typename Ec>
void ex(Ec&& ec) {
if (ec != MDB_SUCCESS) {
throw std::system_error{error::make_error_code(ec)};
}
}
ENUM_FLAGS(env_open_flags){
NONE = 0x0,
// pointers to data items will be constant; highly experimental!
FIXEDMAP = 0x01,
// path is the database file itself (+ {}-lock), not a directory
NOSUBDIR = 0x4000,
// no flush; crash may undo the last commited transactions (ACI)
// if filesystem preserves write order and WRITEMAP is not used
// note: use (MAPASYNC | WRITEMAP) for WRITEMAP
NOSYNC = 0x10000,
// no writes allowed; lock file will be modified except on RO filesystems
RDONLY = 0x20000,
// flush only once per transaction; omit metadata flush
// flush on none-RDONLY commit or env::sync()
// crash may undo the last commited transaction (ACID without D)
NOMETASYNC = 0x40000,
// writeable memory map unless RDONLY is set
// faster for DBs that fit in RAM
// incompatible with nested transactions
WRITEMAP = 0x80000,
// use asynchronous flushes to disk
// a system crash can then corrupt the database
// env::sync() for on-disk database integrity until next commit
MAPASYNC = 0x100000,
// no thread-local storage
// txn::reset() keeps the slot reserved for the txn object
// allows for
// - more than one RO transaction per thread
// - one RO transaction for multiple threads
// user threads per OS thread -> user serializes writes
NOTLS = 0x200000,
// user manages concurrency (single-writer)
NOLOCK = 0x400000,
// random read performance for DB > RAM and RAM is full
NORDAHEAD = 0x800000,
// don't zero out memory
// avoids persisting leftover data from other code (security)
NOMEMINIT = 0x1000000,
// open the env with the previous meta page.
// loses the latest transaction, but may help with curruption
PREVMETA = 0x2000000};
ENUM_FLAGS(txn_flags){NONE = 0x0,
// transaction will not perform any write operations
RDONLY = 0x20000,
// no flush when commiting this transaction
NOSYNC = 0x10000,
// flush system buffer, but omit metadata flush
NOMETASYNC = 0x40000};
ENUM_FLAGS(dbi_flags){
NONE = 0x0,
// sort in reverse order
REVERSEKEY = 0x02,
// keys may have multiple data items, stored in sorted order
DUPSORT = 0x04,
// keys are binary integers in native byte order: unsigned int or mdb_size_t
INTEGERKEY = 0x08,
// only in combination with DUPSORT: data items are same size
// enables GET_MULTIPLE, NEXT_MULTIPLE, and PREV_MULTIPLE cursor ops
DUPFIXED = 0x10,
// duplicate data items are binary integers similar to INTEGERKEY keys
INTEGERDUP = 0x20,
// duplicate data items should be compared as strings in reverse order
REVERSEDUP = 0x40,
// create named database if non-existent (not allowed in RO txn / RO env)
CREATE = 0x40000};
ENUM_FLAGS(put_flags){
NONE = 0x0,
// enter the new key/data pair only if not already contained
// returns KEYEXIST if key/value pair is already contained even with DUPSORT
NOOVERWRITE = 0x10,
// enter key/value pair only if not already contained
// only with DUPSORT database
// returns KEYEXIST if key/value pair is already contained
NODUPDATA = 0x20,
// replace current item; key parameter still required (has to match)
// ideal: size of new is same as old size; otherwise delete+insert
CURRENT = 0x40,
// only make place for data of the given size; no copy
// returns a pointer to the reserved space to be filled later
// returned pointer valid until next update operation / transaction end
// not compatible with DUPSORT!
RESERVE = 0x10000,
// insert to end of database without key comparison (useful for bulk insert)
// returns MDB_KEYEXIST if not sorted
APPEND = 0x20000,
// as APPEND, but for sorted dup data
APPENDDUP = 0x40000,
// only with DUPFIXED: store multiple contiguous data elements
// data argument must be an array of two MDB_vals:
// param=[
// {mv_size="size of a singe data element", mv_data="ptr to begin of arr"},
// {mv_size="number of data elements to store", mv_data=unused}
// ]
// after call: param[1].mv_size = number of elements written
MULTIPLE = 0x80000};
enum class cursor_op {
FIRST, // go to first entry
FIRST_DUP, // go to first entry of current key (DUPSORT)
GET_BOTH, // go to entry (DUPSORT)
GET_BOTH_RANGE, // go to entry with nearest data (DUPSORT)
GET_CURRENT, // return current entry
GET_MULTIPLE, // return key and up to a page of duplicate values (DUPFIXED)
LAST, // go to last entry
LAST_DUP, // go to last entry of current key (DUPSORT)
NEXT, // go to next entry
NEXT_DUP, // go to next entry of current key (DUPSORT)
NEXT_MULTIPLE, // return key and up to a page of duplicate values of next
// entry (DUPFIXED)
NEXT_NODUP, // go to first entry of next key
PREV, // go to previous entry
PREV_DUP, // go to previous entry of current key (DUPSORT)
PREV_NODUP, // go to last entry of previous key
SET, // go to specified key
SET_KEY, // go to specified key and return key + value
SET_RANGE, // go to first key greater or equal specified key
PREV_MULTIPLE // go to previous page and return key and up to a page of
// duplicate entries (DUPFIXED)
};
struct env final {
env() : env_{nullptr} { ex(mdb_env_create(&env_)); }
~env() {
mdb_env_close(env_);
env_ = nullptr;
}
env(env&& e) noexcept : env_{e.env_} { e.env_ = nullptr; }
env& operator=(env&& e) noexcept {
env_ = e.env_;
e.env_ = nullptr;
return *this;
}
env(env const&) = delete;
env& operator=(env const&) = delete;
void open(char const* path, env_open_flags flags = env_open_flags::NONE,
mdb_mode_t mode = 0644) {
ex(mdb_env_open(env_, path, static_cast<unsigned>(flags), mode));
is_open_ = true;
}
void set_maxreaders(unsigned int n) { ex(mdb_env_set_maxreaders(env_, n)); }
void set_mapsize(mdb_size_t size) { ex(mdb_env_set_mapsize(env_, size)); }
void set_maxdbs(MDB_dbi dbs) { ex(mdb_env_set_maxdbs(env_, dbs)); }
env_open_flags get_flags() {
unsigned int flags;
ex(mdb_env_get_flags(env_, &flags));
return env_open_flags{flags};
}
MDB_stat stat() {
MDB_stat stat;
ex(mdb_env_stat(env_, &stat));
return stat;
}
void sync() { ex(mdb_env_sync(env_, 0)); }
void force_sync() { ex(mdb_env_sync(env_, 1)); }
bool is_open() const { return is_open_; }
MDB_env* env_;
bool is_open_ = false;
};
template <typename T>
inline std::enable_if_t<std::is_integral_v<T>, MDB_val> to_mdb_val(T const& s) {
return MDB_val{sizeof(T), const_cast<void*>( // NOLINT
reinterpret_cast<void const*>(&s))};
}
template <int N>
inline MDB_val to_mdb_val(char const (&s)[N]) {
return MDB_val{
N, const_cast<void*>(reinterpret_cast<void const*>(s))}; // NOLINT
}
inline MDB_val to_mdb_val(std::string_view s) {
return MDB_val{s.size(), const_cast<char*>(s.data())}; // NOLINT
}
inline std::string_view from_mdb_val(MDB_val v) {
return {static_cast<char const*>(v.mv_data), v.mv_size};
}
template <typename T = int>
inline T as_int(std::string_view s) {
assert(s.length() >= sizeof(T));
T t;
std::memcpy(&t, s.data(), sizeof(t));
return t;
}
struct txn final {
struct dbi final {
dbi(MDB_txn* txn, char const* name, dbi_flags const flags)
: txn_{txn}, dbi_{std::numeric_limits<MDB_dbi>::max()} {
ex(mdb_dbi_open(txn, name, static_cast<unsigned>(flags), &dbi_));
}
dbi(MDB_txn* txn, MDB_dbi dbi) : txn_{txn}, dbi_{dbi} {}
MDB_stat stat() {
MDB_stat stat;
ex(mdb_stat(txn_, dbi_, &stat));
return stat;
}
void close() { mdb_dbi_close(mdb_txn_env(txn_), dbi_); }
MDB_txn* txn_;
MDB_dbi dbi_;
};
explicit txn(env& env, txn_flags const flags = txn_flags::NONE) {
ex(mdb_txn_begin(env.env_, nullptr, static_cast<unsigned>(flags), &txn_));
}
txn(env& env, txn& parent, txn_flags const flags) {
ex(mdb_txn_begin(env.env_, parent.txn_, static_cast<unsigned>(flags),
&txn_));
}
txn(txn&& t) noexcept
: committed_{t.committed_}, is_write_{t.is_write_}, txn_{t.txn_} {
t.txn_ = nullptr;
}
txn& operator=(txn&& t) noexcept {
committed_ = t.committed_;
is_write_ = t.is_write_;
txn_ = t.txn_;
t.txn_ = nullptr;
return *this;
}
txn(txn const&) = delete;
txn& operator=(txn const&) = delete;
~txn() {
if (!committed_) {
mdb_txn_abort(txn_);
}
}
void commit() {
committed_ = true;
mdb_txn_commit(txn_);
}
void clear() {
mdb_txn_reset(txn_);
ex(mdb_txn_renew(txn_));
}
dbi dbi_open(char const* name = nullptr, dbi_flags flags = dbi_flags::NONE) {
return {txn_, name, flags};
}
dbi dbi_open(dbi_flags flags) { return {txn_, nullptr, flags}; }
void dbi_clear(dbi const& db) {
ex(mdb_drop(txn_, db.dbi_, 0));
is_write_ = true;
}
void dbi_remove(dbi const& db) {
mdb_drop(txn_, db.dbi_, 1);
is_write_ = true;
}
template <typename T>
void put(dbi& dbi, T key, std::string_view value,
put_flags const flags = put_flags::NONE) {
auto k = to_mdb_val(key);
auto v = to_mdb_val(value);
ex(mdb_put(txn_, dbi.dbi_, &k, &v, static_cast<unsigned>(flags)));
is_write_ = true;
}
template <typename T>
bool put_nodupdata(dbi& dbi, T key, std::string_view value,
put_flags const flags = put_flags::NONE) {
auto k = to_mdb_val(key);
auto v = to_mdb_val(value);
if (auto const ec =
mdb_put(txn_, dbi.dbi_, &k, &v,
static_cast<unsigned>(flags | put_flags::NODUPDATA));
ec != MDB_KEYEXIST && ec != MDB_SUCCESS) {
throw std::system_error{error::make_error_code(ec)};
} else {
is_write_ = true;
return ec != MDB_KEYEXIST;
}
}
template <typename T>
std::optional<std::string_view> get(dbi& dbi, T key) {
auto k = to_mdb_val(key);
auto v = MDB_val{0, nullptr};
auto const ec = mdb_get(txn_, dbi.dbi_, &k, &v);
switch (ec) {
case MDB_SUCCESS: return from_mdb_val(v);
case MDB_NOTFOUND: return {};
default: throw std::system_error{error::make_error_code(ec)};
}
}
template <typename T>
bool del(dbi& dbi, T key) {
auto k = to_mdb_val(key);
auto const ec = mdb_del(txn_, dbi.dbi_, &k, nullptr);
switch (ec) {
case MDB_SUCCESS: is_write_ = true; return true;
case MDB_NOTFOUND: return false;
default: throw std::system_error{error::make_error_code(ec)};
}
}
template <typename T>
bool del_dupdata(dbi& dbi, T key, std::string_view value) {
auto k = to_mdb_val(key);
auto v = to_mdb_val(value);
switch (auto const ec = mdb_del(txn_, dbi.dbi_, &k, &v); ec) {
case MDB_SUCCESS: is_write_ = true; return true;
case MDB_NOTFOUND: return false;
default: throw std::system_error{error::make_error_code(ec)};
}
}
bool committed_{false};
bool is_write_{false};
MDB_txn* txn_{nullptr};
};
struct cursor final {
using opt_entry =
std::optional<std::pair<std::string_view, std::string_view>>;
template <typename T>
using opt_int_entry = std::optional<std::pair<T, std::string_view>>;
cursor(txn& txn, txn::dbi& dbi) : txn_{&txn}, cursor_{nullptr} {
ex(mdb_cursor_open(txn.txn_, dbi.dbi_, &cursor_));
}
cursor(cursor&& c) noexcept : txn_{c.txn_}, cursor_{c.cursor_} {
c.cursor_ = nullptr;
}
cursor& operator=(cursor&& c) noexcept {
txn_ = c.txn_;
cursor_ = c.cursor_;
c.cursor_ = nullptr;
return *this;
}
cursor(cursor const&) = delete;
cursor& operator=(cursor const&) = delete;
~cursor() {
if (cursor_ != nullptr && !(txn_->committed_ && txn_->is_write_)) {
mdb_cursor_close(cursor_);
cursor_ = nullptr;
}
}
void reset() { cursor_ = nullptr; }
void commit() { cursor_ = nullptr; }
void renew(txn& t) { ex(mdb_cursor_renew(t.txn_, cursor_)); }
template <int N>
opt_entry get(cursor_op const op, char const (&s)[N]) {
auto k = to_mdb_val<N>(s);
return get(op, &k);
}
opt_entry get(cursor_op const op, std::string const& key) {
return get(op, key.operator std::string_view());
}
opt_entry get(cursor_op const op, std::string_view key) {
auto k = to_mdb_val(key);
return get(op, &k);
}
template <typename T>
std::enable_if_t<std::is_integral_v<T>, opt_int_entry<T>> get(
cursor_op const op) {
auto k = MDB_val{0, nullptr};
auto r = get(op, &k);
return r ? std::make_optional(
std::make_pair(as_int<std::decay_t<T>>(r->first), r->second))
: std::nullopt;
}
opt_entry get(cursor_op const op) {
auto k = MDB_val{};
return get(op, &k);
}
template <typename T>
opt_int_entry<T> get(cursor_op op, T const& key) {
auto k = to_mdb_val(key);
auto r = get(op, &k);
return r ? std::make_optional(
std::make_pair(as_int<T>(r->first), r->second))
: std::nullopt;
}
opt_entry get(cursor_op const op, MDB_val* k) {
auto v = MDB_val{};
switch (auto const ec =
mdb_cursor_get(cursor_, k, &v, static_cast<MDB_cursor_op>(op));
ec) {
case MDB_SUCCESS:
return std::make_pair(from_mdb_val(*k), from_mdb_val(v));
case MDB_NOTFOUND: return std::nullopt;
default: throw std::system_error{error::make_error_code(ec)};
}
}
template <typename T>
void put(T key, std::string_view value,
put_flags const flags = put_flags::NONE) {
auto k = to_mdb_val(key);
auto v = to_mdb_val(value);
ex(mdb_cursor_put(cursor_, &k, &v, static_cast<unsigned>(flags)));
txn_->is_write_ = true;
}
void del() {
ex(mdb_cursor_del(cursor_, 0));
txn_->is_write_ = true;
}
void del_nodupdata() {
ex(mdb_cursor_del(cursor_, MDB_NODUPDATA));
txn_->is_write_ = true;
}
mdb_size_t count() {
mdb_size_t n;
ex(mdb_cursor_count(cursor_, &n));
return n;
}
txn::dbi get_dbi() {
return {mdb_cursor_txn(cursor_), mdb_cursor_dbi(cursor_)};
}
txn* txn_;
MDB_cursor* cursor_;
};
} // namespace lmdb
|
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace SPIRVCross
{
/// <summary>
///
/// </summary>
public static partial class SPIRV
{
///// <summary>
///// SPIRV_CROSS_C_API_H =
//public const string SPIRV_CROSS_C_API_H = ;
///// <summary>
///// spirv_H =
//public const string spirv_H = ;
///// <summary>
///// SPV_VERSION = 0x10500
//public const string SPV_VERSION = 0x10500;
///// <summary>
///// SPV_REVISION = 4
//public const uint SPV_REVISION = 4;
///// <summary>
///// SPVC_C_API_VERSION_MAJOR = 0
//public const uint SPVC_C_API_VERSION_MAJOR = 0;
///// <summary>
///// SPVC_C_API_VERSION_MINOR = 44
//public const uint SPVC_C_API_VERSION_MINOR = 44;
///// <summary>
///// SPVC_C_API_VERSION_PATCH = 0
//public const uint SPVC_C_API_VERSION_PATCH = 0;
///// <summary>
///// SPVC_PUBLIC_API =
//public const string SPVC_PUBLIC_API = ;
///// <summary>
///// SPVC_TRUE = ((spvc_bool)1)
//public const uint SPVC_TRUE = (1);
///// <summary>
///// SPVC_FALSE = ((spvc_bool)0)
//public const string SPVC_FALSE = ((spvc_bool)0);
///// <summary>
///// SPVC_COMPILER_OPTION_COMMON_BIT = 0x1000000
//public const string SPVC_COMPILER_OPTION_COMMON_BIT = 0x1000000;
///// <summary>
///// SPVC_COMPILER_OPTION_GLSL_BIT = 0x2000000
//public const string SPVC_COMPILER_OPTION_GLSL_BIT = 0x2000000;
///// <summary>
///// SPVC_COMPILER_OPTION_HLSL_BIT = 0x4000000
//public const string SPVC_COMPILER_OPTION_HLSL_BIT = 0x4000000;
///// <summary>
///// SPVC_COMPILER_OPTION_MSL_BIT = 0x8000000
//public const uint SPVC_COMPILER_OPTION_MSL_BIT = 0x8000000;
///// <summary>
///// SPVC_COMPILER_OPTION_LANG_BITS = 0x0f000000
//public const string SPVC_COMPILER_OPTION_LANG_BITS = 0x0f000000;
///// <summary>
///// SPVC_COMPILER_OPTION_ENUM_BITS = 0xffffff
//public const float SPVC_COMPILER_OPTION_ENUM_BITS = 0xffffff;
///// <summary>
///// SPVC_MAKE_MSL_VERSION = ((major)*10000+(minor)*100+(patch))
//public const string SPVC_MAKE_MSL_VERSION = ((major)*10000+(minor)*100+(patch));
///// <summary>
///// SPVC_MSL_PUSH_CONSTANT_DESC_SET = (~(0u))
//public const string SPVC_MSL_PUSH_CONSTANT_DESC_SET = (~(0u));
///// <summary>
///// SPVC_MSL_PUSH_CONSTANT_BINDING = (0)
//public const string SPVC_MSL_PUSH_CONSTANT_BINDING = (0);
///// <summary>
///// SPVC_MSL_SWIZZLE_BUFFER_BINDING = (~(1u))
//public const string SPVC_MSL_SWIZZLE_BUFFER_BINDING = (~(1u));
///// <summary>
///// SPVC_MSL_BUFFER_SIZE_BUFFER_BINDING = (~(2u))
//public const string SPVC_MSL_BUFFER_SIZE_BUFFER_BINDING = (~(2u));
///// <summary>
///// SPVC_MSL_ARGUMENT_BUFFER_BINDING = (~(3u))
//public const string SPVC_MSL_ARGUMENT_BUFFER_BINDING = (~(3u));
///// <summary>
///// SPVC_MSL_AUX_BUFFER_STRUCT_VERSION = 1
//public const uint SPVC_MSL_AUX_BUFFER_STRUCT_VERSION = 1;
///// <summary>
///// SPVC_HLSL_PUSH_CONSTANT_DESC_SET = (~(0u))
//public const string SPVC_HLSL_PUSH_CONSTANT_DESC_SET = (~(0u));
///// <summary>
///// SPVC_HLSL_PUSH_CONSTANT_BINDING = (0)
//public const string SPVC_HLSL_PUSH_CONSTANT_BINDING = (0);
}
}
|
package analysisservices
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"net/http"
)
// ConnectionMode enumerates the values for connection mode.
type ConnectionMode string
const (
// All specifies the all state for connection mode.
All ConnectionMode = "All"
// ReadOnly specifies the read only state for connection mode.
ReadOnly ConnectionMode = "ReadOnly"
)
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// Deleting specifies the deleting state for provisioning state.
Deleting ProvisioningState = "Deleting"
// Failed specifies the failed state for provisioning state.
Failed ProvisioningState = "Failed"
// Paused specifies the paused state for provisioning state.
Paused ProvisioningState = "Paused"
// Pausing specifies the pausing state for provisioning state.
Pausing ProvisioningState = "Pausing"
// Preparing specifies the preparing state for provisioning state.
Preparing ProvisioningState = "Preparing"
// Provisioning specifies the provisioning state for provisioning state.
Provisioning ProvisioningState = "Provisioning"
// Resuming specifies the resuming state for provisioning state.
Resuming ProvisioningState = "Resuming"
// Scaling specifies the scaling state for provisioning state.
Scaling ProvisioningState = "Scaling"
// Succeeded specifies the succeeded state for provisioning state.
Succeeded ProvisioningState = "Succeeded"
// Suspended specifies the suspended state for provisioning state.
Suspended ProvisioningState = "Suspended"
// Suspending specifies the suspending state for provisioning state.
Suspending ProvisioningState = "Suspending"
// Updating specifies the updating state for provisioning state.
Updating ProvisioningState = "Updating"
)
// SkuTier enumerates the values for sku tier.
type SkuTier string
const (
// Basic specifies the basic state for sku tier.
Basic SkuTier = "Basic"
// Development specifies the development state for sku tier.
Development SkuTier = "Development"
// Standard specifies the standard state for sku tier.
Standard SkuTier = "Standard"
)
// State enumerates the values for state.
type State string
const (
// StateDeleting specifies the state deleting state for state.
StateDeleting State = "Deleting"
// StateFailed specifies the state failed state for state.
StateFailed State = "Failed"
// StatePaused specifies the state paused state for state.
StatePaused State = "Paused"
// StatePausing specifies the state pausing state for state.
StatePausing State = "Pausing"
// StatePreparing specifies the state preparing state for state.
StatePreparing State = "Preparing"
// StateProvisioning specifies the state provisioning state for state.
StateProvisioning State = "Provisioning"
// StateResuming specifies the state resuming state for state.
StateResuming State = "Resuming"
// StateScaling specifies the state scaling state for state.
StateScaling State = "Scaling"
// StateSucceeded specifies the state succeeded state for state.
StateSucceeded State = "Succeeded"
// StateSuspended specifies the state suspended state for state.
StateSuspended State = "Suspended"
// StateSuspending specifies the state suspending state for state.
StateSuspending State = "Suspending"
// StateUpdating specifies the state updating state for state.
StateUpdating State = "Updating"
)
// Status enumerates the values for status.
type Status string
const (
// Live specifies the live state for status.
Live Status = "Live"
)
// ErrorResponse is describes the format of Error response.
type ErrorResponse struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
// GatewayDetails is the gateway details.
type GatewayDetails struct {
GatewayResourceID *string `json:"gatewayResourceId,omitempty"`
GatewayObjectID *string `json:"gatewayObjectId,omitempty"`
DmtsClusterURI *string `json:"dmtsClusterUri,omitempty"`
}
// GatewayError is detail of gateway errors.
type GatewayError struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
// GatewayListStatusError is status of gateway is error.
type GatewayListStatusError struct {
Error *GatewayError `json:"error,omitempty"`
}
// GatewayListStatusLive is status of gateway is live.
type GatewayListStatusLive struct {
autorest.Response `json:"-"`
Status Status `json:"status,omitempty"`
}
// IPv4FirewallRule is the detail of firewall rule.
type IPv4FirewallRule struct {
FirewallRuleName *string `json:"firewallRuleName,omitempty"`
RangeStart *string `json:"rangeStart,omitempty"`
RangeEnd *string `json:"rangeEnd,omitempty"`
}
// IPv4FirewallSettings is an array of firewall rules.
type IPv4FirewallSettings struct {
FirewallRules *[]IPv4FirewallRule `json:"firewallRules,omitempty"`
EnablePowerBIService *string `json:"enablePowerBIService,omitempty"`
}
// Operation is a Consumption REST API operation.
type Operation struct {
Name *string `json:"name,omitempty"`
Display *OperationDisplay `json:"display,omitempty"`
}
// OperationDisplay is the object that represents the operation.
type OperationDisplay struct {
Provider *string `json:"provider,omitempty"`
Resource *string `json:"resource,omitempty"`
Operation *string `json:"operation,omitempty"`
}
// OperationListResult is result of listing consumption operations. It contains a list of operations and a URL link to
// get the next set of results.
type OperationListResult struct {
autorest.Response `json:"-"`
Value *[]Operation `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
// Resource is represents an instance of an Analysis Services resource.
type Resource struct {
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
Location *string `json:"location,omitempty"`
Sku *ResourceSku `json:"sku,omitempty"`
Tags *map[string]*string `json:"tags,omitempty"`
}
// ResourceSku is represents the SKU name and Azure pricing tier for Analysis Services resource.
type ResourceSku struct {
Name *string `json:"name,omitempty"`
Tier SkuTier `json:"tier,omitempty"`
Capacity *int32 `json:"capacity,omitempty"`
}
// Server is represents an instance of an Analysis Services resource.
type Server struct {
autorest.Response `json:"-"`
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
Location *string `json:"location,omitempty"`
Sku *ResourceSku `json:"sku,omitempty"`
Tags *map[string]*string `json:"tags,omitempty"`
*ServerProperties `json:"properties,omitempty"`
}
// ServerAdministrators is an array of administrator user identities.
type ServerAdministrators struct {
Members *[]string `json:"members,omitempty"`
}
// ServerMutableProperties is an object that represents a set of mutable Analysis Services resource properties.
type ServerMutableProperties struct {
AsAdministrators *ServerAdministrators `json:"asAdministrators,omitempty"`
BackupBlobContainerURI *string `json:"backupBlobContainerUri,omitempty"`
GatewayDetails *GatewayDetails `json:"gatewayDetails,omitempty"`
IPV4FirewallSettings *IPv4FirewallSettings `json:"ipV4FirewallSettings,omitempty"`
QuerypoolConnectionMode ConnectionMode `json:"querypoolConnectionMode,omitempty"`
}
// ServerProperties is properties of Analysis Services resource.
type ServerProperties struct {
AsAdministrators *ServerAdministrators `json:"asAdministrators,omitempty"`
BackupBlobContainerURI *string `json:"backupBlobContainerUri,omitempty"`
GatewayDetails *GatewayDetails `json:"gatewayDetails,omitempty"`
IPV4FirewallSettings *IPv4FirewallSettings `json:"ipV4FirewallSettings,omitempty"`
QuerypoolConnectionMode ConnectionMode `json:"querypoolConnectionMode,omitempty"`
State State `json:"state,omitempty"`
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
ServerFullName *string `json:"serverFullName,omitempty"`
}
// Servers is an array of Analysis Services resources.
type Servers struct {
autorest.Response `json:"-"`
Value *[]Server `json:"value,omitempty"`
}
// ServerUpdateParameters is provision request specification
type ServerUpdateParameters struct {
Sku *ResourceSku `json:"sku,omitempty"`
Tags *map[string]*string `json:"tags,omitempty"`
*ServerMutableProperties `json:"properties,omitempty"`
}
// SkuDetailsForExistingResource is an object that represents SKU details for existing resources.
type SkuDetailsForExistingResource struct {
Sku *ResourceSku `json:"sku,omitempty"`
}
// SkuEnumerationForExistingResourceResult is an object that represents enumerating SKUs for existing resources.
type SkuEnumerationForExistingResourceResult struct {
autorest.Response `json:"-"`
Value *[]SkuDetailsForExistingResource `json:"value,omitempty"`
}
// SkuEnumerationForNewResourceResult is an object that represents enumerating SKUs for new resources.
type SkuEnumerationForNewResourceResult struct {
autorest.Response `json:"-"`
Value *[]ResourceSku `json:"value,omitempty"`
}
|
library pineaple_repo_def_exporter;
// Export all the usecase implementations.
export 'pineaple_area_repo_def.dart';
export 'pineaple_pos_repo_def.dart';
|
package spark1.project.domain
case class ClickLog(ip:String,time:String,courseId:Int,statusCode:Int,referer:String)
|
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { TdFullscreenDirective } from './fullscreen.directive';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { By } from '@angular/platform-browser';
@Component({
template: `
<div tdFullScreen #myDirective="tdFullScreen">
<button id="test-btn" mat-button color="primary" (click)="myDirective.toggleFullScreen()">Fullscreen</button>
<button id="test-btn-exit" mat-button color="warn" (click)="myDirective.exitFullScreen()">exit Fullscreen</button>
</div>
`,
})
class TdFullscreenTestComponent {}
describe('TdFullscreenDirective', () => {
let fixture: ComponentFixture<TdFullscreenTestComponent>;
let btnEl: DebugElement;
let btnExit: DebugElement;
let directiveEl: DebugElement;
let directive: TdFullscreenDirective;
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
TestBed.configureTestingModule({
declarations: [TdFullscreenTestComponent, TdFullscreenDirective],
}).compileComponents();
fixture = TestBed.createComponent(TdFullscreenTestComponent);
btnEl = fixture.debugElement.query(By.css('#test-btn'));
btnExit = fixture.debugElement.query(By.css('#test-btn-exit'));
directiveEl = fixture.debugElement.query(By.directive(TdFullscreenDirective));
directive = directiveEl.injector.get(TdFullscreenDirective);
});
it('Should capture fullscreenchange event and toggle fullScreenIsActive property', async () => {
expect(directive.fullScreenIsActive).toBeFalsy();
const changeSpy: any = spyOn(directive, 'fsChangeHandler').and.returnValue(true);
btnEl.triggerEventHandler('fullscreenchange', undefined);
directive.fullScreenIsActive = true;
fixture.detectChanges();
await fixture.whenStable();
expect(changeSpy).toBeDefined();
expect(changeSpy).toBeTruthy();
expect(directive.fullScreenIsActive).toBeTruthy();
});
it('should trigger toggleFullscreen() on template', () => {
const toggleSpy: any = spyOn(directive, 'toggleFullScreen').and.returnValue(true);
btnEl.triggerEventHandler('click', undefined);
fixture.detectChanges();
expect(toggleSpy).toBeDefined();
expect(toggleSpy).toBeTruthy();
});
it('fullScreenIsActive should change boolean value', () => {
directive.fullScreenIsActive = true;
fixture.detectChanges();
expect(directive.fullScreenIsActive).toBe(true);
directive.fullScreenIsActive = false;
fixture.detectChanges();
expect(directive.fullScreenIsActive).toBe(false);
});
it('should call enterFullScreen() on directive', async () => {
const enterSpy: any = spyOn(directive, 'enterFullScreen').and.returnValue(true);
btnEl.triggerEventHandler('click', undefined);
fixture.detectChanges();
await fixture.whenStable();
expect(enterSpy).toBeDefined();
expect(enterSpy).toHaveBeenCalled();
expect(enterSpy).toBeTruthy();
});
it('should call exitFullScreen() on directive', async () => {
const exitSpy: any = spyOn(directive, 'exitFullScreen').and.callFake(() => true);
btnExit.triggerEventHandler('click', undefined);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(exitSpy).toBeDefined();
expect(exitSpy).toHaveBeenCalled();
expect(exitSpy).toBeTruthy();
});
});
|
<?php
declare(strict_types=1);
namespace IamPersistent\SimpleShop\Interactor\DBal;
use DateTime;
use IamPersistent\SimpleShop\Entity\CreditCard;
use IamPersistent\SimpleShop\Interactor\FindCardByIdInterface;
final class FindCardById extends DBalCommon implements FindCardByIdInterface
{
public function find($id): ?CreditCard
{
$statement = $this->connection->executeQuery('SELECT * FROM credit_cards WHERE id ='. $id);
$cardData = $statement->fetch();
if (empty($cardData)) {
return null;
}
return (new HydrateCreditCard())($cardData);
}
} |
---
uid: System.EnterpriseServices.ApplicationIDAttribute
internalonly: False
---
---
uid: System.EnterpriseServices.ApplicationIDAttribute.Value
internalonly: False
---
---
uid: System.EnterpriseServices.ApplicationIDAttribute.#ctor(System.String)
internalonly: False
---
|
# Allows you to see the Virtuoso loading progress, once started with load.sh
#
sql='select count(*) from DB.DBA.LOAD_LIST'
isql='/nfs/public/rw/homes/rdf_adm/virtuoso-opensource-7/bin/isql 127.0.0.1:1151 dba dba'
echo ------ Loaded Files ------
echo "$sql WHERE ll_state = 2;" | $isql
echo ------ Total Files ------
echo "$sql;" | $isql
|
/**
* @Author: Mervyn
* @Date: 2016,Apr,30 11:52:05
* @Last modified by: Mervyn
* @Last modified time: 2016,Aug,01 01:02:40
*/
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
BackAndroid,
ToastAndroid,
} from 'react-native';
import {Main} from './views/android/main';
import {Pop} from './views/android/pop';
class playwithrn extends Component {
constructor(props) {
super(props);
this.state = {
mainTag: false,
// outTag: 0
};
}
componentDidMount() {
setTimeout(
() => {
this.setState({mainTag: true});
},
2000);
let outTag = 0;
BackAndroid.addEventListener('hardwareBackPress', () => {
// return true;
// ToastAndroid.show(outTag + '', ToastAndroid.SHORT);
if (outTag < 1) {
var toast = ToastAndroid.show('Press again to exit MicroIR', ToastAndroid.SHORT);
outTag++;
setTimeout(
() => {
outTag = 0;
},
1000);
return true;
} else {
// BackAndroid.exitApp();
// toast.cancel();
return false;
}
});
}
render() {
if (this.state.mainTag) {
return (
<Main></Main>
);
} else {
return (
<Pop></Pop>
);
}
}
}
AppRegistry.registerComponent('playwithrn', () => playwithrn);
|
package com.ONLLL.basequickadapter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorLong;
import android.support.annotation.DrawableRes;
import android.support.annotation.FloatRange;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.util.SparseArray;
import android.view.View;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.TextView;
/**
* author xingyun
* create at 2017/9/26 16:54
* description:适用所有RecyclerView的ViewHolder
*/
public class BaseViewHolder extends RecyclerView.ViewHolder {
//子布局中的控件
private SparseArray<View> mItemViews;
//子布局
private View mView;
//初始化ViewHolder
public BaseViewHolder(View itemView) {
super(itemView);
mView = itemView;
mItemViews = new SparseArray<>();
}
/**
* 获取子控件
* <p>
* 子控件的id
*
* @param viewId 返回子控件
* @return
*/
public View getView(@IdRes int viewId) {
View view = mItemViews.get(viewId);
if (view == null) {
view = mView.findViewById(viewId);
mItemViews.put(viewId, view);
}
return view;
}
/**
* 通过strings.xml文件给TextView设置文本
* <p>
* 子控件的id
*
* @param viewId 子控件在strings.xml中的文本
* @param resId 返回子控件
* @return BaseViewHolder
*/
public BaseViewHolder setText(@IdRes int viewId, @StringRes int resId) {
TextView textView = (TextView) getView(viewId);
textView.setText(resId);
return this;
}
/**
* 通过String给TextView设置文本
* <p>
* 子控件的id
*
* @param viewId 子控件中的文本
* @param text 返回子控件
* @return BaseViewHolder
*/
public BaseViewHolder setText(@IdRes int viewId, String text) {
TextView textView = (TextView) getView(viewId);
if (text != null) {
textView.setText(text);
} else {
textView.setText("");
}
return this;
}
/**
* 通过SpannableStringBuilder给TextView设置文本
*
* @param viewId View的id
* @param text 文本
* @return BaseViewHolder
*/
public BaseViewHolder setText(@IdRes int viewId, SpannableStringBuilder text) {
TextView textView = (TextView) getView(viewId);
if (text != null) {
textView.setText(text);
} else {
textView.setText("");
}
return this;
}
/**
* 通过drawable文件夹中的资源设置图片
*
* @param viewId view的id
* @param resId 文本
* @return BaseViewHolder
*/
public BaseViewHolder setImageResource(@IdRes int viewId, @DrawableRes int resId) {
ImageView imageView = (ImageView) getView(viewId);
imageView.setImageResource(resId);
return this;
}
/**
* 通过Bitmap设置图片
*
* @param viewId view Id
* @param bitmap Bitmap
* @return BaseViewHolder
*/
public BaseViewHolder setImageBitmap(@IdRes int viewId, @NonNull Bitmap bitmap) {
ImageView imageView = (ImageView) getView(viewId);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
return this;
}
/**
* 通过Drawable设置图片
*
* @param viewId View的id
* @param drawable Drawable
* @return BaseViewHolder
*/
public BaseViewHolder setImageDrawable(@IdRes int viewId, @NonNull Drawable drawable) {
ImageView imageView = (ImageView) getView(viewId);
if (drawable != null) {
imageView.setImageDrawable(drawable);
}
return this;
}
/**
* 通过一串数字设置背景色
*
* @param viewId View的id
* @param color 颜色值 16进制
* @return BaseViewHolder
*/
public BaseViewHolder setBackgroundColor(@IdRes int viewId, @ColorLong int color) {
View view = getView(viewId);
view.setBackgroundColor(color);
return this;
}
/**
* 通过drawable文件夹设置背景图
*
* @param viewId View的id
* @param backgroundRes Resource
* @return BaseViewHolder
*/
public BaseViewHolder setBackgroundResource(@IdRes int viewId, @DrawableRes int backgroundRes) {
View view = getView(viewId);
view.setBackgroundResource(backgroundRes);
return this;
}
/**
* 通过Drawable设置背景图
*
* @param viewId View的id
* @param drawable Drawable
* @return BaseViewHolder
*/
public BaseViewHolder setBackgroundDrawable(@IdRes int viewId, Drawable drawable) {
View view = getView(viewId);
if (drawable != null) {
view.setBackground(drawable);
}
return this;
}
/**
* 通过一串数字设置文字颜色
*
* @param viewId View的id
* @param textColor 颜色值 16进制
* @return BaseViewHolder
*/
public BaseViewHolder setTextColor(@IdRes int viewId, @ColorLong int textColor) {
TextView textView = (TextView) getView(viewId);
textView.setTextColor(textColor);
return this;
}
/**
* 通过float设置透明度
*
* @param viewId View的id
* @param value 透明度 范围:[0.0,1.0]
* @return BaseViewHolder
*/
public BaseViewHolder setAlpha(@IdRes int viewId, @FloatRange(from = 0.0, to = 1.0) float
value) {
getView(viewId).setAlpha(value);
return this;
}
/**
* 通过boolean类型设置是否显示
*
* @param viewId View的id
* @param visible 是否可见 true:可见; false:不可见,Gone
* @return BaseViewHolder
*/
public BaseViewHolder setVisible(@IdRes int viewId, boolean visible) {
View view = getView(viewId);
view.setVisibility(visible ? view.VISIBLE : View.GONE);
return this;
}
/**
* 缓存子控件上界面的数据
*
* @param viewId View的id
* @param tag 需要缓存的数据
* @return BaseViewHolder
*/
public BaseViewHolder setTag(@IdRes int viewId, Object tag) {
View view = getView(viewId);
view.setTag(tag);
return this;
}
/**
* 设置某一位置子控件的数据
*
* @param viewId View的id
* @param key 数据标识
* @param tag 数据
* @return BaseViewHolder
*/
public BaseViewHolder setTag(@IdRes int viewId, int key, Object tag) {
View view = getView(viewId);
view.setTag(key, tag);
return this;
}
/**
* 设置子控件是否选中
*
* @param viewId View的id
* @param checked true:选中 false:未选中
* @return BaseViewHolder
*/
public BaseViewHolder setChecked(@IdRes int viewId, boolean checked) {
Checkable checkable = (Checkable) getView(viewId);
checkable.setChecked(checked);
return this;
}
/**
* 设置子控件的点击事件
*
* @param viewId View的id
* @param listener OnClickListener监听器
* @return BaseViewHolder
*/
public BaseViewHolder setOnClickListener(@IdRes int viewId, @NonNull View.OnClickListener
listener) {
View view = getView(viewId);
if (listener != null) {
view.setOnClickListener(listener);
}
return this;
}
/**
* 设置子控件的触摸事件
*
* @param viewId View的id
* @param listener OnTouchListener
* @return BaseViewHolder
*/
public BaseViewHolder setOnTouchListener(@IdRes int viewId, @NonNull View.OnTouchListener
listener) {
View view = getView(viewId);
if (listener != null) {
view.setOnTouchListener(listener);
}
return this;
}
/**
* 设置子控件的长按事件
*
* @param viewId View的id
* @param listener OnLongClickListener
* @return BaseViewHolder
*/
public BaseViewHolder setOnLongClickListener(@IdRes int viewId, @NonNull View
.OnLongClickListener
listener) {
View view = getView(viewId);
if (listener != null) {
view.setOnLongClickListener(listener);
}
return this;
}
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UID extends CI_Model {
public function generate($pref,$tbl,$id_col)
{
$id = uniqid($pref);
while($this->db->get_where($tbl,[$id_col=>$id])->num_rows()>0){
$id = uniqid($pref);
}
return($id);
}
}
|
CREATE TABLE [dbo].[Channel]
(
[ChannelId] INT NOT NULL PRIMARY KEY IDENTITY(1,1),
[Name] NVARCHAR(200) NOT NULL,
[Description] NVARCHAR(4000) NOT NULL,
[UniqueAlias] NVARCHAR(200) NOT NULL,
[ParentChannelID] INT NULL,
[ImageUrl] NVARCHAR(250) NULL,
[CreatedDate] DATETIME NOT NULL DEFAULT GETUTCDATE(),
[CreatedByUserId] INT NOT NULL,
[LastModifiedDate] DATETIME NULL DEFAULT GETUTCDATE(),
[LastModifiedUserID] INT NULL,
[IsVisible] BIT NOT NULL DEFAULT 1,
CONSTRAINT [FK_Channel_Channel] FOREIGN KEY ([ParentChannelID]) REFERENCES [Channel]([ParentChannelID]),
CONSTRAINT [FK_Channel_User_CreatedByUserId] FOREIGN KEY ([CreatedByUserId]) REFERENCES [User]([UserId]),
CONSTRAINT [FK_Channel_User_LastModifiedUserID] FOREIGN KEY ([LastModifiedUserID]) REFERENCES [User]([UserId])
)
GO
CREATE INDEX [IX_Channel_ParentChannelID] ON [dbo].[Channel] ([ParentChannelID])
|
package com.gitee.code4fun.facerecognition.common.util;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* @author yujingze
* @data 18/4/8
*/
public class ResponseBuilder {
private HashMap<String,Object> data = new HashMap<String, Object>();
public ResponseBuilder success(){
this.setCode(ResponseStatus.SUCCESS.getCode());
this.setMsg(ResponseStatus.SUCCESS.getMsg());
return this;
}
public ResponseBuilder failure(String code,String message){
this.setCode(code);
this.setMsg(message);
return this;
}
public ResponseBuilder setCode(String code){
this.putData("code",code);
return this;
}
public ResponseBuilder setMsg(String msg){
this.putData("msg",msg);
return this;
}
public ResponseBuilder putData(String key,Object value){
this.data.put(key,value);
return this;
}
public JSONObject build(){
JSONObject obj = new JSONObject();
for(Map.Entry<String,Object> entry : data.entrySet()){
obj.put(entry.getKey(),entry.getValue());
}
return obj;
}
public static void main(String[] args){
JSONObject obj = new ResponseBuilder().setCode("123")
.setMsg("abc")
.putData("aaa","aaa")
.putData("bbb","bbb")
.build();
System.out.println(obj.toJSONString());
}
}
|
<?php
class XenForo_DataWriter_Helper_Option
{
/**
* Verifies that the Google Analytics Web Property ID is valid, if specified.
* See https://www.google.com/support/googleanalytics/bin/answer.py?answer=113500
*
* @param string $wpId
* @param XenForo_DataWriter $dw
* @param string $fieldName
*
* @return boolean
*/
public static function verifyGoogleAnalyticsWebPropertyId(&$wpId, XenForo_DataWriter $dw, $fieldName)
{
if ($wpId !== '' && !preg_match('/^UA-\d+-\d+$/', $wpId))
{
$dw->error(new XenForo_Phrase('please_enter_your_google_analytics_web_property_id_in_format'), $fieldName);
return false;
}
return true;
}
} |
subroutine foo
c equivalence between variable and single dimensional array
integer len
parameter (len = 10)
integer var
integer array(20)
equivalence(var, array(len + 5))
c equivalence for substring
c equivalence among multiple entities
c character a*4, b*4, c(2)*3
c equivalence (A, C(1)), (B,C(2))
c equivalence causes merging of memory blocks
c size are equal, but offsets are different
real b(10)
real c(10)
equivalence (b(10), c(5))
c offsets are equal, but sizes are different
integer d(10)
integer e(5)
equivalence (d, e)
c three way equivalence
character aa*4, bb*4, cc(2)*3
equivalence (aa, cc(1)), (bb, cc(2))
c three way equivalence
integer*2 sndbuff(16)
integer*4 sndbbid1, sndbbid2
equivalence (sndbuff(2),sndbbid1)
equivalence (sndbuff(4),sndbbid2)
c equvalence list
real r1
real r2
real r3
integer i1
integer i2
integer i3
equivalence (r1, r2, r3), (i1, i2, i3)
c equivalence for multidimensional array
real onedim(10)
real twodim(10, 10)
real threedim(10,10,10)
real fourdim(10,10,10,10)
real fivedim(10,10,10,10,10)
real sixdim(10,10,10,10,10,10)
real sevendim(10,10,10,10,10,10,10)
equivalence (threedim(2,2,2), twodim(2,2))
equivalence (sevendim(2,2,2,2,2,2,2), fivedim)
c substring
character inbuf*80
character exchange_code*1
character price*6
equivalence(inbuf(10:),exchange_code)
equivalence(inbuf(23:28),price)
CHARACTER control_switches(20)*8
CHARACTER*1 tick
equivalence (tick, control_switches(1)(8:8))
c repeated equivalences
integer*4 p6buf(4)
integer*2 p6buf2(8)
integer*4 p6uuid
equivalence (p6buf(1),p6buf2(1))
equivalence (p6buf(1),p6uuid)
equivalence (p6buf2(1),p6uuid)
equivalence (p6buf(1),p6buf2(1))
equivalence (p6buf(1),p6buf2(1),p6uuid)
return
end
|
require 'spec_helper'
describe Ducktrap::Mapper do
let(:object) { described_class }
subject { described_class.build(&block) }
let(:block) { proc {} }
let(:builder) { double('Builder', :object => mapper) }
let(:mapper) { double('Mapper') }
it 'should call Ducktrap::Mapper::Builder' do
Ducktrap::Mapper::Builder.should_receive(:new).with(described_class) do |&block|
block.should be(self.block)
builder
end
subject.should be(mapper)
end
end
|
import Math.NumberTheory.Powers.Squares (exactSquareRoot)
import Data.Foldable
compositions :: Int -> [[Int]]
compositions 0 = [[]]
compositions n = concatMap (\k -> map (k:) $ compositions (n-k)) [1..n]
-- Very closely related to A228352.
f k n = sum $ map ((k^) . numberOfOnes) $ compositions n where
numberOfOnes = length . filter (== 1)
a000079 = f 1
a001519 = f 2
a007052 = f 3
a018902 = f 4
a018903 = f 5
a018904 = f 6
a000027 n = f n 1
a002522 n = f n 2
a135859 n = f n 3 -- Number of binary 3 X (n-1) matrices such that each row and column has at most one 1.
-- 1 2 4 8 16 32 64 128 256 512
-- 2 5 13 34 89 233 610 1597 4181 10946
-- 3 10 34 116 396 1352 4616 15760 53808 183712
-- 4 17 73 314 1351 5813 25012 107621 463069 1992482
-- 5 26 136 712 3728 19520 102208 535168 2802176 14672384
-- 6 37 229 1418 8781 54377 336734 2085253 12913101 79965442
-- 7 50 358 2564 18364 131528 942040 6747152 48324976 346116896
a337243order c1 c2
| sum c1 < sum c2 = LT
| sum c1 > sum c2 = GT
| length c1 < length c2 = LT
| length c1 > length c2 = GT
| otherwise = compare (reverse c1) (reverse c2)
flatMap f = concatMap (Data.Foldable.toList . f)
g x = foldl maybeRoot (Just 0) x
-- f ::
maybeRoot a2 a1 = exactSquareRoot =<< fmap (+a1) a2
|
<?php
namespace OneLang\One\Transforms\InferTypesPlugins\Helpers\InferTypesPlugin;
use OneLang\One\ErrorManager\ErrorManager;
use OneLang\One\Ast\Expressions\Expression;
use OneLang\One\Transforms\InferTypes\InferTypes;
use OneLang\One\Ast\Statements\Statement;
use OneLang\One\Ast\Types\Property;
use OneLang\One\Ast\Types\Lambda;
use OneLang\One\Ast\Types\Method;
use OneLang\One\Ast\Types\IMethodBase;
class InferTypesPlugin {
public $main;
public $errorMan;
public $name;
function __construct($name) {
$this->name = $name;
$this->errorMan = null;
}
function canTransform($expr) {
return false;
}
function canDetectType($expr) {
return false;
}
function transform($expr) {
return $expr;
}
function detectType($expr) {
return false;
}
function handleProperty($prop) {
return false;
}
function handleLambda($lambda) {
return false;
}
function handleMethod($method) {
return false;
}
function handleStatement($stmt) {
return false;
}
}
|
package com.tz.service;
import com.tz.pojo.ZaGift;
import com.tz.pojo.index.vo.ZaGiftVo;
import com.tz.res.AppMsgResult;
public interface GiftService {
AppMsgResult getGiftList(ZaGiftVo zaGiftVo,Integer curPage,Integer rows, String userId, String token);
AppMsgResult addOrUpdateGift(ZaGift zagift, String type, String userId, String token);
AppMsgResult delGiftById(String id, String userId, String token);
AppMsgResult giftFreezeById(String id, Integer status, String userId, String token);
AppMsgResult queryGiftById(String id, String userId, String token);
}
|
#!/bin/bash
NIGHTBOT_COMMAND="<command id>"
SCRIPT_DIR="/Users/noopkat/bin/twitch-scripts"
CREDS_FILE="${SCRIPT_DIR}/nightbot-creds.txt"
TOKENS_FILE="${SCRIPT_DIR}/nightbot-tokens.txt"
REFRESH_TOKEN=$(cat $TOKENS_FILE | /usr/local/bin/jq '.refresh_token' -r)
CREDS=$(cat $CREDS_FILE)
curl -X POST https://api.nightbot.tv/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "${CREDS}&grant_type=refresh_token&refresh_token=${REFRESH_TOKEN}" \
--silent \
-o $TOKENS_FILE
ACCESS_TOKEN=$(cat $TOKENS_FILE | /usr/local/bin/jq '.access_token' -r)
LAST_STATUS=$(curl -X GET "https://api.nightbot.tv/1/commands/${NIGHTBOT_COMMAND}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
--silent \
| /usr/local/bin/jq '.command.message' -r)
echo $LAST_STATUS
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
//Le pts d'interogation indique que le param est optionnel
Route::get('/{auteur?}',[
'uses'=>'OffresController@recupererIndex',
'as'=>'index'
]);
Route::post('/creation',[
'uses'=> 'OffresController@creationoffre',
'as'=>'creation'
]);
Route::get('/supprimer/{offre_id}',[
'uses'=>'OffresController@supprimerOffre',
'as'=>'supprimer'
]);
Route::get('/recuemail/{auteur_nom}',[
'uses'=>'OffresController@receptionMailCallback',
'as'=>'mail_callback'
]);
Route::get('/admin/login',[
'uses'=>'AdminController@getLogin',
'as'=>'admin.login'
]);
Route::post('/admin/login',[
'uses'=>'AdminController@postLogin',
'as'=>'admin.login'
]);
//On protege soit une par une ...
//Route::get('/admin/dashboard',[
// 'uses'=>'AdminController@getDashboard',
// 'as'=>'admin.dashboard',
// 'middleware'=>'auth'
//]);
//Route::get('/admin/les-offres',function(){
// return view('admin.lesOffres');
//})->middleware('auth');
//Soit en groupe :)
Route::group(['middleware'=>'auth'],function(){
Route::get('/admin/dashboard',[
'uses'=>'AdminController@getDashboard',
'as'=>'admin.dashboard'
]);
Route::get('/admin/les-offres',function(){
return view('admin.lesOffres');
});
});
Route::get('/admin/logout',[
'uses'=>'AdminController@getLogout',
'as'=>'admin.logout'
]);
Route::get('/admin/les-offres',function(){
return view('admin.lesOffres');
})->middleware('auth');
|
2020年08月01日23时数据
Status: 200
1.张继科和镜子里动作不一样
微博热度:4023024
2.警方发现在青海失联女大学生遗骸
微博热度:2842198
3.沙溢带兄弟团回家
微博热度:2669182
4.刘忻为了乐夏拒绝乘风破浪
微博热度:2548949
5.字节跳动同意剥离TIKTOK美国业务
微博热度:2231545
6.小鸡长在王一博笑点上
微博热度:1669204
7.691分考入清华暑期搬砖打工
微博热度:1304573
8.5人出游唯一生还者发声
微博热度:1097393
9.TikTok明星博主向粉丝道别
微博热度:904993
10.伊朗称逮捕了美国支持的恐怖组织头目
微博热度:860830
11.父亲回应留守女儿选北大考古专业
微博热度:859511
12.胡宇桐终于把话说开了
微博热度:858996
13.快乐大本营
微博热度:856413
14.云南吃菌中毒死亡人数超过新冠
微博热度:748342
15.这就是街舞
微博热度:663676
16.武汉火神山医院的设备仍在原地列队
微博热度:572080
17.林有有许幻山
微博热度:551574
18.白举纲被专业乐迷质疑
微博热度:547228
19.苹果中国区商店半天下架近3万款应用
微博热度:528812
20.疫情期间拉邻居到家喝酒2人被拘
微博热度:528292
21.五公
微博热度:503330
22.小鬼舞台
微博热度:490289
23.老师别再用全景相机拍照了
微博热度:469149
24.乐队的夏天
微博热度:443785
25.LPL夏季赛
微博热度:408391
26.警方通报铁笼溺水男子生前轨迹
微博热度:373025
27.尹正R1SE热舞
微博热度:372089
28.航空兵双语警告接近台海领空美军机
微博热度:366411
29.福奇否认中国威胁美国疫苗
微博热度:355998
30.农夫山泉获准上市
微博热度:349525
31.张艺兴教王一博跳Krump
微博热度:346622
32.明日之子
微博热度:342896
33.久诚的百里守约
微博热度:326275
34.今年4号台风黑格比
微博热度:320696
35.特朗普将禁止TikTok在美国运营
微博热度:316092
36.蓝盈莹 希怡的眼神杀过来
微博热度:312771
37.香港连续11天单日新增超百例
微博热度:283920
38.高考后扎堆做近视手术
微博热度:279778
39.南京一应届毕业女生失联超21天
微博热度:259311
40.DYG战胜QG
微博热度:248635
41.肖枫三观
微博热度:238216
42.今年十五月亮十四圆
微博热度:203887
43.大连一1个月婴儿确诊
微博热度:198874
44.原来河马在水里是这样的
微博热度:198388
45.阿朵 这才是最奢侈的
微博热度:193072
46.三十而已
微博热度:192158
47.黄晓明脱妆
微博热度:169374
48.OMG iG
微博热度:167920
49.天津暴雨
微博热度:167427
50.武汉灯光秀致敬最可爱的人
微博热度:166504
|
#pragma once
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <node_buffer.h>
#include <uv.h>
using namespace node;
using namespace v8;
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/IRBuilder.h"
#include "llvm/BasicBlock.h"
#include "llvm/Function.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/PassManager.h"
#include "llvm/Support/raw_ostream.h"
#include "protobuilder.h"
typedef llvm::IRBuilder<> IRBuilder; // just so I don't keep forgetting the <>
extern Proto<llvm::LLVMContext> pContext;
extern Proto<llvm::Module> pModule;
extern Proto<llvm::Value> pValue;
extern Proto<llvm::BasicBlock> pBasicBlock;
extern Proto<IRBuilder> pIRBuilder;
extern Proto<llvm::Function> pFunction;
extern Proto<llvm::Type> pType;
extern Proto<llvm::IntegerType> pIntegerType;
extern Proto<llvm::Type> pFPType;
extern Proto<llvm::FunctionType> pFunctionType;
extern Proto<llvm::ExecutionEngine> pExecutionEngine;
extern Proto<llvm::FunctionPassManager> pFunctionPassManager;
extern Proto<llvm::PHINode> pPHINode;
extern Proto<llvm::SwitchInst> pSwitchInst;
// Common constructor for Value and subclasses
Handle<Value> valueConstructor(const Arguments& args);
|
using NMR
using Base.Test
ϵ = 0.001
# Phenyl boronic acid in CDCl3 (300 MHz)
dataset_path = joinpath(@__DIR__, "data", "PhB(OH)2", "1")
# write your own tests here
@testset "Read Bruker" begin
s = Spectrum(dataset_path, 1)
@test s.default_proc == 1
@test length(s) == length(s[1]) == s["SI"] == 32768
@test s["TD"] == 18486
@test typeof(s[:]) == typeof(s[1][:]) <: Array{T,1} where T <: Number
@test limits(s)[1] ≈ -0.4997 atol=ϵ
@test limits(s)[2] ≈ 13.4996 atol=ϵ
@test all( [1.2, 3.5, 7.9, 12.9] .∈ Ref(s) )
@test all( [14.2, 30.9, -2.0, -0.7] .∉ Ref(s) )
end
@testset "Unit conversions" begin
s = Spectrum(dataset_path, 1)
sf = s["SF"]
bf = s["BF1"]
@test NMR.sr(sf, bf) ≈ 0.0
@test -2 < ppmtoindex(s, 6.4502) - 16502 < 2
let rng = ppmtoindex(s, limits(s))
@test 1 ∈ rng
@test s["SI"] - 1 ∈ rng
end
end |
package io.sitoolkit.wt.app.page2script;
import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;
import io.sitoolkit.wt.app.config.BaseConfig;
import io.sitoolkit.wt.app.config.WebDriverConfig;
import io.sitoolkit.wt.domain.pageload.PageContext;
import io.sitoolkit.wt.domain.pageload.PageListener;
import io.sitoolkit.wt.domain.pageload.PageLoader;
import io.sitoolkit.wt.domain.pageload.selenium.AnchorTagLoader;
import io.sitoolkit.wt.domain.pageload.selenium.InputTagLoader;
import io.sitoolkit.wt.domain.pageload.selenium.RadioCheckLoader;
import io.sitoolkit.wt.domain.pageload.selenium.SelectTagLoader;
import io.sitoolkit.wt.domain.pageload.selenium.SeleniumPageLietener;
import io.sitoolkit.wt.domain.pageload.selenium.TextareaTagLoader;
import io.sitoolkit.wt.domain.testscript.TestScriptDao;
import io.sitoolkit.wt.infra.PropertyManager;
@Configuration
@Import({WebDriverConfig.class, BaseConfig.class})
public class Page2ScriptConfig {
@Bean
public Page2Script getTestScriptGenerator(TestScriptDao dao, PageListener listener,
PropertyManager pm, PageLoader... loaders) {
Page2Script page2script = new Page2Script();
page2script.setDao(dao);
page2script.setLoaders(Arrays.asList(loaders));
page2script.setListener(listener);
String projectDir = System.getProperty("sitwt.projectDirectory");
String pageScriptDir = (StringUtils.isEmpty(projectDir)) ? pm.getPageScriptDir()
: projectDir + "/" + pm.getPageScriptDir();
page2script.setOutputDir(pageScriptDir);
page2script.setCli(pm.isCli());
return page2script;
}
@Bean
public RadioCheckLoader getRadioCheckLoader() {
return new RadioCheckLoader();
}
@Bean
public InputTagLoader getInputTagLoader() {
return new InputTagLoader();
}
@Bean
public SelectTagLoader getSelectTagLoader() {
return new SelectTagLoader();
}
@Bean
public AnchorTagLoader getAnchorTagLoader() {
return new AnchorTagLoader();
}
@Bean
public TextareaTagLoader getTextareaTagLoader() {
return new TextareaTagLoader();
}
@Bean
public SeleniumPageLietener getListener() {
return new SeleniumPageLietener();
}
@Bean
@Scope("prototype")
public PageContext getPageContext() {
return new PageContext();
}
}
|
# Single Master with 3-nodes
## Version
```
ElasticSearch: 7.6.1
Kibana: 7.6.1
```
## Run
### Example
|host name|node.name|host ip|master|data|
|:-:|:-:|:-:|:-:|:-:|
|pdk1|es01|10.1.110.1|true|true|
|pdk2|es02|10.1.110.2|false|true|
|pdk3|es03|10.1.110.3|false|true|
please modify the network.publish_host, discovery.seed_hosts in docker-compose.yml to match your host IP
### In pdk1 host
modify docker-compose.yml
```
...
es01:
...
environment:
- network.publish_host=10.1.110.1
...
- discovery.seed_hosts=10.1.110.2,10.1.110.3
...
```
run container es01, kib01
```
$ sudo docker-compose up es01 kib01
```
### In pdk2 host
modify docker-compose.yml
```
...
es02:
...
environment:
- network.publish_host=10.1.110.2
...
- discovery.seed_hosts=10.1.110.1,10.1.110.3
...
```
run container es02
```
$ sudo docker-compose up es02
```
### In pdk3 host
modify docker-compose.yml
```
...
es03:
...
environment:
- network.publish_host=10.1.110.3
...
- discovery.seed_hosts=10.1.110.1,10.1.110.2
...
```
run container es03
```
$ sudo docker-compose up es03
```
|
#!/bin/bash
# LGSM check_config.sh function
# Author: Daniel Gibbs
# Website: http://gameservermanagers.com
lgsm_version="060116"
# Description: If server config missing warn user.
if [ ! -e "${servercfgfullpath}" ]; then
if [ "${gamename}" != "Hurtworld" ]; then
fn_printwarnnl "Config file missing!"
echo "${servercfgfullpath}"
fn_scriptlog "Configuration file missing!"
fn_scriptlog "${servercfgfullpath}"
sleep 2
fi
fi |
(ColName integer, int_start integer, int_stop integer)
RETURNS integer stable AS $$
import random
return random.randint(int_start,int_stop)
$$ LANGUAGE plpythonu; |
/*************************************************************************
* Copyright (C) 2021 by Cambricon, Inc. All rights reserved.
*
* 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.
*************************************************************************/
#ifndef TEST_MLU_OP_GTEST_SRC_GTEST_PERF_TEST_H_
#define TEST_MLU_OP_GTEST_SRC_GTEST_PERF_TEST_H_
#include <libxml/xpath.h>
#include <string>
xmlXPathObjectPtr getNodeSet(xmlDocPtr doc, const xmlChar *xpath);
std::string getTestCaseName(std::string str);
bool getXmlData(std::string case_name, double *xml_time, double *workspace_size);
bool updateBaselineStrategy(double hw_time_mean,
double scale_bound,
double threshold_absolute,
double threshold_relative,
double *hw_time_base);
#endif // TEST_MLU_OP_GTEST_SRC_GTEST_PERF_TEST_H_
|
import 'package:animation_tools/spine/spine_animation_tools.dart';
import 'package:args/args.dart';
void main(List<String> args) async {
final parser = ArgParser();
parser.addOption(
'source',
help: 'Path to animation folder.',
mandatory: true,
);
parser.addOption('copy', help: 'Copy or/and rename animation.');
parser.addOption('scale', help: 'Scale animation.');
parser.addOption('move_animation', help: 'Move animation.');
parser.addOption('remove_animation', help: 'Remove animation.');
parser.addOption('leave_animations', help: 'Leave only animations.');
final results = parser.parse(args);
// source
var sourcePath = '';
if (results.wasParsed('source')) {
sourcePath = results['source'] as String;
}
if (sourcePath.isEmpty) {
throw ArgumentError.value(sourcePath, 'source', 'Should be defined.');
}
final tools = SpineAnimationTools(sourcePath);
await tools.check();
// copy
if (results.wasParsed('copy')) {
var copyPath = results['copy'] as String;
if (copyPath.isEmpty) {
copyPath = sourcePath;
}
await tools.copy(copyPath);
}
// scale
if (results.wasParsed('scale')) {
final s = results['scale'] as String;
final scale = num.parse(s);
await tools.scale(scale);
}
// move_animation
if (results.wasParsed('move_animation')) {
final raw = results['move_animation'] as String;
final list = raw.split(' ');
if (list.length != 2) {
throw ArgumentError.value(
raw,
'move_animation',
'Should be space separated names like `from_name to_name`.',
);
}
await tools.moveAnimation(list.first, list.last);
}
// remove_animation
if (results.wasParsed('remove_animation')) {
final raw = results['remove_animation'] as String;
final list = raw.split(' ');
if (list.length != 1) {
throw ArgumentError.value(
raw,
'remove_animation',
'Should be one name without spaces.',
);
}
await tools.removeAnimation(list.first);
}
// leave_animations
if (results.wasParsed('leave_animations')) {
final raw = results['leave_animations'] as String;
final list = raw.split(' ');
if (list.isEmpty) {
throw ArgumentError.value(
raw,
'leave_animations',
'Should be space separated names.'
' For example: `idle walk run shoot`.',
);
}
await tools.leaveAnimations(list);
}
}
|
package main
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/gabriel-vasile/mimetype"
)
// Define vars for build template
var conv = map[string]interface{}{
"byteArray": byteArray,
"mime": determineMIMEType,
}
var tmpl = template.Must(template.New("").Funcs(conv).Parse(`package internal
// Code generated by go generate; DO NOT EDIT.
func init() {
{{- range $name, $content := . }}
files["{{ $name }}"] = &memfile{
path: "{{ $name }}",
mime: "{{ mime $content }}",
data: {{ byteArray $content }},
}
{{- end }}
}`),
)
func init() {
mimetype.Extend(pijectorCSSDetector, "text/css; charset=utf-8", ".css")
mimetype.Extend(pijectorJSDetector, "application/javascript; charset=utf-8", ".js")
}
func pijectorCSSDetector(raw []byte, limit uint32) bool {
return bytes.HasPrefix(raw, []byte("/** CSS **/"))
}
func pijectorJSDetector(raw []byte, limit uint32) bool {
return bytes.HasPrefix(raw, []byte("/** JS **/"))
}
func determineMIMEType(s []byte) string {
return mimetype.Detect(s).String()
}
func byteArray(s []byte) string {
return fmt.Sprintf("%#v", s)
}
func main() {
args := os.Args[1:]
if len(args) != 2 {
log.Fatal("usage: generator [static dir] [output filename]")
}
staticFileRoot := args[0]
outputFile := args[1]
if _, err := os.Stat(staticFileRoot); os.IsNotExist(err) {
log.Fatalf("configs directory %q does not exist", staticFileRoot)
}
configs := make(map[string][]byte)
if err := filepath.Walk(staticFileRoot, func(path string, info os.FileInfo, err error) error {
relativePath := filepath.ToSlash(strings.TrimPrefix(path, staticFileRoot))
if info.IsDir() {
return nil
} else {
log.Printf("packing %q", path)
b, err := ioutil.ReadFile(path)
if err != nil {
log.Printf("Failed reading %q: %v", path, err)
return err
}
configs[relativePath] = b
}
return nil
}); err != nil {
log.Fatal("Error walking through embed directory:", err)
}
f, err := os.Create(outputFile)
if err != nil {
log.Fatal("Error creating blob file:", err)
}
defer f.Close()
var builder bytes.Buffer
if err = tmpl.Execute(&builder, configs); err != nil {
log.Fatalf("Failed executing template: %v", err)
}
data, err := format.Source(builder.Bytes())
if err != nil {
log.Fatalf("Failed formatting generated code: %v", err)
}
if err = ioutil.WriteFile(outputFile, data, os.ModePerm); err != nil {
log.Fatalf("Failed writing output file: %v", err)
}
}
|
class PlayLeftJoinController < ApplicationController
def index
@left1 = PlayArticle.left_joins(:play_category)
.select(:id, :title, 'play_categories.name as category_name')
@left1_sql = @left1.to_sql
@left2 = PlayArticle.left_joins(:play_authors, :play_accesses)
.select(:id, :title, :name, :value)
@left2_sql = @left2.to_sql
@left3 = PlayArticle.left_joins(:play_category, :play_accesses)
.select(:id, :title, :name, :value)
@left3_sql = @left3.to_sql
end
end
|
# Transformed data
This directory contains transformed versions of municipality-level Rhode Island
overdose data and population estimates. It includes:
- `incidents.csv`: 2018 accidental overdose deaths by municipality
- `populations.csv`: 2018 municipality populations
- `incident_rates.csv`: Event rates, posterior intervals, and sorting scores
|
-module(fns).
-import(lists,[foldl/3,map/2,filter/2]).
-export([doubleAll/1,evens/1,product/1,zip/2,zip_with/3]).
doubleAll(Xs) ->
map(fun(E) -> E * 2 end, Xs).
evens(Xs) ->
filter(fun(E) -> E rem 2 == 0 end, Xs).
product(Xs) ->
foldl(fun erlang:'*'/2, 1 , Xs).
%%
zip_with(Fn, [X|Xs],[Y|Ys]) ->
[Fn(X,Y) | zip_with(Fn, Xs, Ys)];
zip_with(_, _, _) ->
[].
zip(Xs,Ys) ->
zip_with(fun(A,B) -> {A,B} end, Xs, Ys).
|
gpg \
--local-user "${PARAM_KEYPAIR_EMAIL}" \
--armor \
--output /tmp/generated_signature.pgp \
--sign "${PARAM_PAYLOAD_FILEPATH}"
echo "Success! Attestation payload signed" |
script_loc=`cd $(dirname $0) && pwd -P`
. $script_loc/common.sh
START=$PWD
PATH=$NEW_PATH:$PATH
cd $GNATCOLL_DB_SRC
make -w -C sql setup prefix=$PREFIX
make -w -C sql clean build GPRBUILD_OPTIONS="--db $script_loc/config"
make -w -C sql install
make -w -C sqlite setup prefix=$PREFIX
make -w -C sqlite clean build GPRBUILD_OPTIONS="--db $script_loc/config"
make -w -C sqlite install
make -w -C xref setup prefix=$PREFIX
make -w -C xref GPRBUILD_OPTIONS="--db $script_loc/config"
make -w -C xref install
make -w -C gnatinspect setup prefix=$PREFIX
make -w -C gnatinspect clean build GPRBUILD_OPTIONS="--db $script_loc/config"
make -w -C gnatinspect install
make -w -C gnatcoll_db2ada setup prefix=$PREFIX DB_BACKEND=sqlite
make -w -C gnatcoll_db2ada clean build GPRBUILD_OPTIONS="--db $script_loc/config"
make -w -C gnatcoll_db2ada install
|
package ssp
import (
"context"
sqrl "github.com/RaniSputnik/sqrl-go"
)
type TransactionStore interface {
// GetFirstTransaction returns the transaction that started an exchange between
// a SQRL client and SSP server. If no error or transaction is returned then
// the current transaction is the first transaction in the exchange.
GetFirstTransaction(ctx context.Context, nut sqrl.Nut) (*sqrl.Transaction, error)
// SaveTransaction stores a verified transaction in the DB.
SaveTransaction(ctx context.Context, t *sqrl.Transaction) error
// SaveIdentSuccess stores a successful ident query from a client. The token
// that will be returned to the client is stored to allow for retrieval
// (for the pag.sqrl endpoint).
SaveIdentSuccess(ctx context.Context, nut sqrl.Nut, token Token) error
// GetIdentSuccess returns a previously saved token for a given transaction nut
// if such a token exists. An empty string will be returned if the given nut
// has not yet been saved as successful.
GetIdentSuccess(ctx context.Context, nut sqrl.Nut) (token Token, err error)
}
type UserStore interface {
CreateUser(ctx context.Context, idk sqrl.Identity) (*User, error)
// GetByIdentity returns a user from the given identity key.
// If no user is found, a nil user will be returned with no error.
// TODO: Clarify exactly when a user should be saved
// is it after a successful query? Or after successful ident?
// see: https://github.com/RaniSputnik/sqrl-go/issues/25
GetUserByIdentity(ctx context.Context, idk sqrl.Identity) (*User, error)
// TODO: Get by previous identities
}
type User struct {
Id string
Idk sqrl.Identity
// TODO: Do we need to store previous identity keys?
}
type Store interface {
TransactionStore
UserStore
}
|
<?php
/**
* @file
* This file is part of the PdfParser library.
*
* @author Sébastien MALOT <[email protected]>
* @date 2017-01-03
*
* @license LGPLv3
* @url <https://github.com/smalot/pdfparser>
*
* PdfParser is a pdf library written in PHP, extraction oriented.
* Copyright (C) 2017 - Sébastien MALOT <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program.
* If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
*/
// Source : http://www.opensource.apple.com/source/vim/vim-34/vim/runtime/print/mac-roman.ps
namespace Smalot\PdfParser\Encoding;
/**
* Class MacRomanEncoding
*/
class MacRomanEncoding extends AbstractEncoding
{
public function getTranslations(): array
{
$encoding =
'.notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef '.
'.notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef '.
'.notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef '.
'.notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef '.
'space exclam quotedbl numbersign dollar percent ampersand quotesingle '.
'parenleft parenright asterisk plus comma minus period slash '.
'zero one two three four five six seven '.
'eight nine colon semicolon less equal greater question '.
'at A B C D E F G '.
'H I J K L M N O '.
'P Q R S T U V W '.
'X Y Z bracketleft backslash bracketright asciicircum underscore '.
'grave a b c d e f g '.
'h i j k l m n o '.
'p q r s t u v w '.
'x y z braceleft bar braceright asciitilde .notdef '.
'Adieresis Aring Ccedilla Eacute Ntilde Odieresis Udieresis aacute '.
'agrave acircumflex adieresis atilde aring ccedilla eacute egrave '.
'ecircumflex edieresis iacute igrave icircumflex idieresis ntilde oacute '.
'ograve ocircumflex odieresis otilde uacute ugrave ucircumflex udieresis '.
'dagger degree cent sterling section bullet paragraph germandbls '.
'registered copyright trademark acute dieresis notequal AE Oslash '.
'infinity plusminus lessequal greaterequal yen mu partialdiff summation '.
'Pi pi integral ordfeminine ordmasculine Omega ae oslash '.
'questiondown exclamdown logicalnot radical florin approxequal delta guillemotleft '.
'guillemotright ellipsis space Agrave Atilde Otilde OE oe '.
'endash emdash quotedblleft quotedblright quoteleft quoteright divide lozenge '.
'ydieresis Ydieresis fraction currency guilsinglleft guilsinglright fi fl '.
'daggerdbl periodcentered quotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute '.
'Edieresis Egrave Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex '.
'heart Ograve Uacute Ucircumflex Ugrave dotlessi circumflex tilde '.
'macron breve dotaccent ring cedilla hungarumlaut ogonek caron';
return explode(' ', $encoding);
}
}
|
---
title: "Weekly Planner Template"
---
<div class="pdf-container">
<iframe src="/assets/docs/matts_weekly_planner.pdf" height="315" width="560" allowfullscreen="" frameborder="10">
</iframe>
</div> |
require 'simplecov'
SimpleCov.start do
filters.clear # This will remove the :root_filter that comes via simplecov's defaults
add_filter do |src|
!(src.filename =~ /^#{SimpleCov.root}\/lib\/lurker/)
end
end
def example_path
if rails_version = ENV['BUNDLE_GEMFILE'].to_s.match(/rails_\d\d/)
File.expand_path("../../../tmp/lurker_app_#{rails_version}", __FILE__)
else
raise "Use `appraisal rails-XY cucumber ...` or export BUNDLE_GEMFILE=gemfiles/... explicitly"
end
end
require 'fileutils'
require 'aruba/cucumber'
require 'rspec/expectations'
World(RSpec::Matchers)
require 'capybara'
require 'capybara/dsl'
require 'capybara/cucumber'
require 'capybara/poltergeist'
require "#{example_path}/config/environment"
require 'database_cleaner'
require 'database_cleaner/cucumber'
Capybara.app = Rails.application
Capybara.javascript_driver = :poltergeist
DatabaseCleaner.strategy = :truncation
# see: https://github.com/colszowka/simplecov/issues/234
Aruba.configure do |config|
config.before_cmd do |cmd|
set_env 'SIMPLECOV_CMDNAME', Digest::MD5.hexdigest(cmd)
set_env 'SIMPLECOV_ROOT', File.expand_path('../../..', __FILE__)
end
end
Before do
@dirs = [example_path]
@aruba_timeout_seconds = 30
DatabaseCleaner.start
if ENV['CLEAN']
system "bin/spring stop"
%w[lurker html public/lurker spec/requests spec/controllers].each do |dir_name|
in_current_dir { _rm_rf(dir_name) }
end
end
end
After do |scenario|
ActiveRecord::Base.connection.reconnect!
DatabaseCleaner.clean
end
After('@selenium') do |scenario|
save_and_open_page if scenario.failed? && !ENV['BUNDLE_GEMFILE'].match(/Gemfile\.ci/)
end
|
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Connection } from 'typeorm';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: {
credentials: true,
},
});
await app.get(Connection).query(`
CREATE TABLE IF NOT EXISTS logs (
date timestamp default now() NOT NULL,
info varchar NOT NULL
);
DROP TRIGGER IF EXISTS on_add_user on user_entity;
DROP FUNCTION IF EXISTS log_user();
CREATE FUNCTION log_user() RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO logs (date, info) VALUES (DEFAULT, CONCAT('Created user ', new.email));
RETURN new;
END
$$;
CREATE TRIGGER on_add_user
AFTER INSERT ON user_entity
FOR EACH ROW
EXECUTE PROCEDURE log_user();
DROP TRIGGER IF EXISTS on_add_security on security_entity;
DROP FUNCTION IF EXISTS log_security();
CREATE FUNCTION log_security() RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO logs (date, info) VALUES (DEFAULT, CONCAT('Created security ', new."fullName"));
RETURN new;
END
$$;
CREATE TRIGGER on_add_security
AFTER INSERT ON security_entity
FOR EACH ROW
EXECUTE PROCEDURE log_security();
`);
app.useGlobalPipes(new ValidationPipe());
const options = new DocumentBuilder()
.setTitle('Exchange API')
.setSchemes('https', 'http')
.setVersion('0.1')
.addBearerAuth('Authorization', 'header')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api/docs', app, document);
await app.listen(process.env.PORT || 3000);
}
bootstrap();
|
using CSV, StatsBase
jp(csv) = joinpath(@__DIR__, csv)
datasets = Dict(
:toy1 => (jp("./data/toy/toy1.csv"), 90, :Y),
:toy2 => (jp("./data/toy/toy2.csv"), 90, :Y),
:wine => (jp("./data/wine/wine5K_f32.csv"), 3600, :quality),
:garnet => (jp("./data/garnet/garnet_norm_f32.csv"), 9000, :TiO2),
)
type RealData{T}
X::AbstractMatrix{T}
signal::AbstractVector{T}
noise::AbstractVector{T}
y::AbstractVector{T}
n::Int
end
RealData(X, y) = RealData(X, y, y*0, y, length(y))
loadrealdata(datasetname::Symbol) = loadrealdata(datasets[datasetname]...)
function loadrealdata(csvfilename::String, ntrain::Int, yname::Symbol)
data = CSV.read(csvfilename)
disallowmissing!(data)
ntotal = nrow(data)
srand(20181103)
testindices = sample(1:ntotal, ntotal-ntrain, replace=false)
trainindices = trues(ntotal)
trainindices[testindices] = false
test = data[testindices, :]
train = data[trainindices, :]
xnames = [name for name in names(data) if name != yname]
trainx = Matrix(train[:, xnames])
trainy = Vector(train[yname])
testx = Matrix(test[:, xnames])
testy = Vector(test[yname])
RealData(trainx, trainy), RealData(testx, testy)
end
|
package Perl::Gib::Util;
##! #[ignore(item)]
##! Perl::Gib internal utilities.
use strict;
use warnings;
use Carp qw(croak);
use Module::Runtime 0.016 qw(use_package_optimistically);
use Readonly;
use Exporter qw(import);
Readonly::Array our @EXPORT_OK => qw(
throw_exception
);
Readonly::Hash our %EXPORT_TAGS => ( all => [@EXPORT_OK], );
### Throw given exception class including optional arguments.
sub throw_exception {
my ($class_name, @args_to_exception) = @_;
my $class = "Perl::Gib::Exception::$class_name";
&use_package_optimistically( $class);
croak($class->new( @args_to_exception ));
}
1;
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <vector>
#include <iomanip>
using namespace std;
const int s = 2; //aantal sleetjes
const int p = 3; //rendieren per slee
const int d = 10; //aantal dagen
const int ptot = s*p; //totaal aantal rendieren
int main(){
//init
srand (time(NULL));
stack<int> nietToegekend; //houdt bij welke dieren nog niet toegekent zijn
int plaatsen[s];//plaatsen[sleenr] geeft aantal beschikbare plaatsen dat nog vrij is voor die slee
int sleeNr[ptot]; //sleeNr[rendiernr] geeft het nummer van de slee waartoe het rendier behoord. -> niet perce nodig
vector<vector<int> > dierenPerSlee(s);//geeft per slee nr een lijst van rendieren weer
int dagenbijelkaar[ptot][ptot];
for (int i =0; i < ptot ; i++){
for (int j = 0 ; j < ptot ; j++){
dagenbijelkaar[i][j] =0;
}
}
for (int dag = 0 ; dag < d ; dag++){
//setup
for (int i = 0 ; i < ptot ; i++)
nietToegekend.push(i);
for (int i = 0 ; i < s ; i++){
plaatsen[i] = p;
dierenPerSlee[i].clear();
}
//random bij elkaar gooien
while (!nietToegekend.empty()){
int rendier = nietToegekend.top();
nietToegekend.pop(); //van stack smijten
int slee = rand() % s;
while (plaatsen[slee] == 0){ //indien de slee al vol zit
slee = rand() %s;
}
dierenPerSlee[slee].push_back(rendier);
sleeNr[rendier] = slee;
plaatsen[slee]--;
}
//uitschrijven
cout << "------------- dag " << dag << " -------------" << endl;
for (int i = 0 ; i < s ; i ++){
cout << "slee: " << i << ": \t";
//uitschrijven
for (int j =0 ; j < p ; j++){
cout << setw(3) << dierenPerSlee[i][j] << " ";
dagenbijelkaar[dierenPerSlee[i][j]][dierenPerSlee[i][(j+1)%p]]++;
dagenbijelkaar[dierenPerSlee[i][(j+1)%p]][dierenPerSlee[i][j]]++;
}
cout << endl;
}
}
//dagenbijelkaar geven & stat berekenen
double gemiddelde;
int max = 0;
cout << endl << endl;
cout << "------------- dagen bij elkaar -------------" << endl;
cout << "dier: |";
for (int i = 0 ; i < ptot ; i++){
cout << setw(2) << i+1 << " | ";
}
cout << endl;
for (int i = 0 ; i < ptot ; i++){
cout << setw(5) << i+1 << " |";
for (int j = 0 ; j < ptot ; j++){
cout << setw(2) << dagenbijelkaar[i][j] << " | ";
//stat
if (dagenbijelkaar[i][j] > max){
max = dagenbijelkaar[i][j];
}
gemiddelde += dagenbijelkaar[i][j];
}
cout << endl;
}
gemiddelde /= (ptot*ptot)-ptot;
cout << "Max dagen bij elkaar = " << max << endl;
cout << "gemiddeld aantal dagen bij elkaar " << gemiddelde << endl;
} |
<?php
namespace Jaf;
/**
* 路由接口定义
* 路由匹配是 Jaf 应用运行的第一步
* 路由配置由用户定义,路由类被 Jaf 内部调用,因此 Jaf 路由是 Jaf内部自维护的,接口变更与无关应用层
* Jaf 路由的目的是生成请求体,所以被设计为static方法调用,Jaf路由实际上是对函数进行类包装
*/
interface Route_Interface {
/**
* 路由匹配
* @param String $match 路由定义中的key
* @param array $mca 包含 module,controller,action的路由定义
* @param array $pathinfo 经由 Jaf::pathInfo 对 URI 进行的 pathinfo 分析
* @param array $params 客户端传入的参数
* @return Request_Model 匹配成功返回 Request_Model 实例,包含 module,controller,action,params (mcap)信息
*/
public static function match ( $match, array $mca,array $pathinfo,array $params );
} |
#!/bin/bash -x
# configuration
user=webiopi # login username
pass=raspberry # login password
ipadr=raspberrypi.local # webiopi server ip address
port=8000 # webiopi server port number
ch=0 # PWM Ch# [0 or 1]
# Ch#0: GPIO 12 or 18
# Ch#1: GPIO 13 or 19
pin=18 # hardware-PWM-enabled GPIO port number
# set clock source
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/clock
# [osc, plla, pllc, plld, or pllh]
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/clock/osc
# set frequency
# valid frequency ranges:
# ----------------------------------------
# min max
# ----------------------------------------
# osc 4,688 through 19,200,000 Hz
# plla 158,730 through 650,000,000 Hz
# pllc 48,840 through 200,000,000 Hz
# plld 122,100 through 500,000,000 Hz
# pllh 52,747 through 216,000,000 Hz
# ----------------------------------------
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/freq
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/freq/40000
# set M/S mode [optional]
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/msmode
# 0: PWM mode
# 1: M/S mode
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/msmode/1
# set polarity [optional]
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/polarity
# 0: normal
# 1: reverse
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/polarity/0
# set GPIO port
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/port
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/port/$pin
# set period
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/period
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/period/1024
# set duty
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/duty
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/duty/1
# set output to enable
curl -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/output
# enable or disable
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/output/enable
# set duty
for ((i=0; i<1024; i+=16)); do
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/duty/$i
done
# set output to disable
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/output/disable
sleep 3
# set output to enable
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/output/enable
# set frequency
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/freq/50000
sleep 3
# set output to disable
curl -X POST -u $user:$pass http://$ipadr:$port/GPIO/$ch/hwpwm/output/disable
|
package tech.kzen.auto.client.objects.document.script.step.display
import tech.kzen.auto.client.service.global.SessionState
import tech.kzen.auto.common.paradigm.imperative.model.ImperativeModel
import tech.kzen.lib.common.model.attribute.AttributeNesting
import tech.kzen.lib.common.model.locate.ObjectLocation
open class StepDisplayProps(
var common: Common
): react.Props {
data class Common(
var clientState: SessionState,
// var graphStructure: GraphStructure,
var objectLocation: ObjectLocation,
var attributeNesting: AttributeNesting,
var imperativeModel: ImperativeModel,
var managed: Boolean = false,
var first: Boolean = false,
var last: Boolean = false/*,
var active: Boolean = false*/
) {
fun isRunning(): Boolean {
return objectLocation == imperativeModel.running
}
fun isActive(): Boolean {
return clientState.activeHost != null &&
imperativeModel.frames.any { it.path == clientState.navigationRoute.documentPath }
}
// fun graphStructure(): GraphStructure {
// return clientState.graphDefinitionAttempt.successful.graphStructure
// }
}
} |
-- fktree.sql
-- prototype SQL
-- find the tree of tables linked by FK
-- get the constraint names so we know how to find the columns
-- to use when looking for orphaned rows, and disparities in rows
-- between the same tables on separate servers
@clears
-- example: call with @fktree SCHEMA TABLE_NAME
@@get-schema-name &1
@@get-table-name &2
col table_name format a30
col constraint_name format a30
col r_constraint_name format a30
set linesize 200 trimspool on
set pagesize 100
with fks as (
select c1.table_name
, c1.constraint_name
, c2.r_constraint_name
from dba_constraints c1
left join dba_constraints c2
on (
c2.owner = c1.owner
and c2.table_name = c1.table_name
and c2.constraint_type='R'
)
and c1.constraint_type in ('U','P')
where c1.owner = '&schema_name'
and c2.r_constraint_name is not null
),
pks as (
select c1.table_name, c1.constraint_name, null r_constraint_name
from dba_constraints c1
where c1.constraint_name in (
select r_constraint_name
from fks
)
and c1.owner = '&schema_name'
),
all_data as (
select
table_name
, constraint_name
, r_constraint_name
from fks
union
select
table_name
, constraint_name
, r_constraint_name
from pks
)
select distinct
lpad(' ', 2 * (level - 1))|| table_name table_name
, constraint_name
, r_constraint_name
, level
from all_data
start with table_name = '&u_table_name'
connect by nocycle prior constraint_name = r_constraint_name
and level <=5
--order by level
/
undef 1 2
|
from functools import reduce
sample_input = ['+1', '-2', '+3', '+1']
def to_change(change):
if change[0] == '-':
return lambda x: x - int(change[1:])
else:
return lambda x: x + int(change[1:])
def get_frequency(changes):
return reduce(lambda acc, x: to_change(x)(acc), changes, 0)
assert get_frequency(sample_input) == 3
# solution one
with open('input') as f:
input = f.readlines()
print(get_frequency(input))
# solution two
def frequency_generator(values):
i = 0
while True:
yield values[i]
i += 1
if i >= len(values):
i = 0
gathered_frequencies = set()
current_freq = 0
gen = frequency_generator(input)
while current_freq not in gathered_frequencies:
gathered_frequencies.add(current_freq)
current_freq = to_change(next(gen))(current_freq)
print(current_freq)
|
using System;
using BookingsApi.Domain.Participants;
using BookingsApi.Infrastructure.Services.Dtos;
namespace BookingsApi.Infrastructure.Services.IntegrationEvents.Events
{
public class ParticipantUpdatedIntegrationEvent: IIntegrationEvent
{
public ParticipantUpdatedIntegrationEvent(Guid hearingId, Participant participant)
{
if (participant == null) return;
HearingId = hearingId;
Participant = ParticipantDtoMapper.MapToDto(participant);
}
public Guid HearingId { get; }
public ParticipantDto Participant { get; }
}
} |
package ta.aws.lambda.acme
import fm.common.{Enum, EnumEntry}
object ACMELambdaRequest {
sealed trait Action extends EnumEntry
object Action extends Enum[Action] {
val values: IndexedSeq[Action] = findValues
}
case object HTTPChallenge extends Action
case object GetCertificate extends Action
case object GetWildCardCertificate extends Action
case object ListCertificates extends Action
}
trait ACMELambdaRequest {
def action: ACMELambdaRequest.Action
}
|
import json
import os
import re
def handler(request, context):
command = 'compgen -c'
result = os.popen(command).read()
result = re.split('\n', result)
result.sort()
obj = { "cmds": result }
return obj
|
<?php
if (file_exists('install.lock')) {
die('Nightsparrow je već instaliran. Ako niste instalirali Nightsparrow, konzultirajte se s dokumentacijom.');
}
require_once '../inc/install.php';
$install = new Installer();
/** Nightsparrow instalacija **/
$dir = dirname(__FILE__); // koja je putanja do foldera
$dir = str_replace('install', '', $dir); // izbacimo install do foldera
$dir = addslashes($dir); // jer Windows postoji, svima nama na žalost
if (($_SERVER['HTTPS'] == null) || ($_SERVER['HTTPS'] == 'off')) {
$protocol = 'http://';
} else {
$protocol = 'https://';
}
$domain = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$domain = str_replace('install/index.php', '', $domain); // koja nam je domena i putanja do instalacije?
$configfile = file_get_contents('../config.php.new'); // učitajmo predložak za instalaciju
$configfile = str_replace('@@nightsparrow-directory@@', $dir, $configfile); // zamjena placeholdera
$configfile = str_replace('@@nightsparrow-domain-path@@', $domain, $configfile); // zamjena placeholdera
$fpcres = file_put_contents('../config.php', $configfile);
if ($fpcres == false) {
$install->chmod_error($configfile, 'config.php', 'step2.php'); // spremi vrijednost ili prikaži grešku
die();
}
if (version_compare(PHP_VERSION, '5.6.0') < 0) { // provjerava verziju PHP-a za kompatibilnost
include '../template/install/fail_header.php';
include '../template/install/phpversion_fail.php';
include '../template/install/footer.php';
die();
}
if (ini_get('sql.safe_mode') == 'On') { // ovo ne smije biti uključeno
include '../template/install/fail_header.php';
include '../template/install/sqlsafemode_fail.php';
include '../template/install/footer.php';
die();
} else { // sve kompatibilno! krenimo s instalacijom :)
include '../template/install/header.php';
include '../template/install/hello.php';
include '../template/install/footer.php';
} |
---
layout: post
title: "Java的一些特性与机制"
subtitle: "RMI JMS"
date: 2016-03-13
author: "brucechen"
header-img: "img/post-bg-java.jpg"
published: false
tags:
- Java
- 读书笔记
---
### RMI
Java RMI指的是远程方法调用(Remote Method Invocation)。可以让某个虚拟机上的对象调用另一个虚拟机中的对象方法。下面是一个简单的RMI应用。
```
//定义一个远程接口,必须继承Remote接口,需要远程调用的方法必须抛出RemoteException
public interface IHello extends Remote{
public String helloWorld() throws RemoteException;
public String sayHello(string name) throws RemoteException;
}
```
实现被调用方的远程接口
```
public class HelloImpl extends UnicastRemoteObjects implements IHello{
public HelloImpl() throws RemoteException{}
public String helloWorld() throws RemoteException{
return "Hello World";
}
public String sayHello(String name) throws RemoteException{
return "hello"+name;
}
}
```
被调用方需要创建RMI注册表,启动RMI服务,并将远程对象注册到RMI注册表中,这样才可以被正确调用。
```
public class HelloServer{
public static main(String[] args){
try{
IHello rhello = new HelloImpl();
LocateRegistry.createRegistry(8888);//创建注册表实例并指定端口
Naming.rebind("rmi://localhost:8888/RHello",rhello);//远程对象注册到RMI注册服务器上
}catch(RemoteException){
System.out.println("创建远程对象发生异常!");
e.printStackTrace();
}catch (AlreadyBoundException e) {
System.out.println("发生重复绑定对象异常!");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("发生URL畸形异常!");
e.printStackTrace();
}
}
}
```
至此,RMI服务器构建完成,下面进行客户端测试。
```
public class HelloInvocation{
public static void main(String[] args){
try{
IHello rHello = (IHello)Naming.lookup("rmi://localhost:8888/RHello");
System.out.println(rhello.helloWorld());
System.out.println(rhello.sayHelloToSomeBody("Chen"));
}catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
```
### JMS
JMS,即Java Message Service,是Java平台中关于面向消息中间件的API,用于两个程序之间、或分布式系统中发送消息,进行异步通信。
JMS由以下元素组成:
* JMS提供者,JMS接口的具体实现
* JMS客户,生成或消费基于消息的Java应用程序或对象
* JMS生产者,创建并发送消息的JMS客户
* JMS消费者,接收消息的JMS客户
* JMS消息,JMS客户之间传递数据的对象
* JMS队列,一个容纳被发送等待阅读的消息区域
* JMS主题,一种支持发送消息给多个订阅者的机制
### RPC
|
package org.acmvit.gitpositive
import android.content.Intent
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.View
import android.text.Html
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.textfield.TextInputLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
import org.acmvit.gitpositive.databinding.ActivityHomeScreenBinding
@AndroidEntryPoint
class HomeScreen : AppCompatActivity() {
var vibrator: Vibrator? = null
private val viewModel: HomeViewModel by viewModels()
private var _binding: ActivityHomeScreenBinding? = null
private val binding: ActivityHomeScreenBinding
get() {
return _binding!!
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityHomeScreenBinding.inflate(layoutInflater)
setContentView(binding.root)
observeViewModel()
binding.Appname.text = Html.fromHtml(
getColorStr("Git", "#6CFF54") + getColorStr(
"Positive",
getColor(R.color.text_color).toString()
)
)
binding.floatingActionButton.setOnClickListener {
doVibration()
if (binding.username.text.toString().isNotEmpty()) {
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("Username", binding.username.text?.toString())
startActivity(intent)
} else {
Toast.makeText(applicationContext, "Username cannot be empty!!", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun observeViewModel() {
viewModel.userList.observe(this) {
it?.let { usersList ->
val adapter: ArrayAdapter<String> = ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, usersList
)
binding.username.setAdapter(adapter)
}
}
}
private fun doVibration() {
vibrator = this.getSystemService(VIBRATOR_SERVICE) as Vibrator
vibrator!!.vibrate(
VibrationEffect.createOneShot(
50,
VibrationEffect.EFFECT_TICK
)
)
}
override fun onResume() {
super.onResume()
val noInternet = findViewById<ConstraintLayout>(R.id.noInternet)
val fab = findViewById<FloatingActionButton>(R.id.floatingActionButton)
val textBox = findViewById<TextInputLayout>(R.id.textInputLayout)
val networkConnection = NetworkConnection(applicationContext)
networkConnection.observe(this, Observer { isConnected->
if(isConnected){
noInternet.visibility = View.GONE
fab.visibility = View.VISIBLE
textBox.visibility = View.VISIBLE
} else {
Toast.makeText(applicationContext, "Internet is not connected", Toast.LENGTH_SHORT).show()
noInternet.visibility = View.VISIBLE
fab.visibility = View.GONE
textBox.visibility = View.GONE
}
})
}
}
fun getColorStr(text: String, color: String): String = "<font color=$color>$text</font>" |
class Evaluator
def self.evaluate_tree(tree, lexicon)
unless tree.empty?
operator, list = Lucio.behead tree
if operator.is_symbol? || operator.is_array?
operator = evaluate_tree(operator, lexicon) if operator.is_array?
instruction = (operator.is_hash?) ? operator : lexicon.get(operator)
if instruction
if instruction[:type] == :function
list.map! {|item| (item.is_array?) ? item = evaluate_tree(item, lexicon) : item}
list.map! do |item|
if item.is_symbol?
op = lexicon.get item
unbound item if op.nil?
item = op[:code].call lexicon, []
else
item
end
end
result = instruction[:code].call lexicon, list
result.is_hash? && result[:type] == :function ? result[:code].call(lexicon, list) : result
elsif instruction[:type] == :macro
result = instruction[:code].call lexicon, list
# result.is_array? ? evaluate_tree(result, lexicon) : result
end
else
unbound operator
end
else
operator
end
end
end
private
def self.unbound symbol
raise UnboundSymbolException.new("Unbound symbol: #{symbol.to_s}")
end
end
|
import React from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import Glitch from "./Glitch";
class PortfolioListItem extends React.Component {
render() {
const { assetUrl, id } = this.props;
return (
<div
className="portfolio__list-item"
>
<div
className="portfolio__list-item__content"
>
<div
className="portfolio__list-item__content__media"
>
<Link
to={`/work/${id}`}
>
<Glitch
src={`https:${assetUrl}`}
/>
</Link>
</div>
</div>
</div>
);
}
}
PortfolioListItem.defaultProps = {
assetUrl: '',
id: '',
title: ''
}
PortfolioListItem.propTypes = {
assetUrl: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired
}
export default PortfolioListItem;
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
let _user_info;
Office.initialize = function(reason)
{
on_initialization_complete();
}
function on_initialization_complete()
{
$(document).ready
(
function()
{
lazy_init_user_info();
populate_templates();
show_signature_settings();
}
);
}
function lazy_init_user_info()
{
if (!_user_info)
{
let user_info_str = localStorage.getItem('user_info');
if (user_info_str)
{
_user_info = JSON.parse(user_info_str);
}
else
{
console.log("Unable to retrieve 'user_info' from localStorage.");
}
}
}
function populate_templates()
{
populate_template_A();
populate_template_B();
populate_template_C();
}
function populate_template_A()
{
let str = get_template_A_str(_user_info);
$("#box_1").html(str);
}
function populate_template_B()
{
let str = get_template_B_str(_user_info);
$("#box_2").html(str);
}
function populate_template_C()
{
let str = get_template_C_str(_user_info);
$("#box_3").html(str);
}
function show_signature_settings()
{
let val = Office.context.roamingSettings.get("newMail");
if (val)
{
$("#new_mail").val(val);
}
val = Office.context.roamingSettings.get("reply");
if (val)
{
$("#reply").val(val);
}
val = Office.context.roamingSettings.get("forward");
if (val)
{
$("#forward").val(val);
}
val = Office.context.roamingSettings.get("override_olk_signature");
if (val != null)
{
$("#checkbox_sig").prop('checked', val);
}
} |
package izumi.distage.docker
object DockerConst {
object Labels {
final val reuseLabel = "distage.reuse"
final val containerTypeLabel = "distage.type"
final val jvmRunId = "distage.jvmrun"
final val distageRunId = "distage.run"
final val namePrefixLabel = "distage.name.prefix"
final val portPrefix = "distage.port"
final val networkDriverPrefix = "distage.driver"
}
object State {
final val running = "running"
final val exited = "exited"
}
object Vars {
final val portPrefix = "DISTAGE_PORT"
}
}
|
%% -*- mode: nitrogen -*-
-module(register).
-include_lib("nitrogen_core/include/wf.hrl").
-include("schema.hrl").
-export([
main/0,
nav/0,
title/0,
body/0,
event/1]).
%% main() -> #template { file="./site/templates/base.html" }.
main() -> #template { file="./priv/templates/base.html" }.
nav() ->
#panel {class=nav_panel,
body=[
#link {text="about", postback=about}
]}.
title() -> "register".
body() ->
wf:wire(submit, username,
#validate {validators=[
#is_required { text="Required."},
#custom{text="Unavailable", tag=ignored_tag,
function=fun is_username_available/2},
#custom{text="Invalid", tag=ignored_tag,
function=fun is_name_valid/2}]}),
wf:wire(submit, password,
#validate {validators=[
#is_required {text="Required."},
#custom{text="Too weak", tag=ignored_tag,
function=fun is_password_strong/2}]}),
wf:wire(submit, email,
#validate {validators=[
#is_required {text="Required."}]}),
wf:wire(submit, confirm,
#validate {validators=[
#is_required {text="Required."},
#confirm_password {password=password,
text="Passwords must match."}]}),
[
#panel {class=main_panel, body=[
#panel {body=[
#label {text="username/subdomain"},
#textbox {id=username, next=email},
#span {text="."},
#dropdown {id=base_domain, options=[
#option {text=D#domain.name, value=D#domain.name} ||
D <- db:get_base_domains()]}]},
#p{},
#label {text="default email"},
#textbox {id=email, next=password},
#p{},
#label {text="password"},
#password {id=password, next=confirm},
#p{},
#label {text="confirm"},
#password {id=confirm, next=register},
#p{},
#button {id=submit, text="register", postback=register}
]}
].
register(Username, Password, Email, BaseDomain) ->
%?PRINT({Username, Password, Email, BaseDomain}),
{id, User_id} = db:create_user(Username, Password, Email),
DomainName = Username ++ "." ++ BaseDomain,
{id, Domain_id} = db:create_domain(DomainName, User_id),
{id, _Alias_id} = db:create_alias("example.com@" ++ DomainName, Email, Domain_id,
"sample alias - click here to edit"),
{User_id, Domain_id}.
event(about) ->
wf:redirect("/index");
event(register) ->
case register(wf:q(username), wf:q(password), wf:q(email), wf:q(base_domain)) of
{_User_id, _Domain_id} ->
%?PRINT({"redirect to login"}),
wf:redirect("/login");
_ ->
%?PRINT({"flash error"}),
wf:flash("Registration error - please try again")
end,
ok;
event(_) -> ok.
is_username_available(_Tag, Name) ->
Domain = Name ++ "." ++ wf:q(base_domain),
db:is_username_available(Name) and db:is_domain_available(Domain).
is_name_valid(_Tag, Name) ->
rfc:is_valid_domain_label(Name).
is_password_strong(_Tag, Password) ->
length(Password) >= 6. % fixme
|
package docs
import org.specs2.mutable.Specification
import cc.spray.testkit.Specs2RouteTest
import cc.spray.routing.HttpService
import akka.actor.Actor
class RejectionHandlerExamplesSpec extends Specification with Specs2RouteTest with HttpService {
implicit def actorRefFactory = system
//# example-1
import cc.spray.routing.RejectionHandler
import cc.spray.routing.MissingCookieRejection
import cc.spray.http.HttpResponse
import cc.spray.http.StatusCodes._
implicit val myRejectionHandler = RejectionHandler.fromPF {
case MissingCookieRejection(cookieName) :: _ =>
HttpResponse(BadRequest, "No cookies, no service!!!")
}
class MyService extends Actor with HttpService {
def actorRefFactory = context
def receive = runRoute {
`<my-route-definition>`
}
}
//#
def `<my-route-definition>`: cc.spray.routing.Route = null
"example" in {
Get() ~> sealRoute(reject(MissingCookieRejection("abc"))) ~> check {
entityAs[String] === "No cookies, no service!!!"
}
}
}
|
import { createFundedGeneral } from './create_account'
import { createAndApproveAsset } from './create_asset'
import { assetPairHelper, keyValueHelper } from '../helpers'
import { logger } from '../logger'
import { Asset } from '../helpers/asset'
import { createOfferRequest } from './create_sale_offer'
import { ASSET_PAIR_POLICIES, KEY_VALUE_KEYS } from '../../src/const'
export async function createAndPopulateOrderBookWithRequests () {
const log = logger.new('populateExchange')
const baseAssetCode = Asset.randomCode('BASE')
const quoteAssetCode = Asset.randomCode('QUOTE')
await Promise.all([
createAndApproveAsset({ code: baseAssetCode }),
createAndApproveAsset({ code: quoteAssetCode })
])
log.info(`Created assets for order book, base: ${baseAssetCode}, quote: ${quoteAssetCode}`)
await assetPairHelper.create({
base: baseAssetCode,
quote: quoteAssetCode,
policies: ASSET_PAIR_POLICIES.tradeableSecondaryMarket
})
log.info(`Created tradeable asset pair, base: ${baseAssetCode}, quote: ${quoteAssetCode}`)
await keyValueHelper.putEntries({
[ KEY_VALUE_KEYS.createOfferTasks + ':*:*' ]: 0
})
const actors = []
for (let i = 0; i < 1; i++) {
const balances = {
[baseAssetCode]: '1000.0000',
[quoteAssetCode]: '1000.0000'
}
const { accountId, accountKp } = await createFundedGeneral(balances)
log.info(`Actor ${accountId} created, ready to place offer`)
actors.push(accountKp)
}
for (const actorKp of actors) {
const amountToBuy = getRandomArbitrary('2.000000', '5.000000')
const priceToBuy = '44.55' // getRandomArbitrary('1.000000', '3.000000')
await createOfferRequest({
quoteAsset: quoteAssetCode,
baseAsset: baseAssetCode,
amount: amountToBuy,
price: priceToBuy,
orderBookID: '0',
isBuy: true
}, actorKp)
log.info(`actor ${actorKp.accountId()} made an offer to buy ${amountToBuy} ${baseAssetCode}`)
const amountToSell = getRandomArbitrary('5.100000', '8.000000') // we don't want offers to match here
const priceToSell = '66.11' // getRandomArbitrary('4.000000', '5.000000')
await createOfferRequest({
quoteAsset: quoteAssetCode,
baseAsset: baseAssetCode,
amount: amountToSell,
price: priceToSell,
orderBookID: '0',
isBuy: false
}, actorKp)
log.info(`actor ${actorKp.accountId()} made an offer to sell ${amountToSell} ${baseAssetCode}`)
}
}
export function getRandomArbitrary (min, max) {
const n = Math.random() * (Number(max) - Number(min)) + Number(min)
return n.toFixed(6)
}
|
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA-NoP20OejFNd_gxMizvmRCDHwRPg0gJI" ></script>
<style type="text/css">
#map {
height: calc(70vh);
}
</style>
<script>
function initMap() {
//var position = ;
// var locations = ;
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 13.3 , lng: 100.5778827},
zoom: 5.8
});
@foreach($dealers as $item)
var marker = new google.maps.Marker({
position: {lat: {{ $item->latitude }} , lng: {{ $item->longitude }} },
map: map,
});
/*google.maps.event.addListener(marker,'click',function(){
var info = new google.maps.InfoWindow({
content : '<div style = "font-size:15px;"> marker </div>'
});
info.open(map , marker);
});*/
@endforeach
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<div id="map"></div>
|
DELIMITER /
ALTER TABLE COST_ELEMENT ADD FIN_OBJECT_CODE VARCHAR(4)
/
DELIMITER ;
|
<?php
namespace DMraz\StenoApi\Serializers;
abstract class Base
{
protected $section;
public function __construct($sections)
{
$this->iterateSections($sections);
}
protected function iterateSections($sections)
{
foreach($sections as $section)
{
if($this->find($section)) {
break;
}
}
}
public function getSerializerName()
{
$reflect = new \ReflectionClass(get_class($this));
return strtolower($reflect->getShortName());
}
abstract protected function find($sections);
} |
package eu.caraus.home24.application.data.domain.home24
import com.google.gson.annotations.SerializedName
data class MediaItem(
@field:SerializedName("size")
val size: Any? = null,
@field:SerializedName("mimeType")
val mimeType: String? = null,
@field:SerializedName("type")
val type: Any? = null,
@field:SerializedName("priority")
val priority: Int? = null,
@field:SerializedName("uri")
val uri: String? = null
) |
<?php return array (
'root' =>
array (
'pretty_version' => 'v1.5.65',
'version' => '1.5.65.0',
'aliases' =>
array (
),
'reference' => NULL,
'name' => 'phphleb/hleb',
),
'versions' =>
array (
'phphleb/debugpan' =>
array (
'pretty_version' => 'v1.7',
'version' => '1.7.0.0',
'aliases' =>
array (
),
'reference' => 'a3a0dd3aaee432b934679d5dbc0f3357a39c9667',
),
'phphleb/framework' =>
array (
'pretty_version' => '1.5.65',
'version' => '1.5.65.0',
'aliases' =>
array (
),
'reference' => 'b3b660941f9179c1c9fb33674041b1b2a307ba0a',
),
'phphleb/hleb' =>
array (
'pretty_version' => 'v1.5.65',
'version' => '1.5.65.0',
'aliases' =>
array (
),
'reference' => NULL,
),
),
);
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/Navigation.framework/Navigation
*/
@interface MNSettingsManager : NSObject {
MNObserverHashTable * _observers;
MNSettings * _settings;
}
@property (nonatomic, readonly) MNSettings *settings;
+ (id)sharedInstance;
- (void).cxx_destruct;
- (void)_setVolumeFromDefaults;
- (void)addObserver:(id)arg1;
- (void)removeObserver:(id)arg1;
- (id)settings;
- (void)updateForSettings:(id)arg1;
@end
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CompanyName.MyMeetings.BuildingBlocks.Domain;
namespace CompanyName.MyMeetings.Modules.Payments.Domain.SeedWork
{
public interface IAggregateStore
{
Task Save();
Task<T> Load<T>(AggregateId<T> aggregateId) where T : AggregateRoot;
List<IDomainEvent> GetChanges();
void AppendChanges<T>(T aggregate) where T : AggregateRoot;
void ClearChanges();
}
} |
/////////////////////////////////////////////////////////////////////////////
// PigAccount.cpp : Implementation of the CPigAccount class.
#include "pch.h"
#include <TCLib.h>
#include <..\TCAtl\ObjectMap.h>
#include "PigAccountDispenser.h"
#include "PigAccount.h"
/////////////////////////////////////////////////////////////////////////////
// CPigAccount
TC_OBJECT_EXTERN_NON_CREATEABLE_IMPL(CPigAccount)
/////////////////////////////////////////////////////////////////////////////
// Construction / Destruction
CPigAccount::CPigAccount() :
m_pDispenser(NULL)
{
}
HRESULT CPigAccount::FinalConstruct()
{
// Indicate success
return S_OK;
}
void CPigAccount::FinalRelease()
{
// Release ourself within the parent object
XLock lock(this);
m_pDispenser->AccountReleased(m_bstrName);
// Release the parent object
m_pDispenser->Release();
m_pDispenser = NULL;
}
HRESULT CPigAccount::Init(CPigAccountDispenser* pDispenser, _bstr_t bstrName,
_bstr_t bstrPassword)
{
// Save the specified parameters
XLock lock(this);
m_pDispenser = pDispenser;
m_bstrName = bstrName;
m_bstrPassword = bstrPassword;
// AddRef the parent object
m_pDispenser->AddRef();
// Indicate success
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// ISupportErrorInfo Interface Methods
STDMETHODIMP CPigAccount::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IPigAccount,
};
for (int i = 0; i < sizeofArray(arr); ++i)
{
if (InlineIsEqualGUID(*arr[i], riid))
return S_OK;
}
return S_FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// IPigAccount Interface Methods
STDMETHODIMP CPigAccount::get_Name(BSTR* pbstrName)
{
// Initialize the [out] parameter
CLEAROUT(pbstrName, (BSTR)NULL);
// Copy the string to the [out] parameter
XLock lock(this);
*pbstrName = m_bstrName.copy();
// Indicate success
return S_OK;
}
STDMETHODIMP CPigAccount::get_Password(BSTR* pbstrPassword)
{
// Initialize the [out] parameter
CLEAROUT(pbstrPassword, (BSTR)NULL);
// Copy the string to the [out] parameter
XLock lock(this);
*pbstrPassword = m_bstrPassword.copy();
// Indicate success
return S_OK;
}
|
import scala.io._
import scala.quoted.Expr
def ﷽[A](a: A): A = a
object Day10 extends App:
val start = System.currentTimeMillis
val lines =
Source
.fromFile("src/resources/input10.txt")
.getLines
.toList
def loop(s: String, cur: List[Char] = List.empty[Char]): Option[Char] =
if (s.isEmpty && cur.isEmpty) None else {
s.toList match {
case Nil => None // incomplete
case '(' :: cs => loop(cs.mkString(""), '(' :: cur)
case '[' :: cs => loop(cs.mkString(""), '[' :: cur)
case '{' :: cs => loop(cs.mkString(""), '{' :: cur)
case '<' :: cs => loop(cs.mkString(""), '<' :: cur)
case ')' :: cs if cur.headOption == Some('(') => loop(cs.mkString(""), cur.tail)
case ']' :: cs if cur.headOption == Some('[') => loop(cs.mkString(""), cur.tail)
case '}' :: cs if cur.headOption == Some('{') => loop(cs.mkString(""), cur.tail)
case '>' :: cs if cur.headOption == Some('<') => loop(cs.mkString(""), cur.tail)
case c :: _ => Some(c)
}
}
val answer1 =
lines.map(loop(_)).filterNot(_.isEmpty).map {
case Some(')') => 3L
case Some(']') => 57L
case Some('}') => 1197L
case Some('>') => 25137L
case _ => sys.error(s"boom!")
}
.groupMapReduce(identity)(identity)(_+_)
.values.sum
println(s"Answer 1 = ${answer1} [${System.currentTimeMillis - start}ms]")
assert(answer1 == 268845)
def loop2(s: String, cur: List[Char] = List.empty[Char]): List[Char] =
if (s.isEmpty && cur.isEmpty) Nil else {
s.toList match {
case Nil => cur // incomplete
case '(' :: cs => loop2(cs.mkString(""), '(' :: cur)
case '[' :: cs => loop2(cs.mkString(""), '[' :: cur)
case '{' :: cs => loop2(cs.mkString(""), '{' :: cur)
case '<' :: cs => loop2(cs.mkString(""), '<' :: cur)
case ')' :: cs if cur.headOption == Some('(') => loop2(cs.mkString(""), cur.tail)
case ']' :: cs if cur.headOption == Some('[') => loop2(cs.mkString(""), cur.tail)
case '}' :: cs if cur.headOption == Some('{') => loop2(cs.mkString(""), cur.tail)
case '>' :: cs if cur.headOption == Some('<') => loop2(cs.mkString(""), cur.tail)
case c :: _ => Nil
}
}
val answer2 =
val scores = lines.map(loop2(_)).filterNot(_.isEmpty).map { stack =>
stack.foldLeft(0L)((res,c) => c match {
case '(' => (res * 5) + 1
case '[' => (res * 5) + 2
case '{' => (res * 5) + 3
case '<' => (res * 5) + 4
})
}.sorted
scores(scores.length / 2)
println(s"Answer 2 = ${answer2} [${System.currentTimeMillis - start}ms]")
assert(answer2 == 4038824534L)
|
/* eslint-disable no-console */
import mongoose from 'mongoose';
import chalk from 'chalk';
import configs from 'configs/index';
mongoose.Promise = global.Promise;
const { connection } = mongoose;
const logs = {
connected: chalk.bold.cyan,
error: chalk.bold.yellow,
disconnected: chalk.bold.red,
reconnected: chalk.bold.blue,
terminated: chalk.bold.magenta,
};
connection.on('connected', () => {
console.log(logs.connected(`Connected, default connection is open to: ${configs.DB_URL}`));
});
connection.on('error', (err) => {
console.log(logs.error(`Error, default connection has occured ${err} erorr`));
});
connection.on('disconnected', () => {
console.log(logs.disconnected('Disconnected'));
});
connection.on('reconnected', () => {
console.log(logs.reconnected(`Reconnected, default connection is re-open to: ${configs.DB_URL}`));
});
process.on('SIGINT', () => {
connection.close(() => {
console.log(logs.terminated('Terminated, default connection is disconnected due to application termination'));
process.exit(0);
});
});
const open = async () => {
try {
await mongoose.connect(configs.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
auth: {
user: configs.DB_USER,
password: configs.DB_PWD,
},
});
} catch (error) {
console.log(error);
}
};
const defaultInstance = connection;
export {
open,
defaultInstance,
};
|
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<label class="btn btn-success mb-0">
<input type="file" class="d-none" id="txtFile" /> 选择(拖拽)文件
</label>
<label id="labSize" class="ml-3"></label>
</div>
<div class="col-md-12 my-2">
<textarea class="form-control min300" id="txtBase64"></textarea>
</div>
<div class="col-md-12 mb-2">
<button class="btn btn-success" id="btnBase64ToFile">Base64转文件</button>
<div id="viewBase64" class="mt-3"></div>
</div>
</div>
</div>
<script src="/js/filetobase64.js" asp-append-version="true"></script> |
---
_id: 'https://my.framasoft.org/u/borisschapira/?chL6Aw'
title: '"Service Workers" par Eric Daspet à Paris Web 2015'
link: >-
https://docs.google.com/presentation/d/1hKQLmKrZU9pUVNYAp_loxxeuNeYtiqasVHn6IH2zcmk/edit#slide=id.p
date: '2015-10-01'
tags:
- name: js
slug: js
- name: offline
slug: offline
- name: service
slug: service
- name: sharemarks
slug: sharemarks
- name: webapp
slug: webapp
- name: workers
slug: workers
---
<div class="markdown"><p></p></div>
|
package edacc.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author simon
*/
public class Course extends BaseModel implements Serializable {
private int initialLength;
private List<InstanceSeed> instanceSeedList;
private int modifiedIndex;
public Course() {
super();
initialLength = 0;
modifiedIndex = 0;
instanceSeedList = new ArrayList<InstanceSeed>();
}
protected Course(Course course) {
this();
initialLength = course.initialLength;
modifiedIndex = course.modifiedIndex;
for (InstanceSeed is : course.instanceSeedList) {
instanceSeedList.add(new InstanceSeed(is.instance, is.seed));
}
}
protected void setInitialLength(int initialLength) {
this.initialLength = initialLength;
}
public int getInitialLength() {
return initialLength;
}
public void add(InstanceSeed elem) {
instanceSeedList.add(new InstanceSeed(elem.instance, elem.seed));
if (this.isSaved()) {
modifiedIndex = instanceSeedList.size()-1;
this.setModified();
}
}
public InstanceSeed get(int index) {
return new InstanceSeed(instanceSeedList.get(index).instance, instanceSeedList.get(index).seed);
}
protected int getModifiedIndex() {
return modifiedIndex;
}
public int getLength() {
return instanceSeedList.size();
}
public void clear() {
if (getModifiedIndex() != 0) {
throw new IllegalArgumentException("Cannot change a saved course.");
}
instanceSeedList.clear();
}
public List<InstanceSeed> getInstanceSeedList() {
return instanceSeedList;
}
}
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Plutonomy.Hereditary where
import Data.Foldable (foldl', toList)
import Data.Kind (Type)
import Data.Sequence (Seq)
import Data.String (IsString (..))
import Data.Text (Text)
import PlutusCore.Default (DefaultFun (..), DefaultUni (..), Some (..), ValueOf (..))
import qualified Data.Sequence as Seq
import Plutonomy.Builtins
import Plutonomy.Name
import Plutonomy.Raw (Raw)
import Plutonomy.Known (pattern RawFix)
import Subst
import qualified Plutonomy.Raw as Raw
-- $setup
-- >>> import Subst (Nat (..))
-- >>> import Data.Text (Text)
-- >>> import Plutonomy.Pretty (prettyRaw)
-- >>> import qualified Prettyprinter as PP
-- >>> let pp t = prettyRaw PP.pretty (toRaw (t :: Term Text Z))
-------------------------------------------------------------------------------
-- * Types
-------------------------------------------------------------------------------
-- | Term representation.
--
-- This representation is more-normalised then the 'Term'.
-- It forces applications to form 'mkLet bindings (we don't perfrom substitions!)
--
-- In addition the applications are represented in spine form,
-- therefore we can quickly access the head of a spine,
-- which we do often in the optimizer.
--
-- Terms are either
--
-- * Definitions 'Defn'
--
-- * Error
--
-- * or 'mkLet binding.
--
-- Before using this representation the @Script size" tests took 13.5 seconds.
-- Using @'toRaw' . 'fromRaw'@ as a simplify function takes 14.2 seconds.
--
type Term :: Type -> Nat -> Type
data Term a n
= Defn (Defn a n)
| Error
| Let Name (Defn a n) (Term a (S n))
deriving (Eq, Ord, Show)
-- | 'Spine' head is
--
-- * a variable ('HeadVar')
--
-- * free ('HeadFree')
--
-- * or a builtin ('HeadBuiltin')
--
data Head a n
= HeadVar (Var n)
| HeadFree a
| HeadBuiltin DefaultFun
| HeadFix
deriving (Eq, Ord, Show)
-- | Eliminators.
--
-- * Applications of an argument to a function ('App'), or
--
-- * Forcing of delayed terms ('Force').
--
-- Technically builtins should be eliminators, but we treat
-- them more like free variables.
--
data Elim a n
= App (Term a n)
| Force
deriving (Eq, Ord, Show)
-- | Definition forms.
--
-- * Neutral spines
--
-- * Lambda abstractions ('Lam'),
--
-- * Delayed terms ('Delay'), or
--
-- * Constants ('Constant').
--
-- in other forms neutral terms and introduction forms.
--
data Defn a n
= Neutral (Head a n) (Spine a n)
| Lam Name (Term a (S n))
| Delay (Term a n)
| Constant (Some (ValueOf DefaultUni))
deriving (Eq, Ord, Show)
type Spine a n = Seq (Elim a n)
-------------------------------------------------------------------------------
-- * Patterns
-------------------------------------------------------------------------------
pattern Var :: Var n -> Term a n
pattern Var x = Defn (Neutral (HeadVar x) Seq.Empty)
pattern Free :: a -> Term a n
pattern Free x = Defn (Neutral (HeadFree x) Seq.Empty)
pattern Builtin :: DefaultFun -> Term a n
pattern Builtin x = Defn (Neutral (HeadBuiltin x) Seq.Empty)
pattern Var0 :: Term a (S n)
pattern Var0 = Var VZ
pattern Var1 :: Term a (S (S n))
pattern Var1 = Var (VS VZ)
pattern Var2 :: Term a (S (S (S n)))
pattern Var2 = Var (VS (VS VZ))
-------------------------------------------------------------------------------
-- * Instances
-------------------------------------------------------------------------------
instance IsString a => IsString (Term a n) where
fromString = Free . fromString
instance Rename (Term a) where
r <@> Defn t = Defn (r <@> t)
r <@> Let n t s = Let n (r <@> t) (liftRen r <@> s)
_ <@> Error = Error
instance Rename (Defn a) where
r <@> Neutral h xs = Neutral (r <@> h) (fmap (r <@>) xs)
r <@> Lam n t = Lam n (liftRen r <@> t)
r <@> Delay t = Delay (r <@> t)
_ <@> Constant c = Constant c
instance Rename (Head a) where
r <@> HeadVar x = HeadVar (r <@> x)
_ <@> HeadFix = HeadFix
_ <@> HeadFree x = HeadFree x
_ <@> HeadBuiltin b = HeadBuiltin b
instance Rename (Elim a) where
r <@> App t = App (r <@> t)
_ <@> Force = Force
instance Vars (Term a) where
var = Var
instance Vars (Defn a) where
var x = Neutral (HeadVar x) Seq.Empty
bound = flip defnVars pure
instance Subst (Term a) where
subst = substTerm
substTerm :: Sub (Term a) n m -> Term a n -> Term a m
substTerm sub (Defn i) = substDefn sub i
substTerm _sub Error = Error
substTerm sub (Let n t s) = mkLet n (substDefn sub t) (substTerm (liftSub sub) s)
substDefn :: Sub (Term a) n m -> Defn a n -> Term a m
substDefn sub (Neutral h xs) = neutral_ (substHead sub h) (substElim sub <$> xs)
substDefn sub (Lam n b ) = Defn (Lam n (subst (liftSub sub) b))
substDefn sub (Delay t ) = Defn (Delay (subst sub t))
substDefn _sub (Constant c ) = Defn (Constant c)
substHead :: Sub (Term a) n m -> Head a n -> Term a m
substHead _sub (HeadFree x) = Free x
substHead _sub (HeadBuiltin b) = Builtin b
substHead sub (HeadVar x) = substVar sub x
substHead _sub HeadFix = Defn (Neutral HeadFix Seq.Empty)
substElim :: Sub (Term a) n m -> Elim a n -> Elim a m
substElim sub (App x) = App (subst sub x)
substElim _sub Force = Force
instance Free Term where
ret = Free
(>>==) = bindTerm
vars = termVars
bindTerm :: Term a n -> (a -> Term b n) -> Term b n
bindTerm (Defn i ) k = bindDefn i k
bindTerm (Error ) _ = Error
bindTerm (Let n t s) k = mkLet n (bindDefn t k) (bindTerm s (weaken . k))
bindHead :: Head a n -> (a -> Term b n) -> Term b n
bindHead (HeadFree x) k = k x
bindHead (HeadVar x) _ = Var x
bindHead (HeadBuiltin b) _ = Builtin b
bindHead HeadFix _ = Defn (Neutral HeadFix Seq.empty)
bindElim :: Elim a n -> (a -> Term b n) -> Elim b n
bindElim (App x) k = App (bindTerm x k)
bindElim Force _ = Force
bindDefn :: Defn a n -> (a -> Term b n) -> Term b n
bindDefn (Neutral h xs) k = neutral_ (bindHead h k) (fmap (`bindElim` k) xs)
bindDefn (Lam n t ) k = Defn (Lam n (bindTerm t (weaken . k)))
bindDefn (Delay t ) k = Defn (Delay (bindTerm t k))
bindDefn (Constant c) _ = Defn (Constant c)
termVars :: Applicative f => (Var n -> f (Var m)) -> (a -> f b) -> Term a n -> f (Term b m)
termVars f g (Defn i) = Defn <$> defnVars f g i
termVars _ _ (Error ) = pure Error
termVars f g (Let n t s ) = Let n <$> defnVars f g t <*> termVars f' g s where
f' VZ = pure VZ
f' (VS x) = VS <$> f x
headVars :: Applicative f => (Var n -> f (Var m)) -> (a -> f b) -> Head a n -> f (Head b m)
headVars _ g (HeadFree x) = HeadFree <$> g x
headVars _ _ (HeadBuiltin b) = pure (HeadBuiltin b)
headVars f _ (HeadVar x) = HeadVar <$> f x
headVars _ _ HeadFix = pure HeadFix
elimVars :: Applicative f => (Var n -> f (Var m)) -> (a -> f b) -> Elim a n -> f (Elim b m)
elimVars f g (App x) = App <$> vars f g x
elimVars _ _ Force = pure Force
defnVars :: Applicative f => (Var n -> f (Var m)) -> (a -> f b) -> Defn a n -> f (Defn b m)
defnVars f g (Neutral h xs) = Neutral <$> headVars f g h <*> traverse (elimVars f g) xs
defnVars f g (Lam n t) = Lam n <$> vars f' g t where
f' VZ = pure VZ
f' (VS x) = VS <$> f x
defnVars _ _ (Constant c ) = pure (Constant c)
defnVars f g (Delay t ) = Delay <$> vars f g t
-------------------------------------------------------------------------------
-- * Value
-------------------------------------------------------------------------------
-- | Applications, Forcing terms, 'mkLet and 'Error' are not values.
--
-- Unsaturated applications of builtins are also values.
--
-- >>> isValue (const 0) (const 0) (force_ trace_ :@ str_ "err")
-- True
--
-- >>> isValue (const 0) (const 0) (force_ trace_ :@ str_ "err" :@ tt_)
-- False
--
-- >>> isValue (const 0) (const 0) $ fix_ :@ lams_ ["rec", "x"] "x"
-- True
--
isValue
:: (Var n -> Int)
-> (a -> Int)
-> Term a n
-> Bool
isValue _ _ Error {} = False
isValue _ _ Let {} = False
isValue _ _ (Defn (Neutral (HeadBuiltin b) args)) = builtinArity b > length args
isValue v _ (Defn (Neutral (HeadVar x) args)) = null args || v x > length args
isValue _ h (Defn (Neutral (HeadFree x) args)) = null args || h x > length args
isValue _ _ (Defn (Neutral HeadFix Seq.Empty)) = True
isValue _ _ (Defn (Neutral HeadFix (f Seq.:<| args))) = elimArity f - 1 > length args
isValue _ _ (Defn Lam {}) = True
isValue _ _ (Defn Delay {}) = True
isValue _ _ (Defn Constant {}) = True
-- | Approximate arity of a term.
--
-- >>> termArity $ lam_ "x" "x"
-- 1
--
-- >>> termArity $ lams_ ["x","y","z"] "x"
-- 3
--
-- >>> termArity "free"
-- 0
--
termArity :: Term a n -> Int
termArity (Defn d) = defnArity d
termArity _ = 0
elimArity :: Elim a n -> Int
elimArity (App t) = termArity t
elimArity Force = 0
defnArity :: Defn a n -> Int
defnArity = go 0 where
go :: Int -> Defn a n -> Int
go !acc (Lam _ t) = go' (acc + 1) t
go acc (Delay t) = go' (acc + 1) t
go acc _ = acc
go' :: Int -> Term a n -> Int
go' !acc (Defn t) = go acc t
go' acc _ = acc
-------------------------------------------------------------------------------
-- * Error
-------------------------------------------------------------------------------
isErrorTerm :: Term n a -> Bool
isErrorTerm Error = True
isErrorTerm _ = False
isErrorElim :: Elim n a -> Bool
isErrorElim (App t) = isErrorTerm t
isErrorElim Force = False
-------------------------------------------------------------------------------
-- * Normilising \"constructors\"
-------------------------------------------------------------------------------
neutral_ :: Foldable f => Term a n -> f (Elim a n) -> Term a n
neutral_ = foldl' elim_
elim_ :: Term a n -> Elim a n -> Term a n
elim_ h Force = force_ h
elim_ h (App x) = app_ h x
-- | Let constructor on terms.
--
-- This automatically does /let-from-let/ transformation.
--
-- >>> let term = let_ "x" (let_ "y" (delay_ "foo") (delay_ "bar")) ("body" :@ "x" :@ "z")
-- >>> pp term
-- let* y = \ ~ -> foo
-- x = \ ~ -> bar
-- in body x z
--
-- It also inlines cheap definitions.
--
-- >>> let term = let_ "x" "foo" "x"
-- >>> pp term
-- foo
--
mkLet :: Name -> Term b n -> Term b (S n) -> Term b n
mkLet _ t Var0 = t
mkLet _ Error _ = Error
mkLet n (Defn d) r = mkLet' n d r
mkLet n (Let n' t s) r = Let n' t $ mkLet n s (rename bumpRen r)
-- cheap definitions
mkLet' :: Name -> Defn b n -> Term b (S n) -> Term b n
mkLet' n d r
| cheap d = instantiate1 (Defn d) r
| otherwise = Let n d r
where
cheap :: Defn a m -> Bool
cheap (Delay Error) = True
cheap (Lam _ Error) = True
cheap (Lam _ Var0) = True
cheap (Neutral _ Seq.Empty) = True
cheap _ = False
-------------------------------------------------------------------------------
-- * Smart constructors
-------------------------------------------------------------------------------
-- | Application @f x@
--
-- This automatically reduces an application of @'Lam' n s@ to @t@ to @'mkLet n t s@.
-- This also floats let from the head of application.
--
-- >>> let term = let_ "n" (delay_ "def") "f" :@ "x"
-- >>> pp term
-- let* n = \ ~ -> def
-- in f x
--
app_ :: Term a n -> Term a n -> Term a n
app_ (Defn (Neutral h xs)) x = Defn (Neutral h (xs Seq.|> App x))
app_ (Defn (Lam n t)) x = mkLet n x t
app_ (Defn Delay {}) _ = Error
app_ (Defn Constant {}) _ = Error
app_ (Let n t s) x = Let n t (app_ s (weaken x))
app_ Error _ = Error
-- | Matching oa npplication.
matchApp_ :: Term a n -> Maybe (Term a n, Term a n)
matchApp_ (Defn (Neutral h (xs Seq.:|> App x))) = Just (Defn (Neutral h xs), x)
matchApp_ _ = Nothing
-- | Infix version of 'app_'
--
-- >>> pp $ lam_ "x" $ "x" :@ "x"
-- \ x -> x x
--
pattern (:@) :: Term a n -> Term a n -> Term a n
pattern (:@) f x <- (matchApp_ -> Just (f, x))
where (:@) f x = app_ f x
infixl 9 :@
-- | Force @f !@
--
-- This automatically reduces forcing of @'Delay' t@ to @t@
-- This also floats out lets (or floats ins @!@).
--
-- >>> let term = force_ (delay_ "t")
-- >>> pp term
-- t
---
force_ :: Term a n -> Term a n
force_ (Defn (Neutral h xs)) = Defn (Neutral h (xs Seq.|> Force))
force_ (Defn (Delay t)) = t
force_ (Defn Lam {}) = Error
force_ (Defn Constant {}) = Error
force_ (Let n t s) = Let n t (force_ s)
force_ Error = Error
-- | 'Delay'.
delay_ :: Term a n -> Term a n
delay_ = Defn . Delay
-- | N-ary application.
--
-- >>> pp $ apps_ "f" ["x", "y", "z"]
-- f x y z
--
apps_ :: Foldable f => Term a n -> f (Term a n) -> Term a n
apps_ = foldl' app_
-- | Let smart constructor.
--
-- >>> pp $ let_ "x" (delay_ "foo") $ let_ "y" (delay_ "bar") "body"
-- let* x = \ ~ -> foo
-- y = \ ~ -> bar
-- in body
--
let_ :: Text -> Term Text n -> Term Text n -> Term Text n
let_ n t s = mkLet (Name n) t (abstract1 n s)
-- | Functioa nbstraction smart constructor.
--
-- >>> pp $ lam_ "x" $ "x" :@ "x"
-- \ x -> x x
--
lam_ :: Text -> Term Text n -> Term Text n
lam_ n t = Defn (Lam (Name n) (abstract1 n t))
-- | Functioa nbstraction for multiple arguments.
--
-- >>> pp $ lams_ ["x", "f"] $ "f" :@ "x"
-- \ x f -> f x
--
lams_ :: [Text] -> Term Text n -> Term Text n
lams_ n t = foldr lam_ t n
-- | Fixed-point
--
-- >>> pp fix_
-- let* fix = \ f -> let* s = \ s0 x -> f (s0 s0) x in s s
-- in fix
--
fix_ :: Term a n
fix_ = Defn (Neutral HeadFix Seq.Empty)
-- | If-then-else
ite_ :: Term a n
ite_ = Builtin IfThenElse
-- | Trace
trace_ :: Term a n
trace_ = Builtin Trace
-- | String constant.
str_ :: Text -> Term a n
str_ t = Defn (Constant (Some (ValueOf DefaultUniString t)))
-- | Builtin unit constant.
tt_ :: Term a n
tt_ = Defn (Constant (Some (ValueOf DefaultUniUnit ())))
-------------------------------------------------------------------------------
-- * Conversion
-------------------------------------------------------------------------------
-- | Convert 'Term' to 'Raw'.
toRaw :: Term a n -> Raw a n
toRaw t
| Just t'' <- bound unusedVar t' = t''
| otherwise = Raw.Let "fix" (RawFix "f" "s" "s0" "x") t'
where
t' = weaken (toRaw' t) >>== \aux -> case aux of
Aux a -> Raw.Free a
AuxFix -> Raw.Var0
toRaw' :: Term a n -> Raw (Aux a) n
toRaw' Error = Raw.Error
toRaw' (Defn i) = defnToRaw i
toRaw' (Let n t s) = Raw.Let n (defnToRaw t) (toRaw' s)
data Aux a
= Aux a
| AuxFix
elimToRaw :: Elim a n -> Raw.Arg (Aux a) n
elimToRaw (App t) = Raw.ArgTerm (toRaw' t)
elimToRaw Force = Raw.ArgForce
headToRaw :: Head a n -> Raw (Aux a) n
headToRaw (HeadVar x) = Raw.Var x
headToRaw HeadFix = Raw.Free AuxFix
headToRaw (HeadFree x) = Raw.Free (Aux x)
headToRaw (HeadBuiltin b) = Raw.Builtin b
defnToRaw :: Defn a n -> Raw (Aux a) n
defnToRaw (Neutral h xs) = Raw.appArgs_ (headToRaw h) (map elimToRaw (toList xs))
defnToRaw (Constant c) = Raw.Constant c
defnToRaw (Delay t) = Raw.Delay (toRaw' t)
defnToRaw (Lam n t) = Raw.Lam n (toRaw' t)
-- | Convert 'Raw' to 'Term'.
fromRaw :: Raw a n -> Term a n
fromRaw (RawFix _ _ _ _) = Defn (Neutral HeadFix Seq.Empty)
fromRaw (Raw.Var x) = Var x
fromRaw (Raw.Free x) = Free x
fromRaw (Raw.Builtin b) = Builtin b
fromRaw (Raw.Constant c) = Defn (Constant c)
fromRaw (Raw.Lam n t) = Defn (Lam n (fromRaw t))
fromRaw (Raw.Delay t) = Defn (Delay (fromRaw t))
fromRaw (Raw.App f t) = app_ (fromRaw f) (fromRaw t)
fromRaw (Raw.Let n t s) = mkLet n (fromRaw t) (fromRaw s)
fromRaw (Raw.Force t) = force_ (fromRaw t)
fromRaw Raw.Error = Error
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'covid_all_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CovidAllResponse _$CovidAllResponseFromJson(Map<String, dynamic> json) {
return CovidAllResponse(
todayDeaths: json['todayDeaths'] as int,
updated: json['updated'] as int,
cases: json['cases'] as int,
todayCases: json['todayCases'] as int,
deaths: json['deaths'] as int,
recovered: json['recovered'] as int,
todayRecovered: json['todayRecovered'] as int,
active: json['active'] as int,
critical: json['critical'] as int,
casesPerOneMillion: (json['casesPerOneMillion'] as num).toDouble(),
deathsPerOneMillion: (json['deathsPerOneMillion'] as num).toDouble(),
tests: json['tests'] as int,
testsPerOneMillion: (json['testsPerOneMillion'] as num).toDouble(),
population: json['population'] as int,
oneCasePerPeople: json['oneCasePerPeople'] as int,
oneDeathPerPeople: json['oneDeathPerPeople'] as int,
oneTestPerPeople: json['oneTestPerPeople'] as int,
activePerOneMillion: (json['activePerOneMillion'] as num).toDouble(),
recoveredPerOneMillion: (json['recoveredPerOneMillion'] as num).toDouble(),
criticalPerOneMillion: (json['criticalPerOneMillion'] as num).toDouble(),
affectedCountries: json['affectedCountries'] as int,
);
}
Map<String, dynamic> _$CovidAllResponseToJson(CovidAllResponse instance) =>
<String, dynamic>{
'updated': instance.updated,
'cases': instance.cases,
'todayDeaths': instance.todayDeaths,
'todayCases': instance.todayCases,
'deaths': instance.deaths,
'recovered': instance.recovered,
'todayRecovered': instance.todayRecovered,
'active': instance.active,
'critical': instance.critical,
'casesPerOneMillion': instance.casesPerOneMillion,
'deathsPerOneMillion': instance.deathsPerOneMillion,
'tests': instance.tests,
'testsPerOneMillion': instance.testsPerOneMillion,
'population': instance.population,
'oneCasePerPeople': instance.oneCasePerPeople,
'oneDeathPerPeople': instance.oneDeathPerPeople,
'oneTestPerPeople': instance.oneTestPerPeople,
'activePerOneMillion': instance.activePerOneMillion,
'recoveredPerOneMillion': instance.recoveredPerOneMillion,
'criticalPerOneMillion': instance.criticalPerOneMillion,
'affectedCountries': instance.affectedCountries,
};
|
module Arhelk.Armenian.Lemma.Substantive(
substantive,
stripHolov
) where
import Arhelk.Core.Rule
import Arhelk.Armenian.Lemma.Common
import Arhelk.Armenian.Lemma.Data
import Arhelk.Armenian.Lemma.Data.Substantive
import Control.Monad
import Data.Text as T
import Data.List as L
import Lens.Simple
stripHolov :: [Text] -> Text -> Text
stripHolov h w = L.foldl (\acc e ->
if acc `endsWith` [e]
then T.dropEnd (T.length e) acc
else acc
) w h
-- | Try to guess quantity, declension and case by ending of word
substantive :: Text -> Rule SubstantiveProperties
substantive w = do
guessQuantity
guessCase
guessArticle
where
guessArticle = do
let d = w `endsWith` ["ը"] -- This rule is 100%
let a = w `endsWith` ["ան", "են", "էն", "ին", "ուն", "ոն", "օն"] --This might be wrong
when (d) $ imply substArticle Definite
when (a) $ imply substArticle Definite
when (not (a || d) ) $ imply substArticle Undefinite
when (w `endsWith` ["ս"]) $ imply substArticle FirstPersonArticle
when (w `endsWith` ["դ"]) $ imply substArticle SecondPersonArticle
when (w `endsWith` ["ն"]) $ imply substArticle ThirdPersonArticle
guessQuantity = do
if (stripHolov (holovs Ուղղական) ws) `endsWith` ["եր","ներ"]
then imply substQuantity GrammarMultiple
else imply substQuantity GrammarSingle
where ws = if (w `endsWith` ["ը"]) then T.dropEnd 1 w else w
guessCase = do
when (ws `endsWith` holovs Սերական) $ imply substCase Սերական
when (ws `endsWith` holovs Տրական) $ imply substCase Տրական
when (ws `endsWith` holovs Հայցական) $ imply substCase Հայցական
when (ws `endsWith` holovs Բացարական) $ imply substCase Բացարական
when (ws `endsWith` holovs Գործիական) $ imply substCase Գործիական
when (ws `endsWith` holovs Ներգոյական) $ imply substCase Ներգոյական
when (not (ws `endsWith` holovs Ուղղական) || (w `endsWith` [""])) $ imply substCase Ուղղական
where ws = if (w `endsWith` ["ը"]) then T.dropEnd 1 w else w |
<?php
/*
/ Facade Pattern
/ We need to consider the use of the facade pattern in those cases that
/ the code that we want to use consists of too many classes and methods,
/ and all we want is a simple interface, preferably one method, that can do all the job for us.
*/
class FacebookShare {
public function shareOnFacebook(string $post)
{
echo "Shared {$post} with on Facebook\n";
}
}
class TwitterShare {
public function shareOnTwitter(string $post, int $postId)
{
echo "Shared {$post} with post id of {$postId} on Twitter\n";
}
}
class TelegramShare {
public function shareOnTelegram(string $post)
{
echo "Shared {$post} with on Telegram\n";
}
}
class ShareFacade {
private $facebookShare;
private $twitterShare;
private $telegramShare;
public function __construct()
{
$this->facebookShare = new FacebookShare();
$this->twitterShare = new TwitterShare();
$this->telegramShare = new TelegramShare();
}
public function share(string $post, int $postId)
{
$this->facebookShare->shareOnFacebook($post);
$this->twitterShare->shareOnTwitter($post, $postId);
$this->telegramShare->shareOnTelegram($post);
}
}
(new ShareFacade())->share('Post 1', '1'); |
# options :id=options
Miscellaneous options regarding the runtime behaviour of MQTT IO.
```yaml
Type: dict
Required: False
Default: {}
```
**Example**:
```yaml
options:
install_requirements: no
```
## install_requirements :id=options-install_requirements
*options*.**install_requirements**
Whether to install missing module packages on startup.
```yaml
Type: boolean
Required: False
Default: True
```
|
### bloom
班级聚会网站
### 功能
* 用户登录注册
* 用户信息配置
* 班级信息管理
* 联络簿
* 精彩内容
* 聚会照片展示
* 聚会倒计时与邀请函
### start
* $ git clone https://github.com/honwlee/bloom.git
* $ cd bloom; npm install; npm run dev;
### build
* $ cd bloom/build; npm install;
* $ gulp sass;
### 网站
[http://bloom.bedoer.com](http://bloom.bedoer.com)
### Contributors
* Fork it!
* Create your feature branch: git checkout -b my-new-feature
* Commit your changes: git commit -m 'Add some feature'
* Push to the branch: git push origin my-new-feature
* Submit a pull request
|
---
week: 13
day : April 27
title: Advanced Topic
---
### Summary
TBD. Given time, it will be the class's choice.
### Notes
- Reminder the bring your class to computer. |
using AdventOfCode.Base;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using static AdventOfCode.Base.Helpers;
namespace Day09
{
public class Day09Tests
{
private readonly ITestOutputHelper Output;
public Day09Tests(ITestOutputHelper output) => Output = output;
[Fact]
public void RunStep1() => Output.WriteLine(new Day09Solver().ExecutePuzzle1());
[Fact]
public void RunStep2() => Output.WriteLine(new Day09Solver().ExecutePuzzle2());
}
public class Day09Solver : SolverBase
{
protected override string Solve1(List<string> data)
{
var computer = new Computer(data[0]);
computer.Run();
computer.SetInputAndResume(1);
var result = new List<string>();
while (computer.State == State.OutputProduced) ;
result.Add(computer.GetOutputAndResume().ToString());
return string.Join(Environment.NewLine, result);
}
protected override string Solve2(List<string> data)
{
return "??";
}
}
}
|
<?php
namespace App\Repository;
use App\Entity\Watchlist;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* @method Watchlist|null find($id, $lockMode = null, $lockVersion = null)
* @method Watchlist|null findOneBy(array $criteria, array $orderBy = null)
* @method Watchlist[] findAll()
* @method Watchlist[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class WatchlistRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Watchlist::class);
}
public static function createWatchlist($name, $description = null, $expressions = [], $instruments = [])
{
$watchlist = new Watchlist();
$watchlist->setCreatedAt(new \DateTime())
->setName($name)
->setDescription($description)
;
foreach ($expressions as $expression) {
$watchlist->addExpression($expression);
}
foreach ($instruments as $instrument) {
$watchlist->addInstrument($instrument);
}
return $watchlist;
}
}
|
import * as R from 'ramda';
import hh from 'hyperscript-helpers';
import { h } from 'virtual-dom';
import {
billAmountInputMsg,
tipPercentInputMsg
} from './Update';
const {
div,
h1,
label,
input,
pre
} = hh(h);
const round = places =>
R.pipe(
num => num * Math.pow(10, places),
Math.round,
num => num * Math.pow(10, -1 * places),
);
const formatMoney = R.curry(
(symbol, places, number) => {
return R.pipe(
R.defaultTo(0),
round(places),
num => num.toFixed(places),
R.concat(symbol),
)(number);
}
);
function calcTipAndTotal(billAmount, tipPercent) {
const bill = parseFloat(billAmount);
const tip = bill * parseFloat(tipPercent) / 100 || 0;
return [tip, bill + tip];
}
function inputSet(name, value, oninput) {
return div({ className: 'w-40' }, [
label({ className: 'db fw6 lh-copy f5' }, name),
input({
className: 'border-box pa2 ba mb2 tr w-100',
type: 'text',
value,
oninput,
}),
]);
}
function calculatedAmounts(tip, total) {
return div({ className: 'w-40 b bt mt2 pt2' }, [
calculatedAmount('Tip:', tip),
calculatedAmount('Total:', total),
]);
}
function calculatedAmount(description, amount) {
return div({ className: 'flex w-100' }, [
div({ className: 'w-50 pv1 pr2' }, description),
div({ className: 'w-50 tr pv1 pr2' }, amount),
]);
}
function view(dispatch, model) {
const { billAmount, tipPercent } = model;
const [tip, total] = calcTipAndTotal(billAmount, tipPercent);
const toMoney = formatMoney('$', 2);
return div({ className: 'mw6 center' }, [
h1({ className: 'f2 pv2 bb' }, 'Tip Calculator'),
inputSet('Bill Amount', billAmount, e =>
dispatch(billAmountInputMsg(e.target.value)),
),
inputSet('Tip %', tipPercent, e =>
dispatch(tipPercentInputMsg(e.target.value)),
),
calculatedAmounts(toMoney(tip), toMoney(total)),
]);
}
export default view;
|
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#pragma once
#include "Async/Future.h"
#include "CoreMinimal.h"
#include "UObject/StrongObjectPtr.h"
DECLARE_LOG_CATEGORY_EXTERN(LogSpatialGDKEditor, Log, All);
DECLARE_DELEGATE_OneParam(FSpatialGDKEditorErrorHandler, FString);
class FSpatialGDKDevAuthTokenGenerator;
class FSpatialGDKPackageAssembly;
struct FCloudDeploymentConfiguration;
class SPATIALGDKEDITOR_API FSpatialGDKEditor
{
public:
FSpatialGDKEditor();
enum ESchemaGenerationMethod
{
InMemoryAsset,
FullAssetScan
};
bool GenerateSchema(ESchemaGenerationMethod Method);
void GenerateSnapshot(UWorld* World, FString SnapshotFilename, FSimpleDelegate SuccessCallback, FSimpleDelegate FailureCallback, FSpatialGDKEditorErrorHandler ErrorCallback);
void StartCloudDeployment(const FCloudDeploymentConfiguration& Configuration, FSimpleDelegate SuccessCallback, FSimpleDelegate FailureCallback);
void StopCloudDeployment(FSimpleDelegate SuccessCallback, FSimpleDelegate FailureCallback);
bool IsSchemaGeneratorRunning() { return bSchemaGeneratorRunning; }
bool FullScanRequired();
bool IsSchemaGenerated();
void SetProjectName(const FString& InProjectName);
TSharedRef<FSpatialGDKDevAuthTokenGenerator> GetDevAuthTokenGeneratorRef();
TSharedRef<FSpatialGDKPackageAssembly> GetPackageAssemblyRef();
private:
bool bSchemaGeneratorRunning;
TFuture<bool> SchemaGeneratorResult;
TFuture<bool> LaunchCloudResult;
TFuture<bool> StopCloudResult;
bool LoadPotentialAssets(TArray<TStrongObjectPtr<UObject>>& OutAssets);
FDelegateHandle OnAssetLoadedHandle;
void OnAssetLoaded(UObject* Asset);
void RemoveEditorAssetLoadedCallback();
TSharedRef<FSpatialGDKDevAuthTokenGenerator> SpatialGDKDevAuthTokenGeneratorInstance;
TSharedRef<FSpatialGDKPackageAssembly> SpatialGDKPackageAssemblyInstance;
};
|
using FanKit.Transformers;
using Retouch_Photo2.Layers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Retouch_Photo2.ViewModels
{
public partial class ViewModel : INotifyPropertyChanged
{
/// <summary> Gets or sets the snap. </summary>
public VectorVectorSnap VectorVectorSnap = new VectorVectorSnap();
/// <summary> Gets or sets the snap. </summary>
public VectorBorderSnap VectorBorderSnap = new VectorBorderSnap();
/// <summary> Gets or sets the snap. </summary>
public BorderBorderSnap BorderBorderSnap = new BorderBorderSnap();
/// <summary> Initiate the snap. </summary>
public void VectorVectorSnapInitiate(NodeCollection nodes)
{
this.VectorVectorSnap.Destinations =
from node
in nodes
where node.IsChecked == false && node.Type != NodeType.EndFigure
select node.Point;
// NodeRadius
float scale = this.CanvasTransformer.Scale;
this.VectorVectorSnap.NodeRadius = FanKit.Math.NodeRadius / scale;
}
/// <summary> Initiate the snap. </summary>
public void VectorBorderSnapInitiate(Transformer transformer)
{
this.VectorBorderSnap.Destinations = this.GetSnapDestinations(transformer);
// NodeRadius
float scale = this.CanvasTransformer.Scale;
this.VectorBorderSnap.NodeRadius = FanKit.Math.NodeRadius / scale;
}
/// <summary> Initiate the snap. </summary>
public void VectorBorderSnapInitiate(Layerage firstLayerages)
{
if ((firstLayerages is null) == false)
{
this.VectorBorderSnap.Destinations = this.GetSnapDestinations(firstLayerages);
}
// NodeRadius
float scale = this.CanvasTransformer.Scale;
this.VectorBorderSnap.NodeRadius = FanKit.Math.NodeRadius / scale;
}
/// <summary> Initiate the snap. </summary>
public void BorderBorderSnapInitiate(Layerage firstLayer)
{
if ((firstLayer is null) == false)
{
this.BorderBorderSnap.Destinations = this.GetSnapDestinations(firstLayer);
}
// NodeRadius
float scale = this.CanvasTransformer.Scale;
this.BorderBorderSnap.NodeRadius = FanKit.Math.NodeRadius / scale;
}
private IEnumerable<TransformerBorder> GetSnapDestinations(Transformer transformer)
{
yield return new TransformerBorder(transformer);
}
private IEnumerable<TransformerBorder> GetSnapDestinations(Layerage firstLayer)
{
// CanvasTransformer
float width = this.CanvasTransformer.Width;
float height = this.CanvasTransformer.Height;
yield return new TransformerBorder(width, height);
// Parents
if (firstLayer.Parents != LayerManager.RootLayerage)
{
Transformer transformer = firstLayer.Parents.Self.Transform.Transformer;
yield return new TransformerBorder(transformer);
}
// Layers
Layerage layerage = LayerManager.GetParentsChildren(firstLayer);
foreach (Layerage child in layerage.Children)
{
if (child.Self.IsSelected == false)
{
Transformer transformer = child.Self.Transform.Transformer;
yield return new TransformerBorder(transformer);
}
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnScriptUpgraded : MonoBehaviour
{
[System.Serializable]
public struct prefabData
{
public GameObject prefab;
public float spawnChance;
public float spawnRad;
}
public prefabData[] prefabsBig;
public prefabData[] prefabsSmall;
public float difficulty;
public float genOffcetUp;
public float genDelOffcet;
public ScoreScript score;
float spawnRate = 1.0f;
public int prefDif = 3;
/*
In posArray is data of spawnPositions for small and big blocks
it is a two dismentional array with 5 Vector3 coordinates in a row,
wich represent 4 small coordinates and 1 big
*/
GameObject Player;
Vector3 spawnPosition;
void Start()
{
Player = GameObject.Find("Player Model");
spawnPosition = transform.position;
}
void Update()
{
if (Player.transform.position.y + genOffcetUp > spawnPosition.y)
{
GenerateLevel(spawnPosition);
spawnPosition.y += 10.0f;
}
ClearRedundantParts();
}
public void GenerateLevel(Vector3 spawnPositionG)
{
int spawnBlockType = (int)Random.Range(1.0f, 4.0f);
switch (spawnBlockType)
{
case 1:
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f + 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f + 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f + 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f + 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f - 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f - 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f - 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f - 5, -2.5f, 0.0f), prefabsSmall, prefDif);
break;
case 2:
SpawnObjectInPlace(spawnPositionG + new Vector3(-5.0f, 0.0f, 0.0f), prefabsBig, 0);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f + 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f + 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f + 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f + 5, -2.5f, 0.0f), prefabsSmall, prefDif);
break;
case 3:
SpawnObjectInPlace(spawnPositionG, prefabsBig, 0);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f + 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f + 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f - 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f - 5, 2.5f, 0.0f), prefabsSmall, prefDif);
break;
case 4:
SpawnObjectInPlace(spawnPositionG + new Vector3(5.0f, 0.0f, 0.0f), prefabsBig, 0);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f - 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f - 5, 2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(2.5f - 5, -2.5f, 0.0f), prefabsSmall, prefDif);
SpawnObjectInPlace(spawnPositionG + new Vector3(-2.5f - 5, -2.5f, 0.0f), prefabsSmall, prefDif);
break;
}
if (score.yMax % 200 == 0 && score.yMax <= 1000 && score.yMax > 0)
{
spawnRate -= 0.05f;
if (prefDif > 0)
{
prefDif -= 1;
}
difficulty += 1;
}
}
public void SpawnObjectInPlace(Vector3 spawnPos, prefabData[] prefs, int prefDifF)
{
int num = (int)Random.Range(0, prefs.Length - prefDifF);
if (Random.Range(0, prefs[num].spawnChance) < spawnRate)
{
GameObject pref = Instantiate(prefs[num].prefab);
Vector3 spawnPosPref = Random.insideUnitCircle * prefs[num].spawnRad;
spawnPos = spawnPosPref + spawnPos;
pref.transform.position = spawnPos;
pref.transform.SetParent(transform);
}
}
public void ClearRedundantParts()
{
for (int i = 0; i < this.gameObject.transform.childCount; i++)
{
if (this.gameObject.transform.GetChild(i).position.y < Player.transform.position.y - genDelOffcet)
{
Destroy(this.gameObject.transform.GetChild(i).gameObject);
}
}
}
public void ClearAll()
{
spawnPosition = transform.position;
score.yMax = 0;
for (int i = 0; i < this.gameObject.transform.childCount; i++)
{
Destroy(this.gameObject.transform.GetChild(i).gameObject);
}
}
}
|
#include<iostream>
#include<queue>
using namespace std;
struct node{
int data;
node * left;
node * right;
node(int data){
this->data = data;
left = right = NULL;
}
};
void addElement(node *& root,int data){
if(!root){
root = new node(data);
return;
}
node * it = root;
node * prev = NULL;
while(it){
prev = it;
if(it->data > data){
it = it->left;
}else{
it = it->right;
}
}
if(prev->data > data){
prev->left = new node(data);
}else{
prev->right = new node(data);
}
return;
}
void printLevelWisePrint(node * root){
queue<node *>q1;
queue<node *>q2;
q1.push(root);
while(!q1.empty() || !q2.empty()){
while(!q1.empty()){
node * top = q1.front();
q1.pop();
cout<<top->data<<" ";
if(top->left){
q2.push(top->left);
}
if(top->right){o
q2.push(top->right);
}
}
cout<<endl;
while(!q2.empty()){
node * top = q2.front();
q2.pop();
cout<<top->data<<" ";
if(top->left){
q1.push(top->left);
}
if(top->right){
q1.push(top->right);
}
}
cout<<endl;
}
}
v
int main(){
node * root = NULL;
addElement(root,8);addElement(root,3);addElement(root,10);
addElement(root,1);addElement(root,6);addElement(root,14);
addElement(root,13);addElement(root,4);addElement(root,7);
addElement(root,2);
printLevelWisePrint(root);
}
|
//! Message types used in the SaltyRTC protocol.
//!
//! ## Implementation notes
//!
//! All message types own their values. This choice was made to simplify the
//! use and implementation of the library. Some values may be optimized to take
//! references in a future version.
use std::collections::HashMap;
use std::convert::From;
use rmp_serde as rmps;
use rmpv::Value;
use serde::{Deserialize, Serialize};
use crate::crypto_types::{PublicKey, SignedKeys};
use crate::errors::{SignalingError, SignalingResult};
use crate::tasks::Tasks;
use crate::CloseCode;
use super::send_error::SendErrorId;
use super::{Address, Cookie};
/// The `Message` enum contains all possible message types that may be used
/// during the handshake in the SaltyRTC protocol.
///
/// When converting a `Message` to msgpack bytes, it is serialized as
/// internally tagged enum. This is why the inner structs don't actually need
/// to contain a `type` field.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(tag = "type")]
pub(crate) enum Message {
// Server to client messages
#[serde(rename = "client-hello")]
ClientHello(ClientHello),
#[serde(rename = "server-hello")]
ServerHello(ServerHello),
#[serde(rename = "client-auth")]
ClientAuth(ClientAuth),
#[serde(rename = "server-auth")]
ServerAuth(ServerAuth),
#[serde(rename = "new-initiator")]
NewInitiator(NewInitiator),
#[serde(rename = "new-responder")]
NewResponder(NewResponder),
#[serde(rename = "drop-responder")]
DropResponder(DropResponder),
#[serde(rename = "send-error")]
SendError(SendError),
#[serde(rename = "disconnected")]
Disconnected(Disconnected),
// Client to client messages
#[serde(rename = "token")]
Token(Token),
#[serde(rename = "key")]
Key(Key),
#[serde(rename = "auth")]
Auth(Auth),
#[serde(rename = "close")]
Close(Close),
}
impl Message {
/// Decode a message from msgpack bytes.
pub(crate) fn from_msgpack(bytes: &[u8]) -> SignalingResult<Self> {
Ok(rmps::from_slice(bytes)?)
}
/// Convert this message to msgpack bytes.
pub(crate) fn to_msgpack(&self) -> Vec<u8> {
rmps::to_vec_named(&self).expect("Serialization failed")
}
/// Return the type of the contained message.
pub(crate) fn get_type(&self) -> &'static str {
match *self {
// Server to client messages
Message::ClientHello(_) => "client-hello",
Message::ServerHello(_) => "server-hello",
Message::ClientAuth(_) => "client-auth",
Message::ServerAuth(_) => "server-auth",
Message::NewInitiator(_) => "new-initiator",
Message::NewResponder(_) => "new-responder",
Message::DropResponder(_) => "drop-responder",
Message::SendError(_) => "send-error",
Message::Disconnected(_) => "disconnected",
// Client to client messages
Message::Token(_) => "token",
Message::Key(_) => "key",
Message::Auth(_) => "auth",
Message::Close(_) => "close",
}
}
}
/// Implement conversion traits to wrap a type in a `Message`.
macro_rules! impl_message_wrapping {
($type:ty, $variant:expr) => {
impl From<$type> for Message {
fn from(val: $type) -> Self {
$variant(val)
}
}
#[allow(dead_code)]
impl $type {
pub(crate) fn into_message(self) -> Message {
self.into()
}
}
};
}
impl_message_wrapping!(ClientHello, Message::ClientHello);
impl_message_wrapping!(ServerHello, Message::ServerHello);
impl_message_wrapping!(ClientAuth, Message::ClientAuth);
impl_message_wrapping!(ServerAuth, Message::ServerAuth);
impl_message_wrapping!(NewInitiator, Message::NewInitiator);
impl_message_wrapping!(NewResponder, Message::NewResponder);
impl_message_wrapping!(DropResponder, Message::DropResponder);
impl_message_wrapping!(SendError, Message::SendError);
impl_message_wrapping!(Token, Message::Token);
impl_message_wrapping!(Key, Message::Key);
impl_message_wrapping!(Auth, Message::Auth);
impl_message_wrapping!(Close, Message::Close);
/// The client-hello message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct ClientHello {
pub(crate) key: PublicKey,
}
impl ClientHello {
pub(crate) fn new(key: PublicKey) -> Self {
Self { key }
}
/// Create a new instance with dummy data. Used in testing.
#[cfg(test)]
pub(crate) fn random() -> Self {
use crypto_box::rand_core::{OsRng, RngCore};
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
Self {
key: PublicKey::from(bytes),
}
}
}
/// The server-hello message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct ServerHello {
pub(crate) key: PublicKey,
}
impl ServerHello {
#[cfg(test)]
pub(crate) fn new(key: PublicKey) -> Self {
Self { key }
}
/// Create a new instance with dummy data. Used in testing.
#[cfg(test)]
pub(crate) fn random() -> Self {
use crypto_box::rand_core::{OsRng, RngCore};
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
Self {
key: PublicKey::from(bytes),
}
}
}
/// The client-auth message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct ClientAuth {
pub(crate) your_cookie: Cookie,
pub(crate) subprotocols: Vec<String>,
pub(crate) ping_interval: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) your_key: Option<PublicKey>,
}
/// The server-auth message received by the initiator.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct ServerAuth {
pub(crate) your_cookie: Cookie,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) signed_keys: Option<SignedKeys>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) responders: Option<Vec<Address>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) initiator_connected: Option<bool>,
}
impl ServerAuth {
/// Create a new ServerAuth message targeted at an initiator.
#[cfg(test)]
pub(crate) fn for_initiator(
your_cookie: Cookie,
signed_keys: Option<SignedKeys>,
responders: Vec<Address>,
) -> Self {
Self {
your_cookie,
signed_keys,
responders: Some(responders),
initiator_connected: None,
}
}
/// Create a new ServerAuth message targeted at a responder.
#[cfg(test)]
pub(crate) fn for_responder(
your_cookie: Cookie,
signed_keys: Option<SignedKeys>,
initiator_connected: bool,
) -> Self {
Self {
your_cookie,
signed_keys,
responders: None,
initiator_connected: Some(initiator_connected),
}
}
}
/// Sent by the server to all responders when a new initiator joins.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct NewInitiator;
/// Sent by the server to the initiator when a new responder joins.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct NewResponder {
pub(crate) id: Address,
}
#[allow(dead_code)]
pub(crate) enum DropReason {
ProtocolError,
InternalError,
DroppedByInitiator,
InitiatorCouldNotDecrypt,
}
impl Into<u16> for DropReason {
fn into(self) -> u16 {
use self::DropReason::*;
match self {
ProtocolError => 3001,
InternalError => 3002,
DroppedByInitiator => 3004,
InitiatorCouldNotDecrypt => 3005,
}
}
}
/// Sent by the initiator to the server when requesting to drop a responder.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct DropResponder {
pub(crate) id: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) reason: Option<u16>,
}
impl DropResponder {
/// Create a new `DropResponder` message with a reason code.
pub(crate) fn with_reason(id: Address, reason: DropReason) -> Self {
Self {
id,
reason: Some(reason.into()),
}
}
}
/// Sent by the server if relaying a client-to-client message fails.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct SendError {
pub(crate) id: SendErrorId,
}
/// Sent by the server if an authenticated peer disconnects.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Disconnected {
pub(crate) id: Address,
}
impl Disconnected {
#[allow(dead_code)]
pub(crate) fn new(id: Address) -> Self {
Self { id }
}
}
/// The token message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Token {
pub(crate) key: PublicKey,
}
impl Token {
/// Create a new instance with dummy data. Used in testing.
#[cfg(test)]
pub(crate) fn random() -> Self {
use crypto_box::rand_core::{OsRng, RngCore};
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
Self {
key: PublicKey::from(bytes),
}
}
}
/// The key message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Key {
// TODO (#9): Do we want to differentiate between permanent key and session key
// in the type system?
pub(crate) key: PublicKey,
}
impl Key {
/// Create a new instance with dummy data. Used in testing.
#[cfg(test)]
pub(crate) fn random() -> Self {
use crypto_box::rand_core::{OsRng, RngCore};
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
Self {
key: PublicKey::from(bytes),
}
}
}
/// The auth message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Auth {
pub(crate) your_cookie: Cookie,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) tasks: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) task: Option<String>,
pub(crate) data: HashMap<String, Option<HashMap<String, Value>>>,
}
pub(crate) struct InitiatorAuthBuilder {
auth: Auth,
}
pub(crate) struct ResponderAuthBuilder {
auth: Auth,
}
impl InitiatorAuthBuilder {
/// Create a new `Auth` message targeted at a responder.
pub(crate) fn new(your_cookie: Cookie) -> Self {
Self {
auth: Auth {
your_cookie,
tasks: None,
task: None,
data: HashMap::new(),
},
}
}
/// Set the task.
pub(crate) fn set_task<S: Into<String>>(
mut self,
name: S,
data: Option<HashMap<String, Value>>,
) -> Self {
let name: String = name.into();
self.auth.task = Some(name.clone());
self.auth.data.clear();
self.auth.data.insert(name, data);
self
}
/// Return the resulting `Auth` message.
pub(crate) fn build(self) -> SignalingResult<Auth> {
if self.auth.tasks.is_some() {
panic!("tasks may not be set");
}
if self.auth.task.is_some() {
Ok(self.auth)
} else {
Err(SignalingError::InvalidMessage(
"An `Auth` message must have a task set".into(),
))
}
}
}
impl ResponderAuthBuilder {
/// Create a new `Auth` message targeted at an initiator.
pub(crate) fn new(your_cookie: Cookie) -> Self {
Self {
auth: Auth {
your_cookie,
tasks: Some(vec![]),
task: None,
data: HashMap::new(),
},
}
}
/// Add a task.
#[cfg(test)]
pub(crate) fn add_task<S: Into<String>>(
mut self,
name: S,
data: Option<HashMap<String, Value>>,
) -> Self {
let name: String = name.into();
match self.auth.tasks {
Some(ref mut tasks) => tasks.push(name.clone()),
None => panic!("tasks list not initialized!"),
};
self.auth.data.insert(name, data);
self
}
/// Add a `Tasks` instance.
pub(crate) fn add_tasks(mut self, tasks: &Tasks) -> Self {
for task in &tasks.0 {
let name: String = task.name().into();
match self.auth.tasks {
Some(ref mut tasks) => tasks.push(name.clone()),
None => panic!("tasks list not initialized!"),
};
self.auth.data.insert(name, task.data());
}
self
}
/// Return the resulting `Auth` message.
pub(crate) fn build(self) -> SignalingResult<Auth> {
if self.auth.task.is_some() {
panic!("task may not be set");
}
{
// Validate tasks
let tasks = self
.auth
.tasks
.as_ref()
.expect("tasks list not initialized!");
// Ensure that tasks list is not empty
if tasks.is_empty() {
return Err(SignalingError::InvalidMessage(
"An `Auth` message must contain at least one task".to_string(),
));
}
// Ensure that tasks list does not contain duplicates
let mut cloned = tasks.clone();
cloned.sort_unstable();
cloned.dedup();
if cloned.len() != tasks.len() {
return Err(SignalingError::InvalidMessage(
"An `Auth` message may not contain duplicate tasks".to_string(),
));
}
} // Waiting for NLL
Ok(self.auth)
}
}
/// The client-hello message.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Close {
pub(crate) reason: u16,
}
impl Close {
#[cfg(test)]
pub(crate) fn new(reason: u16) -> Self {
Self { reason }
}
pub(crate) fn from_close_code(close_code: CloseCode) -> Self {
Self {
reason: close_code.as_number(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
/// Verify that a message is correctly serialized, internally tagged.
fn test_encode_message() {
let key = PublicKey::from([
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 99, 255,
]);
let msg = Message::ServerHello(ServerHello { key });
let bytes: Vec<u8> = rmps::to_vec_named(&msg).expect("Serialization failed");
#[rustfmt::skip]
assert_eq!(bytes, vec![
// Fixmap with two entries
0x82,
// Key: type
0xa4, 0x74, 0x79, 0x70, 0x65,
// Val: server-hello
0xac, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2d, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
// Key: key
0xa3, 0x6b, 0x65, 0x79,
// Val: Binary 32 bytes
0xc4, 0x20,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x63, 0xff,
]);
}
#[test]
/// Verify that a message is correctly deserialized, depending on the type.
fn test_decode_message() {
// Create the ServerHello message we'll compare against
let key = PublicKey::from([
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 99, 255,
]);
let server_hello = ServerHello { key };
// The bytes to deserialize
#[rustfmt::skip]
let bytes = vec![
// Fixmap with two entries
0x82,
// Key: type
0xa4, 0x74, 0x79, 0x70, 0x65,
// Val: server-hello
0xac, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2d, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
// Key: key
0xa3, 0x6b, 0x65, 0x79,
// Val: Binary 32 bytes
0xc4, 0x20,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x63, 0xff,
];
// Deserialize and compare
let msg: Message = rmps::from_slice(&bytes).unwrap();
if let Message::ServerHello(sh) = msg {
assert_eq!(sh, server_hello);
} else {
panic!(
"Wrong message type: Should be ServerHello, but is {:?}",
msg
);
}
}
mod roundtrip {
use super::*;
macro_rules! roundtrip {
($name:ident, $msg_inner:expr) => {
#[test]
fn $name() {
let msg: Message = $msg_inner.into();
let bytes = msg.to_msgpack();
let decoded = Message::from_msgpack(&bytes).unwrap();
assert_eq!(msg, decoded);
}
};
}
roundtrip!(client_hello, ClientHello::random());
roundtrip!(server_hello, ServerHello::random());
roundtrip!(
drop_responder,
DropResponder::with_reason(4.into(), DropReason::DroppedByInitiator)
);
roundtrip!(token, Token::random());
roundtrip!(key, Key::random());
roundtrip!(
auth_responder,
InitiatorAuthBuilder::new(Cookie::random())
.set_task("foo.bar.baz", None)
.build()
.unwrap()
);
roundtrip!(
auth_initiator,
ResponderAuthBuilder::new(Cookie::random())
.add_task("foo.bar.baz", None)
.build()
.unwrap()
);
roundtrip!(close, Close::new(3003));
}
mod auth {
use super::*;
#[test]
fn initiator_auth_builder_incomplete() {
let builder = InitiatorAuthBuilder::new(Cookie::random());
let result = builder.build();
assert!(result.is_err());
}
#[test]
fn initiator_auth_builder() {
let cookie = Cookie::random();
let builder = InitiatorAuthBuilder::new(cookie.clone()).set_task("data.none", None);
let result = builder.build();
let auth = result.unwrap();
assert_eq!(auth.your_cookie, cookie);
assert!(auth.tasks.is_none());
assert!(auth.task.is_some());
assert_eq!(auth.task.unwrap(), "data.none");
assert_eq!(auth.data.len(), 1);
assert!(auth.data.contains_key("data.none"));
}
#[test]
fn responder_auth_builder_incomplete() {
let builder = ResponderAuthBuilder::new(Cookie::random());
let result = builder.build();
assert!(result.is_err());
}
#[test]
fn responder_auth_builder() {
let mut data = HashMap::new();
data.insert("foo".to_string(), Value::Boolean(true));
let cookie = Cookie::random();
let builder = ResponderAuthBuilder::new(cookie.clone())
.add_task("data.none", None)
.add_task("data.some", Some(data.clone()));
let result = builder.build();
let auth = result.unwrap();
assert_eq!(auth.your_cookie, cookie);
assert!(auth.task.is_none());
assert!(auth.tasks.is_some());
assert_eq!(auth.tasks.unwrap().len(), 2);
assert_eq!(auth.data.len(), 2);
}
}
mod send_error {
use super::*;
#[test]
fn send_error_decode() {
#[rustfmt::skip]
let bytes = [
// Fixmap with two entries
0x82,
// Key: type
0xa4, 0x74, 0x79, 0x70, 0x65,
// Val: send-error
0xaa, 0x73, 0x65, 0x6e, 0x64, 0x2d, 0x65, 0x72, 0x72, 0x6f, 0x72,
// Key: id
0xa2, 0x69, 0x64,
// Val: binary data
0xc4, 0x08,
// Source address
0x02,
// Destination address
0x01,
// Overflow number
0x00, 0x00,
// Sequence number
0x8a, 0xe3, 0xbe, 0xb5,
];
let msg: Message = rmps::from_slice(&bytes).unwrap();
if let Message::SendError(se) = msg {
assert_eq!(se.id.source, Address(2));
assert_eq!(se.id.destination, Address(1));
assert_eq!(se.id.csn.overflow_number(), 0);
assert_eq!(
se.id.csn.sequence_number(),
(0x8a << 24) + (0xe3 << 16) + (0xbe << 8) + 0xb5
);
} else {
panic!("Wrong message type: Should be SendError, but is {:?}", msg);
}
}
}
}
|
Subsets and Splits