text
stringlengths 27
775k
|
|---|
interface onEveryReturn {
/**
* Callback function you passed to onEvery
*/
callback: () => void;
/**
* Timer Id of setInterval
*/
code: number;
/**
* Stop the interval, you cannot resume
*/
stop(): boolean;
/**
* Pauses the interval, it's resumable
*/
pause(): boolean;
/**
* Resumes paused interval
*/
resume(): boolean;
}
interface IdleInfo {
/**
* if page idle now?
*/
isIdle: boolean,
/**
* How long was the page idle in milliseconds
*/
idleFor: number,
/**
* How much time left to become idle in milliseconds
*/
timeLeft: number,
/**
* How much time left to become idle represented as percentage
*/
timeLeftPer: string
}
interface IfVisible {
/**
* Registers a callback function to blur event
* @param callback function to run when event fires
*/
blur(callback: () => void): IfVisible;
/**
* Triggers the blur event
*/
blur(): IfVisible;
/**
* Registers a callback function to focus event
* @param callback function to run when event fires
*/
focus(callback: () => void): IfVisible;
/**
* Triggers the focus event
*/
focus(): IfVisible;
/**
* Registers a callback function to idle event
* @param callback function to run when event fires
*/
idle(callback: () => void): IfVisible;
/**
* Triggers the idle event
*/
idle(): IfVisible;
/**
* Registers a callback function to wakeup event
* @param callback function to run when event fires
*/
wakeup(callback: () => void): IfVisible;
/**
* Triggers the wakeup event
*/
wakeup(): IfVisible;
/**
* Register any event
* @param name Name of the event
* @param callback Function to run when event fires
*/
on(name: string, callback: (status?: string) => void): number;
/**
* Unregister given event of name
* @param name name of the event
* @param handler function to remove from registered events
*/
off(name: string, handler: Function): void;
/**
* Unregister all event of given name
* @param name Name to unregister all events of
*/
off(name: string): void;
/**
* Returns the current duration time in milliseconds
*/
getIdleDuration(): number;
/**
* Returns detailed information about current idle status
*/
getIdleInfo(): IdleInfo;
/**
* Given the event, it check if page is in that state for example
* ifvisible.now('idle') return boolean to state if you are idle or not
*/
now(check: string): boolean;
/**
* Tells if page is visible or not at the moment
*/
now(): boolean;
/**
* Utility to run a given function at every given seconds intervals.
* This method is smart and it will stop executing when the page is not active
* @param seconds duration to wait between each interval in seconds
* @param callback callback function run on every iteration
*/
onEvery(seconds: number, callback: () => void): onEveryReturn;
/**
* Let's you change duration that page becomes idle dynamically
* @param seconds new duration in seconds
*/
setIdleDuration(seconds: number): number;
}
declare var ifvisible: IfVisible;
declare module 'ifvisible' {
export = ifvisible;
}
|
define(
[
"pinpin/app"
],
function(PinpinApp) {
"use strict";
PinpinApp.module("HeaderApp", function(HeaderApp, PinpinApp, Backbone, Mn, $, _) {
var API = {
showHeader: function() {
require(["pinpin/apps/header/header_controller"], function(HeaderController) {
HeaderController.showHeader();
});
}
};
HeaderApp.on("start", function() {
console.log("HeaderApp start");
API.showHeader();
})
});
return PinpinApp.HeaderApp;
}
);
|
package com.twu.biblioteca;
public class BibliotecaApp {
private BookAndMovieDatabase bookAndMovieDatabase;
private Machine machine;
public BibliotecaApp() {
bookAndMovieDatabase = new BookAndMovieDatabase();
machine = new Machine(bookAndMovieDatabase);
}
public static void main(String[] args) {
BibliotecaApp bibliotecaApp = new BibliotecaApp();
bibliotecaApp.getMachine().display();
}
public BookAndMovieDatabase getBookAndMovieDatabase() {
return bookAndMovieDatabase;
}
public Machine getMachine() {
return machine;
}
}
|
package ru.igla.ferriswheel.sample
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.support.v7.widget.AppCompatSeekBar
import android.text.TextPaint
import android.util.AttributeSet
class TextThumbSeekBar :
AppCompatSeekBar {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, attributeSetId: Int) : super(context, attrs, attributeSetId)
private val thumbSize = context.dpF(16f)
private val textPaint: TextPaint = TextPaint().apply {
color = Color.WHITE
textSize = context.sp(14f)
typeface = Typeface.DEFAULT
textAlign = Paint.Align.CENTER
}
private var bounds = Rect()
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val progressText = progress.toString()
textPaint.getTextBounds(progressText, 0, progressText.length, bounds)
val leftPadding = paddingLeft - thumbOffset
val rightPadding = paddingRight - thumbOffset
val width = width - leftPadding - rightPadding
val progressRatio = progress.toFloat() / max
val thumbOffset = thumbSize * (.5f - progressRatio)
val thumbX = progressRatio * width + leftPadding.toFloat() + thumbOffset
val thumbY = height / 2f + bounds.height() / 2f
canvas.drawText(progressText, thumbX, thumbY, textPaint)
}
private fun Context.sp(sp: Float): Float = sp * resources.displayMetrics.scaledDensity
private fun Context.dpF(dp: Float): Float = dp * resources.displayMetrics.density
}
|
package net.xblacky.animexstream
import android.app.Application
import net.xblacky.animexstream.utils.realm.InitalizeRealm
import timber.log.Timber
class AnimeXStream : Application() {
override fun onCreate() {
super.onCreate()
InitalizeRealm.initializeRealm(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Woosh : MonoBehaviour {
public AnimationCurve curve;
public Text countdown;
private float _elapsedTime;
private bool _processAnim = true;
// Use this for initialization
void Start () {
_elapsedTime = 0;
AudioManager.instance.waterDrop.PlayDelayed (0.1f);
AudioManager.instance.waterDrop2.PlayDelayed (1.1f);
AudioManager.instance.waterDrop3.PlayDelayed (2.1f);
}
// Update is called once per frame
void Update () {
_elapsedTime += Time.deltaTime;
if(_elapsedTime < 3f)
{
countdown.transform.localScale = Vector3.one * curve.Evaluate(_elapsedTime);
countdown.text = (3f - Mathf.Floor(_elapsedTime)).ToString();
} else if(_processAnim == true)
{
GetComponent<Animator>().Stop();
_processAnim = false;
Game.instance.enableInputs();
AudioManager.instance.mainMusic.Play ();
}
}
public void Reset()
{
_elapsedTime = 0;
_processAnim = true;
GetComponent<Animator>().Play("321Animation");
}
}
|
module Rerebase.Generator
(
ModuleName(..),
ModuleContents(..),
Module(..),
forwardingModule,
generate,
)
where
import Rebase.Prelude
import Rerebase.Generator.Model
import qualified Rerebase.Generator.Templates as A
import qualified System.Directory as B
import qualified System.FilePath as C
import qualified Rebase.Data.Text as D
generate :: List Module -> IO ()
generate modules =
do
B.removeDirectoryRecursive "library"
forM_ modules (uncurry overwriteModule)
D.writeFile "rerebase.cabal" (A.cabal (map fst modules))
D.writeFile "README.md" A.readme
overwriteModule :: ModuleName -> ModuleContents -> IO ()
overwriteModule (ModuleName moduleNameText) (ModuleContents moduleContentsText) =
do
B.createDirectoryIfMissing True directoryPath
D.writeFile filePath moduleContentsText
where
directoryPath =
C.takeDirectory filePath
filePath =
moduleNameText &
D.replace "." "/" &
mappend "library/" &
flip mappend ".hs" &
D.unpack
forwardingModule :: ModuleName -> Module
forwardingModule =
liftA2 (,) id forwardingModuleContents
forwardingModuleContents :: ModuleName -> ModuleContents
forwardingModuleContents name =
ModuleContents (A.forwardingModule name)
|
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.bindingtariffrulingfrontend.repository
import org.mongodb.scala.{MongoCollection, ReadConcern}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.test.Helpers._
import uk.gov.hmrc.bindingtariffrulingfrontend.controllers.forms.SimpleSearch
import uk.gov.hmrc.bindingtariffrulingfrontend.model.Ruling
import uk.gov.hmrc.mongo.test.DefaultPlayMongoRepositorySupport
import java.time._
import scala.concurrent.ExecutionContext.Implicits.global
//scalastyle:off magic.number
class RulingMongoRepositoryTest
extends AnyWordSpecLike
with GuiceOneAppPerSuite
with Matchers
with DefaultPlayMongoRepositorySupport[Ruling] {
private val clock = Clock.tickSeconds(ZoneOffset.UTC)
override protected lazy val repository: RulingMongoRepository = new RulingMongoRepository(mongoComponent)
lazy val readConcern: ReadConcern = ReadConcern.MAJORITY
protected def collection: MongoCollection[Ruling] = repository.collection
val startOfToday: LocalDateTime = LocalDate.now().atStartOfDay
val zoneOffsetToday: ZoneOffset = ZoneId.of("Europe/London").getRules.getOffset(startOfToday)
val today: Instant = startOfToday.toInstant(zoneOffsetToday)
val startOfTomorrow: LocalDateTime = LocalDate.now().plusDays(1).atStartOfDay
val startOfNextMonth: LocalDateTime = LocalDate.now().plusMonths(1).atStartOfDay
val zoneOffsetTomorrow: ZoneOffset = ZoneId.of("Europe/London").getRules.getOffset(startOfTomorrow)
val zoneOffsetNextMonth: ZoneOffset = ZoneId.of("Europe/London").getRules.getOffset(startOfNextMonth)
val tomorrow: Instant = startOfTomorrow.toInstant(zoneOffsetTomorrow)
val nextMonth: Instant = startOfNextMonth.toInstant(zoneOffsetNextMonth)
override def beforeEach(): Unit = {
super.beforeEach()
await(repository.ensureIndexes)
}
override def afterEach(): Unit = {
super.afterEach()
await(repository.collection.drop().toFuture())
}
"Update" should {
"Update One" in {
val document = Ruling(reference = "ref", "code", clock.instant(), tomorrow, "justification", "description")
givenAnExistingDocument(document)
val update = document.copy(bindingCommodityCode = "code")
await(repository.update(update, upsert = false)) shouldBe update
}
}
"Delete by Reference" should {
"Delete One" in {
givenAnExistingDocument(
Ruling(reference = "ref1", "code", clock.instant(), tomorrow, "justification", "description")
)
givenAnExistingDocument(
Ruling(reference = "ref2", "code", clock.instant(), tomorrow, "justification", "description")
)
await(repository.delete("ref1"))
thenTheDocumentCountShouldBe(1)
}
}
"Delete Many" should {
"Delete All" in {
givenAnExistingDocument(
Ruling(reference = "ref1", "code", clock.instant(), tomorrow, "justification", "description")
)
givenAnExistingDocument(
Ruling(reference = "ref2", "code", clock.instant(), tomorrow, "justification", "description")
)
await(repository.deleteAll())
thenTheDocumentCountShouldBe(0)
}
}
"Get by Reference" should {
"Retrieve None" in {
await(repository.get("some id")) shouldBe None
}
"Retrieve One" in {
// Given
val document = Ruling(reference = "ref", "code", clock.instant(), tomorrow, "justification", "description")
givenAnExistingDocument(document)
await(repository.get("ref")) shouldBe Some(document)
}
}
"Get by SimpleSearch" should {
"Retrieve None" in {
await(repository.get(SimpleSearch(Some("ref"), imagesOnly = false, 1, 100))).results shouldBe Seq.empty
}
"Retrieve Multiple - no query" in {
// Given
val document1 = Ruling(reference = "ref1", "0", clock.instant(), tomorrow, "justification", "exacting")
val document2 = Ruling(reference = "ref2", "0", clock.instant(), tomorrow, "justification", "exactly")
val document3 = Ruling(reference = "ref3", "0", clock.instant(), tomorrow, "justification", "fountain pen")
givenAnExistingDocument(document1)
givenAnExistingDocument(document2)
givenAnExistingDocument(document3)
await(repository.get(SimpleSearch(Some("0"), imagesOnly = false, 1, 100))).results shouldBe Seq(
document1,
document2,
document3
)
}
"Retrieve One - by Reference - exact match" in {
// Given
val document1 = Ruling(reference = "ref1", "0", clock.instant(), tomorrow, "justification", "description")
val document2 = Ruling(reference = "ref11", "0", clock.instant(), tomorrow, "justification", "description")
givenAnExistingDocument(document1)
givenAnExistingDocument(document2)
await(repository.get(SimpleSearch(Some("ref1"), imagesOnly = false, 1, 100))).results shouldBe Seq(document1)
}
"Retrieve One - by Commodity Code - starts with" in {
// Given
val document1 = Ruling(reference = "ref1", "00", clock.instant(), tomorrow, "justification", "description")
val document2 = Ruling(reference = "ref2", "10", clock.instant(), tomorrow, "justification", "description")
givenAnExistingDocument(document1)
givenAnExistingDocument(document2)
await(repository.get(SimpleSearch(Some("0"), imagesOnly = false, 1, 100))).results shouldBe Seq(document1)
}
"Retrieve One - by Goods Description - case insensitive" in {
// Given
val document1 = Ruling(reference = "ref1", "0", clock.instant(), tomorrow, "justification", "fountain pen")
val document2 = Ruling(reference = "ref2", "0", clock.instant(), tomorrow, "justification", "laptop")
givenAnExistingDocument(document1)
givenAnExistingDocument(document2)
await(repository.get(SimpleSearch(Some("FOUNTAIN"), imagesOnly = false, 1, 100))).results shouldBe Seq(document1)
await(repository.get(SimpleSearch(Some("lapTOP"), imagesOnly = false, 1, 100))).results shouldBe Seq(document2)
}
"Retrieve Multiple - by Goods Description - word stems" in {
// Given
val document1 = Ruling(reference = "ref1", "0", clock.instant(), nextMonth, "justification", "exacting")
val document2 = Ruling(reference = "ref2", "0", clock.instant(), tomorrow, "justification", "exactly")
val document3 = Ruling(reference = "ref3", "0", clock.instant(), tomorrow, "justification", "fountain pen")
givenAnExistingDocument(document1)
givenAnExistingDocument(document2)
givenAnExistingDocument(document3)
await(repository.get(SimpleSearch(Some("exact"), imagesOnly = false, 1, 100))).results shouldBe Seq(
document1,
document2
)
}
"Retrieve One - by Goods Description - images only" in {
// Given
val document1 =
Ruling(
reference = "ref1",
"0",
clock.instant(),
tomorrow,
"justification",
"exacting",
images = Seq("id1, id2")
)
val document2 = Ruling(reference = "ref2", "0", clock.instant(), tomorrow, "justification", "exactly")
val document3 = Ruling(reference = "ref3", "0", clock.instant(), tomorrow, "justification", "fountain pen")
givenAnExistingDocument(document1)
givenAnExistingDocument(document2)
givenAnExistingDocument(document3)
await(repository.get(SimpleSearch(Some("exact"), imagesOnly = true, 1, 100))).results shouldBe Seq(document1)
}
}
private def givenAnExistingDocument(ruling: Ruling): Unit =
await(repository.update(ruling, upsert = true))
private def thenTheDocumentCountShouldBe(count: Int): Unit =
await(repository.collection.countDocuments().toFuture()) shouldBe count
}
|
---
permalink: /
title: "Ben is writing"
excerpt: "Home"
author_profile: true
redirect_from:
- /about/
- /about.html
---
Hello! I'm writing. Look at my smiling face
Read and follow along.
|
;;
;; ANSI COMMON LISP: 7. Objects
;;
;;
;; Macro DEFMETHOD
;;
;;
;; defmethod
;;
(defgeneric defmethod-1 ())
(defmethod defmethod-1 ()
:hello)
(deftest defmethod.1
(defmethod-1)
:hello)
(defgeneric defmethod-2 ())
(deftest defmethod.2
(closp
(defmethod defmethod-2 ()))
t)
(defgeneric defmethod-3 (a))
(defmethod defmethod-3 (a)
(+ a 10))
(deftest defmethod.3
(defmethod-3 111)
121)
(defgeneric defmethod-4 (a))
(defmethod defmethod-4 (a)
(+ a 10))
(defmethod defmethod-4 ((a string))
(concatenate 'string "abc" a))
(deftest defmethod.4
(defmethod-4 100)
110)
(deftest defmethod.5
(defmethod-4 "def")
"abcdef")
(defgeneric defmethod-6 (a))
(defmethod defmethod-6 (a)
(+ a 10))
(defmethod defmethod-6 ((a string))
(+ (length a) (call-next-method 1000)))
(deftest defmethod.6
(defmethod-6 30)
40)
(deftest defmethod.7
(defmethod-6 "Hello")
1015)
(defgeneric defmethod-8 (a))
(defmethod defmethod-8 (a)
(declare (ignore a))
(next-method-p))
(defmethod defmethod-8 ((a string))
(declare (ignore a))
(next-method-p))
(deftest defmethod.8
(defmethod-8 30)
nil)
(deftest defmethod.9
(defmethod-8 "Hello")
t)
(deftest defmethod.10
(progn
(defgeneric defmethod-10 ())
(typep
(defmethod defmethod-10 ())
'standard-method))
t)
(deftest defmethod-setf.1
(progn
(defgeneric (setf defmethod-setf-1) ())
(typep
(defmethod (setf defmethod-setf-1) ())
'standard-method))
t)
(defvar *defmethod-qualifier*)
(deftest defmethod-qualifier.1
(progn
(defgeneric defmethod-qualifier-1 ())
(defmethod defmethod-qualifier-1 :before ()
(push :aaa *defmethod-qualifier*)
10)
(defmethod defmethod-qualifier-1 ()
(push :bbb *defmethod-qualifier*)
20)
(let (*defmethod-qualifier*)
(values
(defmethod-qualifier-1)
(nreverse *defmethod-qualifier*))))
20 (:aaa :bbb))
(deftest defmethod-declaration.1
(progn
(defgeneric defmethod-declaration-1 (x))
(defmethod defmethod-declaration-1 (x)
(declare (special x))
x)
(defmethod-declaration-1 100))
100)
(deftest defmethod-documentation.1
(progn
(defgeneric defmethod-documentation-1 (x))
(documentation
(defmethod defmethod-documentation-1 (x)
(declare (ignore x))
"Hello"
(+ 10 20 30))
't))
"Hello")
;;
;; new generic
;;
(deftest defmethod-new.1
(progn
(fmakunbound 'defmethod-new-1)
(defmethod defmethod-new-1 (x y)
(+ 100 x y))
(defmethod-new-1 11 22))
133)
(deftest defmethod-new.2
(typep
#'defmethod-new-1
'standard-generic-function)
t)
(deftest defmethod-new.3
(class-name
(generic-function-method-class
#'defmethod-new-1))
standard-method)
(deftest defmethod-new.4
(slot-value
(generic-function-method-combination #'defmethod-new-1)
'lisp-clos::name)
standard)
(defun defmethod-new-5 ())
(deftest-error defmethod-new.5
(defmethod defmethod-new-5 ()))
(defmacro defmethod-new-6 ())
(deftest-error defmethod-new.6
(defmethod defmethod-new-6 ()))
(deftest-error defmethod-new.7
(defmethod load-time-value ()))
(defun (setf defmethod-new-8) ())
(deftest-error defmethod-new.8
(defmethod (setf defmethod-new-8) ()))
;;
;; overwrite
;;
(defgeneric defmethod-overwrite-1 (x))
(defmethod defmethod-overwrite-1 ((x integer))
(declare (ignore x))
:aaa)
(deftest defmethod-overwrite.1
(closp
(defmethod defmethod-overwrite-1 ((x integer))
(declare (ignore x))
:bbb))
t)
(deftest defmethod-overwrite.2
(defmethod-overwrite-1 100)
:bbb)
;;
;; lambda-list
;;
(deftest-error defmethod-lambda.1
(progn
(defgeneric defmethod-lambda-1 (x))
(defmethod defmethod-lambda-1 ()
:hello)))
(deftest-error defmethod-lambda.2
(progn
(defgeneric defmethod-lambda-2 (x))
(defmethod defmethod-lambda-2 (x y)
(declare (ignore x y))
:hello)))
(deftest-error defmethod-lambda.3
(progn
(defgeneric defmethod-lambda-3 (x &optional y))
(defmethod defmethod-lambda-3 (x y)
(declare (ignore x y))
:hello)))
(deftest-error defmethod-lambda.4
(progn
(defgeneric defmethod-lambda-4 (x y))
(defmethod defmethod-lambda-4 (x &optional y)
(declare (ignore x y))
:hello)))
(deftest defmethod-lambda.5
(progn
(defgeneric defmethod-lambda-5 (x &rest args))
(defmethod defmethod-lambda-5 (x &key)
(declare (ignore x))
:hello)
(defmethod-lambda-5 10))
:hello)
(deftest-error defmethod-lambda.6
(progn
(defgeneric defmethod-lambda-6 (x &key))
(defmethod defmethod-lambda-6 (x)
(declare (ignore x y))
:hello)))
(deftest defmethod-block.1
(progn
(defgeneric defmethod-block-1 (x))
(defmethod defmethod-block-1 (x)
(return-from defmethod-block-1 (+ x 100)))
(defmethod-block-1 200))
300)
(deftest defmethod-block.2
(progn
(defgeneric (setf defmethod-block-2) (x))
(defmethod (setf defmethod-block-2) (x)
(return-from defmethod-block-2 (+ x 500)))
(funcall #'(setf defmethod-block-2) 200))
700)
(deftest defmethod-class.1
(progn
(defclass defmethod-method-class-1 (standard-method) ())
(make-instance 'defmethod-method-class-1)
(defgeneric defmethod-class-1 () (:method-class defmethod-method-class-1))
(let ((x (defmethod defmethod-class-1 ())))
(class-name
(class-of x))))
defmethod-method-class-1)
;;
;; eql-specializer
;;
(defgeneric defmethod-eql-specializer-1 (value))
(defmethod defmethod-eql-specializer-1 (value)
value)
(deftest defmethod-eql-specializer.1
(typep
(defmethod defmethod-eql-specializer-1 ((value (eql 100)))
(format nil "Hello: ~A" value))
'standard-method)
t)
(deftest defmethod-eql-specializer.2
(defmethod-eql-specializer-1 10)
10)
(deftest defmethod-eql-specializer.3
(defmethod-eql-specializer-1 100)
"Hello: 100")
;;
;; Local Function NEXT-METHOD-P
;;
(deftest next-method-p.1
(progn
(defgeneric next-method-p-1 ())
(defmethod next-method-p-1 ()
(next-method-p))
(next-method-p-1))
nil)
(deftest next-method-p.2
(progn
(defgeneric next-method-p-2 (x))
(defmethod next-method-p-2 ((x real))
(declare (ignore x))
:real)
(defmethod next-method-p-2 ((x integer))
(declare (ignore x))
(next-method-p))
(values
(next-method-p-2 1.23)
(next-method-p-2 100)))
:real t)
(deftest-error next-method-p.3
(eval '(progn
(defgeneric next-method-p-3 ())
(defmethod next-method-p-3 ()
(next-method-p 100))
(next-method-p-3))))
(deftest next-method-p.4
(flet ((next-method-p () :hello))
(declare (ignorable #'next-method-p))
(defgeneric next-method-p-4 ())
(defmethod next-method-p-4 ()
(next-method-p))
(next-method-p-4))
nil)
;;
;; Local Function CALL-NEXT-METHOD
;;
(deftest call-next-method.1
(progn
(defgeneric call-next-method-1 (x))
(defmethod call-next-method-1 ((x integer))
(declare (ignore x))
(call-next-method))
(defmethod call-next-method-1 ((x real))
(declare (ignore x))
:hello)
(call-next-method-1 100))
:hello)
(deftest call-next-method.2
(progn
(defgeneric call-next-method-2 (x))
(defmethod call-next-method-2 ((x integer))
(declare (ignore x))
(call-next-method))
(defmethod call-next-method-2 ((x real))
(declare (ignore x))
(values 10 20 30))
(call-next-method-2 100))
10 20 30)
(deftest call-next-method.3
(progn
(defgeneric call-next-method-3 (x))
(defmethod call-next-method-3 ((x integer))
(list* :integer x (call-next-method)))
(defmethod call-next-method-3 ((x real))
(list :real x))
(call-next-method-3 100))
(:integer 100 :real 100))
(deftest-error call-next-method.4
(progn
(defgeneric call-next-method-4 ())
(defmethod call-next-method-4 ()
(call-next-method))
(call-next-method-4)))
(deftest call-next-method.5
(progn
(defgeneric call-next-method-5 ())
(defmethod call-next-method-5 ()
(if (next-method-p)
(call-next-method)
:error))
(call-next-method-5))
:error)
(deftest call-next-method.6
(progn
(sysctl 'recovery 'no-next-method)
(defmethod no-next-method
((x standard-generic-function) (y standard-method) &rest args)
(declare (ignore x y args))
:hello)
(defgeneric call-next-method-6 ())
(defmethod call-next-method-6 ()
(call-next-method))
(prog1 (call-next-method-6)
(sysctl 'recovery 'no-next-method)))
:hello)
(deftest call-next-method-standard.1
(progn
(defgeneric call-next-method-standard-1 (x))
(defmethod call-next-method-standard-1 :around ((x integer))
(declare (ignore x))
(+ 10 (call-next-method)))
(defmethod call-next-method-standard-1 :around ((x real))
(declare (ignore x))
(+ 20 (call-next-method)))
(defmethod call-next-method-standard-1 ((x real))
(+ 30 x))
(call-next-method-standard-1 100))
160)
(deftest-error call-next-method-standard.2
(progn
(defgeneric call-next-method-standard-2 (x))
(defmethod call-next-method-standard-2 :before ((x integer))
(declare (ignore x))
(call-next-method))
(defmethod call-next-method-standard-2 :before ((x real))
(declare (ignore x))
111)
(defmethod call-next-method-standard-2 ((x real))
x)
(call-next-method-standard-2 100)))
(deftest-error call-next-method-standard.3
(progn
(defgeneric call-next-method-standard-3 (x))
(defmethod call-next-method-standard-3 :after ((x integer))
(declare (ignore x))
222)
(defmethod call-next-method-standard-3 :after ((x real))
(declare (ignore x))
(call-next-method))
(defmethod call-next-method-standard-3 ((x real))
x)
(call-next-method-standard-3 100)))
(deftest call-next-method-rest.1
(progn
(defgeneric call-next-method-rest-1 (x))
(defmethod call-next-method-rest-1 ((x integer))
(declare (ignore x))
(call-next-method 10))
(defmethod call-next-method-rest-1 ((x real))
(1+ x))
(call-next-method-rest-1 999))
11)
(deftest-error call-next-method-rest.2
(progn
(defgeneric call-next-method-rest-2 (x))
(defmethod call-next-method-rest-2 ((x integer))
(declare (ignore x))
(call-next-method 10 20 30))
(defmethod call-next-method-rest-2 ((x real))
(1+ x))
(call-next-method-rest-2 999)))
(deftest call-next-method-rest.3
(progn
(defgeneric call-next-method-rest-3 (x y &optional z))
(defmethod call-next-method-rest-3 ((x integer) y &optional z)
(declare (ignore x y z))
(call-next-method 10 20 30))
(defmethod call-next-method-rest-3 ((x real) y &optional (z 999))
(values x y z))
(call-next-method-rest-3 888 777 666))
10 20 30)
(deftest call-next-method-rest.4
(progn
(defgeneric call-next-method-rest-4 (x y &optional z))
(defmethod call-next-method-rest-4 ((x integer) y &optional z)
(declare (ignore x y z))
(call-next-method 10 20))
(defmethod call-next-method-rest-4 ((x real) y &optional (z 999))
(values x y z))
(call-next-method-rest-4 888 777 666))
10 20 999)
(deftest-error call-next-method-error.1
(eval '(call-next-method)))
(deftest-error call-next-method-error.2
(progn
(defgeneric call-next-method-error-2 (x y))
(defmethod call-next-method-error-2 ((x integer) y)
(declare (ignore x y z))
(call-next-method 10 20 30))
(defmethod call-next-method-error-2 ((x real) y)
(values x y))
(call-next-method-error-2 888 777 666)))
|
package com.datawizards.dmg.metadata
import java.util.Date
case class WorkExperience(
start: Date,
end: Date,
jobTitle: String,
company: Company
)
|
package trigger
import (
"github.com/TIBCOSoftware/flogo-lib/core/action"
"github.com/TIBCOSoftware/flogo-lib/core/data"
"strconv"
"time"
)
// Config is the configuration for a Trigger
type Config struct {
Name string `json:"name"`
Id string `json:"id"`
Ref string `json:"ref"`
Settings map[string]interface{} `json:"settings"`
Output map[string]interface{} `json:"output"`
Handlers []*HandlerConfig `json:"handlers"`
// Deprecated: Use Output
Outputs map[string]interface{} `json:"outputs"`
}
func (c *Config) FixUp(metadata *Metadata) {
//for backwards compatibility
if len(c.Output) == 0 {
c.Output = c.Outputs
}
// fix up top-level outputs
for name, value := range c.Output {
attr, ok := metadata.Output[name]
if ok {
newValue, err := data.CoerceToValue(value, attr.Type())
if err != nil {
//todo handle error
} else {
c.Output[name] = newValue
}
}
}
// fix up handler outputs
for _, hc := range c.Handlers {
hc.parent = c
//for backwards compatibility
if hc.ActionId == "" {
hc.ActionId = strconv.Itoa(time.Now().Nanosecond())
}
//for backwards compatibility
if len(hc.Output) == 0 {
hc.Output = hc.Outputs
}
// fix up outputs
for name, value := range hc.Output {
attr, ok := metadata.Output[name]
if ok {
newValue, err := data.CoerceToValue(value, attr.Type())
if err != nil {
//todo handle error
} else {
hc.Output[name] = newValue
}
}
}
}
}
func (c *Config) GetSetting(setting string) string {
val, exists := data.GetValueWithResolver(c.Settings, setting)
if !exists {
return ""
}
strVal, err := data.CoerceToString(val)
if err != nil {
return ""
}
return strVal
}
type HandlerConfig struct {
parent *Config
Settings map[string]interface{} `json:"settings"`
Output map[string]interface{} `json:"output"`
Action *action.Config
// Deprecated: Use Action (*action.Config)
ActionId string `json:"actionId"`
// Deprecated: Use Action (*action.Config)
ActionMappings *data.IOMappings `json:"actionMappings,omitempty"`
// Deprecated: Use Action (*action.Config)
ActionOutputMappings []*data.MappingDef `json:"actionOutputMappings,omitempty"`
// Deprecated: Use Action (*action.Config)
ActionInputMappings []*data.MappingDef `json:"actionInputMappings,omitempty"`
// Deprecated: Use Output
Outputs map[string]interface{} `json:"outputs"`
}
func (hc *HandlerConfig) GetSetting(setting string) string {
val, exists := data.GetValueWithResolver(hc.Settings, setting)
if !exists {
return ""
}
strVal, err := data.CoerceToString(val)
if err != nil {
return ""
}
return strVal
}
|
#!/bin/bash
echo "Deploy Script"
git stash --all
git remote add fury https://chwcode:$FURY_API_TOKEN@git.fury.io/chwcode/travis-hello.git
git push fury master
|
# This file was generated, do not modify it. # hide
@show false_positive(cm)
@show accuracy(ŷ, y) |> r3
@show accuracy(cm) |> r3 # same thing
@show precision(ŷ, y) |> r3
@show recall(ŷ, y) |> r3
@show f1score(ŷ, y) |> r3
|
---
title: sign() - Azure 数据资源管理器 | Microsoft Docs
description: 本文介绍 Azure 数据资源管理器中的 sign()。
services: data-explorer
author: orspod
ms.author: v-tawe
ms.reviewer: rkarlin
ms.service: data-explorer
ms.topic: reference
origin.date: 02/13/2020
ms.date: 08/06/2020
ms.openlocfilehash: 70835d65a3ac29fbd2dd93aa8f37467ec661d154
ms.sourcegitcommit: 7ceeca89c0f0057610d998b64c000a2bb0a57285
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 08/06/2020
ms.locfileid: "87841490"
---
# <a name="sign"></a>sign()
数值表达式的符号
**语法**
`sign(`*x*`)`
**参数**
* x:一个实数。
**返回**
* 指定表达式的正号 (+1)、零 (0) 或负号 (-1)。
**示例**
```kusto
print s1 = sign(-42), s2 = sign(0), s3 = sign(11.2)
```
|s1|s2|s3|
|---|---|---|
|-1|0|1|
|
part of 'speech_bloc.dart';
class SpeechState extends Equatable {
const SpeechState({
required this.coordinate,
required this.listening,
});
final String coordinate;
final bool listening;
SpeechState copyWith({
String? coordinate,
bool? listening,
}) {
return SpeechState(
coordinate: coordinate ?? this.coordinate,
listening: listening ?? this.listening,
);
}
@override
List<Object?> get props => [coordinate];
}
|
# Welcome to steam.py's documentation!
steam.py is a modern, easy to use, and async ready API wrapper for the Steam API and its CMs. Heavily inspired by
[discord.py](https://github.com/Rapptz/discord.py) and borrowing functionality from
[ValvePython/steam](https://github.com/ValvePython/steam).
## Key Features
- Modern Pythonic API using `async`/`await` syntax
- Command extension to aid with bot creation
- Easy to use with an object-oriented design
- Fully typed hinted for faster development
## Getting help
- These are good pages to start with if it's your first time see {doc}`quickstart` & {doc}`faq`
- Ask us in our {resource}`discord <discord>` server.
- If you're looking for something specific, try the {ref}`index <genindex>` or {ref}`searching <search>`.
- Report bugs in the {resource}`issue tracker <issues>`.
## API references
Pages detailing the API.
```{toctree}
:maxdepth: 1
steam API Reference <api>
steam.ext.commands API Reference <ext/commands/api.rst>
```
## Extensions
steam.py has extension modules to help with common tasks.
```{toctree}
:maxdepth: 1
ext/commands/index.rst
```
|
package org.cmucreatelab.android.flutterprek.database.models.db_file;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import java.util.List;
/**
* Created by tasota on 10/18/2018.
*
* DbFileDAO
*
* Data access object for {@link DbFile}. See Room persistence library documentation for details:
* https://developer.android.com/training/data-storage/room/accessing-data
*/
@Dao
public interface DbFileDAO {
@Insert
void insert(DbFile dbFile);
@Insert
void insert(List<DbFile> dbFiles);
@Delete
void delete(DbFile dbFile);
@Query("SELECT * FROM db_files")
LiveData<List<DbFile>> getAllDbFiles();
@Query("SELECT * FROM db_files WHERE uuid = :dbFileUuid LIMIT 1")
LiveData<DbFile> getDbFile(String dbFileUuid);
@Query("SELECT * FROM db_files WHERE file_type = :type")
LiveData<List<DbFile>> getDbFilesOfType(String type);
}
|
#!/bin/bash
CPUREV=$(cat /sys/devices/soc0/soc_id)
if [ $CPUREV == "i.MX8MP" ]
then
echo "config sysrepo-tsn related components"
else
exit 0
fi
CMD=$1
if [ $CMD == "start" ]; then
/etc/init.d/sysrepo-init ${CMD}
/etc/init.d/sysrepod ${CMD}
/etc/init.d/sysrepo-plugind ${CMD}
/etc/init.d/sysrepo-tsnd ${CMD}
/etc/init.d/netopeer2-server ${CMD}
else
/etc/init.d/netopeer2-server ${CMD}
/etc/init.d/sysrepo-tsnd ${CMD}
/etc/init.d/sysrepo-plugind ${CMD}
/etc/init.d/sysrepod ${CMD}
fi
exit 0
|
package com.wangduwei.asm.source.part6
import com.wangduwei.asm.source.utils.ClassOutputUtil
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.tree.ClassNode
class RemoveMethodDemo {
fun test() {
}
}
fun main() {
val classReader = ClassReader("com.wangduwei.asm.source.part6.RemoveMethodDemo")
val classNode = ClassNode()
classReader.accept(classNode, ClassReader.SKIP_DEBUG)
val removeMethod = RemoveMethodTransformer("test", "()V")
removeMethod.transform(classNode)
// 尝试输出进行查看
val classWriter = ClassWriter(ClassWriter.COMPUTE_MAXS)
classNode.accept(classWriter)
//输出文件查看
ClassOutputUtil.byte2File("asm_example/files/RemoveMethodDemo.class", classWriter.toByteArray())
}
|
# frozen_string_literal: true
module Devtools
module Flay
# Measure flay mass relative to size of duplicated sexps
class Scale
include Adamantium
include Anima.new(:minimum_mass, :files)
include Procto.call(:measure)
# Measure duplication mass
#
# @return [Array<Rational>]
#
# @api private
def measure
flay.masses.map do |hash, mass|
Rational(mass, flay.hashes.fetch(hash).size)
end
end
# Report flay output
#
# @return [undefined]
#
# @api private
def flay_report
flay.report
end
private
# Memoized flay instance
#
# @return [Flay]
#
# @api private
def flay
::Flay.new(mass: minimum_mass).tap do |flay|
flay.process(*files)
flay.analyze
end
end
memoize :flay, freezer: :noop
end
# Expand include and exclude file settings for flay
class FileList
include Procto.call, Concord.new(:includes, :excludes)
GLOB = '**/*.{rb,erb}'
# Expand includes and filter by excludes
#
# @return [Set<Pathname>]
#
# @api private
def call
include_set - exclude_set
end
private
# Set of excluded files
#
# @return [Set<Pathname>]
#
# @api private
def exclude_set
excludes.flat_map(&Pathname.method(:glob))
end
# Set of included files
#
# Expanded using flay's file expander which takes into
# account flay's plugin support
#
# @return [Set<Pathname>]
#
# @api private
def include_set
Set.new(flay_includes.map(&method(:Pathname)))
end
# Expand includes using flay
#
# Expanded using flay's file expander which takes into
# account flay's plugin support
#
# @return [Array<String>]
#
# @api private
def flay_includes
PathExpander.new(includes.dup, GLOB).process
end
end
end
end
|
const MIN = 3;
const MAX = 8;
function isValidDate (a, b) {
const min = new Date(a);
const max = new Date(a);
min.setDate(min.getDate() + MIN);
max.setDate(max.getDate() + MAX);
return b >= min && b <= max;
}
export default isValidDate;
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class Field extends StatefulWidget {
final TextEditingController controller;
final TextInputType? keyboardType;
final FocusNode? focusNode;
final bool readonly;
final bool clearable;
final bool autofocus;
final List<TextInputFormatter>? inputFormatters;
final Widget? prefixWidget;
final Widget? suffixWidget;
final TextStyle? style;
final String type;
final int rows;
final String? hintText;
final TextStyle? hintStyle;
final bool isDense;
final bool showEyes;
final Color? iconColor;
final TextAlign? textAlign;
final int? maxLength;
final TextStyle? counterStyle;
final ValueChanged<String>? onSubmitted;
final ValueChanged<String>? onChanged;
const Field(
{Key? key,
required this.controller,
this.keyboardType,
this.focusNode,
this.readonly: false,
this.clearable: true,
this.autofocus: false,
this.inputFormatters,
this.prefixWidget,
this.suffixWidget,
this.style,
this.type: "text",
this.rows: 2,
this.hintText,
this.hintStyle,
this.isDense: true,
this.showEyes: true,
this.maxLength,
this.counterStyle,
this.onSubmitted,
this.onChanged,
this.iconColor,
this.textAlign})
: super(key: key);
@override
_FieldState createState() => _FieldState();
}
class _FieldState extends State<Field> {
bool _isShowPwd = false;
bool _isShowDelete = false;
@override
void initState() {
super.initState();
_isShowDelete = widget.controller.text.isNotEmpty;
widget.controller.addListener(() {
if (mounted) {
setState(() {
_isShowDelete = widget.controller.text.isNotEmpty;
});
}
});
}
Widget buildRight() {
return Container(
child: Row(
children: <Widget>[
widget.clearable && _isShowDelete ? SizedBox(width: 10) : Container(),
widget.clearable && _isShowDelete
? GestureDetector(
child: Icon(Icons.cancel,
size: 16.0,
color: widget.iconColor ?? const Color(0xffc8c9cc)),
onTap: () {
widget.controller.text = '';
},
)
: Container(),
if (widget.type == "password") SizedBox(width: 10),
widget.type == "password" && widget.showEyes
? GestureDetector(
child: Icon(
!_isShowPwd ? Icons.visibility_off : Icons.visibility,
size: 16.0,
color: widget.iconColor ?? const Color(0xff969799)),
onTap: () {
setState(() {
_isShowPwd = !_isShowPwd;
});
},
)
: Container(),
],
),
);
}
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
if (widget.prefixWidget != null) widget.prefixWidget!,
Expanded(
child: TextField(
maxLength: widget.maxLength,
controller: widget.controller,
focusNode: widget.focusNode,
keyboardType: widget.keyboardType,
autofocus: widget.autofocus,
readOnly: widget.readonly,
textAlign: widget.textAlign ?? TextAlign.start,
maxLines: widget.type == "textarea" ? widget.rows : 1,
style: widget.style ??
TextStyle(
fontSize: 12,
color: Colors.black,
),
inputFormatters: widget.inputFormatters,
obscureText: widget.type == "password" ? !_isShowPwd : false,
decoration: InputDecoration(
isDense: widget.isDense,
hintText: widget.hintText,
counterStyle: widget.counterStyle,
hintStyle: widget.hintStyle ??
TextStyle(
color: const Color(0xFFD3D3D3),
fontSize: 12,
),
border: InputBorder.none,
),
onSubmitted: widget.onSubmitted,
onChanged: widget.onChanged,
),
),
buildRight(),
if (widget.suffixWidget != null) widget.suffixWidget!,
],
);
}
}
|
import { Box, DefaultTheme } from '@chakra-ui/core';
import { css } from '@emotion/core';
import styled from '@emotion/styled';
import { transparentize } from 'polished';
interface IContainerProps {
theme: DefaultTheme;
isErrored: boolean;
}
export const Container = styled(Box)<IContainerProps>`
--errored-box-shadow: 0 0 0 3px
${props => transparentize(0.4, props.theme.colors.red[500])};
${props =>
props.isErrored &&
css`
box-shadow: var(--errored-box-shadow);
`}
`;
|
package gchat.usermessage;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.github.javafaker.Faker;
import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Locale;
@Configuration
@EnableDynamoDBRepositories(basePackages ={"gchat.usermessage","gchat.lastseen", "gchat.groupmessage"})
public class DynamoDBConfig {
@Value("${amazon.dynamodb.endpoint}")
String endpoint;
@Value("${amazon.aws.accesskey}")
String accesskey;
@Value("${amazon.aws.secretkey}")
String secretkey;
@Value("${amazon.aws.region}")
String region;
public AwsClientBuilder.EndpointConfiguration endpointConfiguration() {
return new AwsClientBuilder.EndpointConfiguration(endpoint, region);
}
public AWSCredentialsProvider awsCredentialsProvider() {
return new AWSStaticCredentialsProvider(new BasicAWSCredentials(accesskey, secretkey));
}
@Bean
public AmazonDynamoDB amazonDynamoDB() {
return AmazonDynamoDBClientBuilder
.standard()
.withEndpointConfiguration(endpointConfiguration())
.withCredentials(awsCredentialsProvider())
.build();
}
@Bean
public Faker faker() {
return new Faker(new Locale("en-US"));
}
}
|
-- |
-- Module: Sound.Accents.GenAm.IPA
-- Description: convert IPA symbols to GenAm sounds
-- Copyright: (c) 2019 Ben Spalding (bnspalding.com)
-- License: MIT
-- Stability: experimental
--
-- GenAm.IPA provides tools for converting strings of IPA symbols into sounds.
-- This is currently very much embedded in the "Sound.GenAm" mapping, which
-- means that certain symbols mean different things than they would in IPA
-- (mostly the symbols used for vowels).
module Sound.Accents.GenAm.IPA
( stringToIPASounds,
textToIPASounds,
normalize,
)
where
import Data.List
import Data.Ord
import qualified Data.Set as Set
import qualified Data.Text as T
import Sound
import qualified Sound.Accents.GenAm as GenAm
import Sound.Stress
import Text.Replace
-- | stringToIPASounds converts a string into GenAm sounds. Non-IPA symbols
-- passed to stringToIPASounds will produce errors
stringToIPASounds :: String -> Maybe [Sound]
stringToIPASounds str =
let toIPAIter sounds [] = Just sounds
toIPAIter sounds xs =
case mSound of
Just sound -> toIPAIter (sounds ++ [sound]) remaining
Nothing -> Nothing
where
(mSound, remaining) = nextSound xs ipaSymbols
in toIPAIter [] (normalize str)
-- | textToIPASounds converts text into GenAm sounds. Non-IPA symbols passed to
-- textToIPASounds will produce errors
textToIPASounds :: T.Text -> Maybe [Sound]
textToIPASounds t = stringToIPASounds $ T.unpack t
-- | normalize performs a series of replacements on a string to simplify the IPA
-- symbols present in the string. Multi-character symbols (like tʃ or eɪ) are
-- joined with tie (becoming t͡ʃ and e͡ɪ respectively). A separate rhotic mark
-- (ə˞) is preferred over single symbols (ɚ) or an inverted r (əɹ) to mark
-- r-colored vowels. Whitespace is removed from the string.
normalize :: String -> String
normalize =
let r = replaceWithTrie
in r replNonChar . r replThrd . r replSnd . r replFst . r replZero
-- NOTE: the string is searched for replacements left to right, and longer
-- replacements are preferred over shorter ones. In some cases (r's, ɜ's) a certain
-- number of successive replacements (see "normalize") is required to get things
-- right. This is not the greatest, and should be perhaps reworked later.
-- NOTE: really, instead of replacing on symbols, we should be replacing on
-- sounds in order to reduce to GenAm. However, that requires that we recognize
-- all of the IPA sounds and then reduce, which is a good bit more work.
replZero :: Trie
replZero =
listToTrie
[ Replace (s "r") "ɹ",
Replace (s "ɾ̃") "d",
Replace (s "ɽ") "d",
Replace (s "ɾ") "ɹ",
Replace (s "ɻ") "ɹ",
Replace (s "ɭ") "l",
Replace (s "ɬ") "ʃ", -- ll from Welsh, I'm uncertain on this one
Replace (s "ʋ") "w", -- or 'v', see "Hindustani phonology" wiki page
Replace (s "t͡s") "ts",
Replace (s "t͡ʃ̩̩") "t͡ʃ", --there's a syllablize symbol on the bottom there
Replace (s "ɸ") "f",
Replace (s "ᵊ") "ə",
Replace (s "ɘ") "e",
Replace (s " ̯") "",
Replace (s "u̯") "u",
Replace (s "ʉ") "u",
Replace (s "ʊ̯") "ʊ",
Replace (s "ʊ̂") "ʊ",
Replace (s "ø") "ʊ", -- I'm torn on this judgement
Replace (s "ô") "o",
Replace (s "ə̯") "ə",
Replace (s "ɪ̯") "ɪ",
Replace (s "ä") "a",
Replace (s "ä") "a",
Replace (s "ɪ̈") "ɪ",
Replace (s "ă") "a",
Replace (s "ɔ̃") "ɔ",
Replace (s "ɑ̃") "ɑ",
Replace (s "ɒ̃") "ɑ",
Replace (s "ã") "æ",
Replace (s "æ̃") "æ",
Replace (s "æ̰") "æ",
Replace (s "ɛ̃") "ɛ",
Replace (s "õ") "o",
Replace (s "ʌ̃") "ʌ",
Replace (s "ē") "i", --long e
Replace (s "ē") "i",
Replace (s "ā") "a",
Replace (s "t̬") "t",
Replace (s "ʲ") "j",
Replace (s "ɕ") "ʃ",
Replace (s "ɲ") "ŋ",
Replace (s "ɱ") "m",
Replace (s " ̬") "",
Replace (s " ̃") "",
Replace (s " ̪") "",
Replace (s "ɪ̪") "",
Replace (s "ʊ̪") "ʊ",
Replace (s "t̪") "t",
Replace (s " ̚") "",
Replace (s "k̚") "k",
Replace (s "p̚") "p",
Replace (s "t̚") "t",
Replace (s "ɥ") "h",
Replace (s "ɦ") "h",
Replace (s "ː") "",
Replace (s "ˑ") "",
Replace (s "ʷ") "", -- quick judgement
Replace (s "ʰ") "",
Replace (s "(") "", -- remove all parens
Replace (s ")") "",
Replace (s " ͡") "", -- remove existing ones. replace the ones we want
Replace (s "o͡") "o",
Replace (s "e͡") "e",
Replace (s "a͡") "a",
Replace (s "‿") "",
Replace (s " ̥") "",
Replace (s "&") "" -- this is a nonsense symbol, used in replacements [b]
]
replFst :: Trie
replFst =
listToTrie
[ Replace (s "ɒ") "ɑ",
Replace (s "ʀ") "ɹ",
Replace (s "ɹ̥") "ɹ",
Replace (s "ɐ") "ə", -- this is a quick judgement
Replace (s "e") "ə", -- partially reversed later [a]
Replace (s "a") "æ", -- partially reversed later [c]
Replace (s "ɵ") "ə", -- quick judgement
Replace (s "n̩") "ən",
Replace (s "ô") "o",
Replace (s "l̩") "əl",
Replace (s "ɫ̩") "əl",
Replace (s "ɹ̩") "əɹ",
Replace (s "m̩") "əm",
Replace (s "ɨ") "ɪ",
Replace (s "ĭ") "ɪ", -- quick judgement
Replace (s "ɫ") "l",
Replace (s "ʍ") "w",
Replace (s "χ") "h", -- quick judgement. consider relation to ʁ
Replace (s "ʁ") "", -- alternatively, this could possibly be syllablized as ə
Replace (s "x") "h",
Replace (s "y") "j",
Replace (s "ç") "k", -- quick judgement
Replace (s "(ɹ)") "ɹ", --all parens should already be removed
Replace (s "(t)") "t",
Replace (s "/") "",
Replace (s "ʔ") "",
Replace (s "-") "",
Replace (s "æɹ") "ɛɹ", -- from Wiktionary's pronunciation guide, see [2]
Replace (s "ɛɪ") "eɪ",
Replace (s "əʊ") "oʊ",
Replace (s "o") "oʊ", -- partially reduced below [d]
Replace (s "ɜː") "ɜɹ", -- This is for UK pronunciations (might be a mistake)
Replace (s "ɜ") "&", -- replace reverse epsilon with nonsense symbol [b]
Replace (s "ɑ˞") "ɑɹ",
Replace (s "œ") "u" -- quick judgement
]
replSnd :: Trie
replSnd =
listToTrie
[ Replace (s "əɪ") "eɪ", -- reversing the e swap above [a]
Replace (s "&ɹ") "ɜ˞", -- reversals for reverse epsilon [b]
Replace (s "&˞") "ɜ˞", -- [b]
Replace (s "&") "ɛ", -- & used to not extend switch to instances of 'ɛ' [b]
Replace (s "æɪ") "aɪ", -- reversing the ash swap above [c]
Replace (s "æu") "aʊ", -- [c]
Replace (s "æʊ") "aʊ", -- [c]
Replace (s "oʊʊ") "oʊ", -- reversing doubles from [d]
Replace (s "au") "aʊ", -- old replacement, should be redundant, see [c]
Replace (s "c") "k" -- there seem to be quite a few c's that should be k's
]
replThrd :: Trie
replThrd =
listToTrie
[ Replace (s "oʊ") "o͡ʊ",
Replace (s "eɪ") "e͡ɪ",
Replace (s "aɪ") "a͡ɪ", -- note some ligatures render a+͡ as ɑ, it is a+͡
Replace (s "ɔɪ") "ɔ͡ɪ",
Replace (s "aʊ") "a͡ʊ",
Replace (s "ɚ") "ə˞",
Replace (s "ɝ") "ɜ˞",
Replace (s "ɜɹ") "ɜ˞",
Replace (s "əɹ") "ə˞",
Replace (s "ɛəɹ") "ɛɹ", -- case "air", should be 1 syllable
Replace (s "ɪəɹ") "ɪɹ", -- case "hear", should be 1 syllable
Replace (s "ɛə˞") "ɛɹ",
Replace (s "ɛ˞") "ɛɹ",
Replace (s "tʃ") "t͡ʃ",
Replace (s "dʒ") "d͡ʒ"
]
replNonChar :: Trie
replNonChar =
listToTrie
[ Replace (s " ") "",
Replace (s "\r") "",
Replace (s "\t") "",
Replace (s "\n") "",
Replace (s "˞˞") "˞", -- handle double rhotics (typos in wiktionary?)
Replace (s ".ˌ") "ˌ",
Replace (s ".ˈ") "ˈ", -- stress mark AND sylbreak causes double sylbreak
Replace (s "ˌ.") "ˌ",
Replace (s "ˈ.") "ˈ" -- stress mark AND sylbreak causes double sylbreak
]
s :: String -> String'
s = string'fromString
-- Note [1]: in the normalizing of r-colored vowels, it's possible to overreach
-- and affect ɹ's on the other side of a syllable divide (ex. derivate :
-- /dɛɹɪveɪt/ -> dɛ.ɹɪ.veɪt, not dɛ(ɹ).ɪ.veɪt).
-- Note [2]: see https://en.wiktionary.org/wiki/Appendix:English_pronunciation
stressSymbols :: [String]
stressSymbols = T.unpack . T.singleton <$> [stressSymbolIPA, secondaryStressSymbolIPA]
syllableBreakSymbol :: String
syllableBreakSymbol = "."
ipaSymbols :: [String]
ipaSymbols =
( sortOn (Down . length)
. (++) (syllableBreakSymbol : stressSymbols)
. Set.toList
. Set.map (\(Sound x) -> T.unpack x)
)
GenAm.sounds
nextSound :: String -> [String] -> (Maybe Sound, String)
nextSound [] _ = error "empty list given to nextSound in Sound.IPA"
nextSound xs [] = (Nothing, xs) -- unknown symbol
nextSound xs (sym : syms) =
if sym `isPrefixOf` xs
then (Just (Sound (T.pack sym)), drop (length sym) xs)
else nextSound xs syms
|
require 'mconnect/helpers'
module Mconnect
class Authorizer
include Helpers
attr_writer :verifier
def initialize
oauth_options = load_yaml "#{Dir.home}/.mconnect/config.yml"
client_options = { :site => oauth_options['site'],
:authorize_path => '/oauth/authorize',
:request_token_path => '/oauth/request_token',
:access_token_path => '/oauth/access_token' }
@client = OAuth::Consumer.new(
oauth_options['consumer_key'],
oauth_options['consumer_secret'],
client_options
)
end
def access_token
access_token = load_yaml "#{Dir.home}/.mconnect/authorization.yml"
OAuth::AccessToken.new(@client, access_token.token, access_token.secret)
end
def request_token
@request_token ||= @client.get_request_token
end
def authorize_url
request_token.authorize_url
end
def authorization
request_token.get_access_token(oauth_verifier: @verifier)
end
end
end
|
#!/bin/bash -l
#PBS -l walltime=95:00:00,nodes=1:ppn=8,mem=150gb
#PBS -q ram256g
#PBS -m abe
#PBS -M eriks074@umn.edu
#PBS -N CaringBridge_SNA_Inds
#PBS -o /home/srivbane/eriks074/repos/sna-social-support/visualization/qsub-scripts/rc.stdout
#PBS -e /home/srivbane/eriks074/repos/sna-social-support/visualization/qsub-scripts/rc.stderr
working_dir="/home/srivbane/eriks074/repos/sna-social-support/visualization/qsub-scripts"
cd $working_dir
echo "In '$working_dir', running the graph generation script."
python3 revised_components.py
echo "Finished."
|
package simyukkuri.geometry
/**
* xy平面上の不変な点.
*/
data class PositionXY(override val x: Double, override val y: Double) : HasPositionXY {
override val position: PositionXY
get() = this
/** 各成分に指定された値を加えた点を返す. */
fun add(x: Double, y: Double) = PositionXY(this.x + x, this.y + y)
}
|
{-# language FlexibleContexts #-}
{-# language PatternSynonyms #-}
{-# language RankNTypes #-}
module Check.Kind
( checkKind
, inferKind
)
where
import Control.Lens.Getter ((^.))
import Control.Lens.Lens (Lens')
import Control.Monad.Except (MonadError, throwError)
import Control.Monad.State.Strict (MonadState)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
import Error.TypeError (TypeError(..))
import IR (Kind(..))
import Syntax (Span, TypeM, pattern TypeM, unTypeM, typemSpan)
import qualified Syntax
import Unify.KMeta (HasKindMetas, freshKMeta)
import Unify.Kind (unifyKind)
import Unify.TMeta (HasTypeMetas, getTMetaKind)
checkKind ::
( MonadState (s ty) m, HasTypeMetas s, HasKindMetas (s ty)
, MonadError TypeError m
) =>
Map Text Kind ->
Lens' ty Span ->
(ty -> Kind) ->
TypeM ty ->
Kind ->
m ()
checkKind kindScope spans kinds ty k = do
k' <- inferKind kindScope kinds ty
let sp = ty ^. typemSpan spans
unifyKind sp k k'
inferKind ::
( MonadState (s ty) m, HasTypeMetas s, HasKindMetas (s ty)
, MonadError TypeError m
) =>
Map Text Kind ->
(ty -> Kind) ->
TypeM ty ->
m Kind
inferKind kindScope kinds ty =
case unTypeM ty of
Syntax.TVar (Left m) -> do
mk <- getTMetaKind m
case mk of
Nothing -> error $ "Missing " <> show mk
Just k -> pure k
Syntax.TVar (Right a) -> pure $ kinds a
Syntax.TApp sp a b -> do
aK <- inferKind kindScope kinds (TypeM a)
bK <- inferKind kindScope kinds (TypeM b)
meta <- freshKMeta
let expected = KArr bK (KVar meta)
unifyKind sp expected aK
pure $ KVar meta
Syntax.TInt32{} -> pure KType
Syntax.TBool{} -> pure KType
Syntax.TPtr{} -> pure $ KArr KType KType
Syntax.TFun{} -> pure $ KArr KType KType
Syntax.TName sp n ->
case Map.lookup n kindScope of
Nothing -> throwError $ TNotInScope sp
Just k -> pure k
|
/**
* @see https://github.com/andymark-by/click-outside-vue3
*/
import vClickOutside from 'click-outside-vue3'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(vClickOutside)
})
|
#!/bin/sh
R_HOME=/home/galaxy/opt/R-3.4.0-Shared/lib/R
export R_HOME
LD_LIBRARY_PATH=/home/galaxy/opt/R-3.4.0-Shared/lib/R/lib
export LD_LIBRARY_PATH
PATH=.:/home/galaxy/opt/R-3.4.0-Shared/bin:/home/galaxy/opt/jdk1.8.0_45/bin:$PATH
|
WORK_DIR=$(dirname $0)
psql -f ${WORK_DIR}/migrations/drop_dbs.sql -U postgres
|
package constant
// FormatJpeg is the format string for jpeg
var FormatJpeg = "jpeg"
// FormatPng is the format string for png
var FormatPng = "png"
|
#include <iostream>
#include <bits/stdc++.h>
#include<numeric>
#include <algorithm>
#define ll long long int
using namespace std;
void Fast()
{
cin.tie(0);
cin.sync_with_stdio(0);
}
int main()
{
Fast(); //File_Input();
int n, k; cin >> n >> k;
vector<int> v;
for (int i = 0; i < n; ++i)
{
int temp; cin >> temp;
v.emplace_back(temp);
}
sort(v.rbegin(), v.rend());
int hours;
for (auto &it : v)
{
if(k % it == 0)
{
hours = k / it;
break;
}
}
cout << hours;
return 0;
}
|
create table if not exists params (
id serial primary key,
name varchar(2000) unique,
value timestamp
);
|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Whether two doubles are within a given distance of each other.
///
/// The `epsilon` argument must be positive and not null.
/// The `a` and `b` arguments may be null. A null value is only considered
/// near-equal to another null value.
bool nearEqual(double? a, double? b, double epsilon) {
assert(epsilon != null);
assert(epsilon >= 0.0);
if (a == null || b == null) {
return a == b;
}
return (a > (b - epsilon)) && (a < (b + epsilon)) || a == b;
}
/// Whether a double is within a given distance of zero.
///
/// The epsilon argument must be positive.
bool nearZero(double a, double epsilon) => nearEqual(a, 0.0, epsilon);
|
package com.phelat.splash.remote.api
import com.phelat.splash.remote.di.DaggerNetworkComponent
import com.phelat.splash.remote.di.NetworkModule
import com.phelat.splash.remote.utils.TestUtils
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class PhotosAPITest {
private lateinit var mockWebServer: MockWebServer
private lateinit var api: PhotosAPI
@Before
fun setUp() {
mockWebServer = MockWebServer()
mockWebServer.start()
val networkComponent = DaggerNetworkComponent.builder()
.networkModule(NetworkModule("http://" + mockWebServer.hostName + ":" + mockWebServer.port))
.build()
api = networkComponent.photosAPI()
}
@Test
fun `test if it maps the server result to appropriate data classes`() {
val response = MockResponse()
response.setResponseCode(200)
response.setBody(TestUtils.readResource("json/photos/photos_response.json", this.javaClass.classLoader))
mockWebServer.enqueue(response)
api.getPhotos(0, 10, sig = 123)
.test()
.assertNoErrors()
.assertValue {
it.size == 10 && it[0].user != null && it[0].urls != null && it[0].user?.profileImage != null
}
.assertComplete()
}
@After
fun tearDown() {
mockWebServer.shutdown()
}
}
|
//go:build unittest
// +build unittest
package storkctl
import (
"testing"
"github.com/libopenstorage/stork/pkg/version"
"github.com/stretchr/testify/require"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func TestVersion(t *testing.T) {
f := NewTestFactory()
streams, _, buf, _ := genericclioptions.NewTestIOStreams()
cmd := newVersionCommand(f, streams)
cmd.SetOutput(buf)
cmd.SetArgs([]string{"version"})
err := cmd.Execute()
require.NoError(t, err, "Error executing command: %v", cmd)
require.Equal(t, "storkctl Version: "+version.Version+"\n", buf.String())
}
|
import math
import numpy as np
print('loading vertiport configuration')
def pointy_hex_corner(center, size, i):
angle_deg = 60 * i
angle_rad = math.radians(angle_deg)
return (center[0] + size * math.cos(angle_rad),
center[1] + size * math.sin(angle_rad))
class Config:
# experiment setting
no_episodes = 5
# airspace setting
window_width = 800
window_height = 800
num_aircraft = 10
EPISODES = 1000
G = 9.8
tick = 30
scale = 60 # 1 pixel = 30 meters
# distance param
minimum_separation = 926 / scale
NMAC_dist = 150 / scale
horizon_dist = 4000 / scale
initial_min_dist = 3000 / scale
goal_radius = 600 / scale
# speed
init_speed = 190 / 3.6 / scale
min_speed = 45 / scale
max_speed = 220 / 3.6 / scale
# d_speed = 0 / scale
speed_sigma = 5 / scale
# position_sigma = 0 / scale
# heading in rad TBD
d_heading = math.radians(5)
heading_sigma = math.radians(2)
# power
aircraft_power = 100
# MCTS algorithm
no_simulations = 100
search_depth = 3
no_simulations_lite = 30
search_depth_lite = 2
simulate_frame = 10
# reward setting
NMAC_penalty = -10
conflict_penalty = -5
wall_penalty = -5
step_penalty = -0.01
goal_reward = 20
sparse_reward = True
# point
point_len = 4
point = np.array([[-point_len, -point_len],
[point_len, -point_len],
[point_len, point_len],
[-point_len, point_len],
[-point_len, -point_len]])
# vertiport parameter
time_interval_lower = 60
time_interval_upper = 180
vertiport_loc = np.zeros([7, 2])
vertiport_center = np.array([window_width / 2, window_height / 2])
vertiport_loc[0, :] = vertiport_center
for i in range(1, 7):
vertiport_loc[i, :] = pointy_hex_corner(vertiport_center, size=300, i=i)
|
create or replace procedure assert_eq( tActual in varchar2, tExpected in varchar2 ) is
tExpectedReplaced varchar2( 4000 ) := replace( tExpected, '<USER>', user );
begin
if tActual = tExpectedReplaced or tActual is null and tExpectedReplaced is null then
return;
end if;
raise_application_error( -20001, 'assertion failed: ' || chr( 10 ) || tActual || chr( 10 ) || tExpectedReplaced );
end;
/
create or replace package APCKG is
procedure PROC;
end;
/
create or replace package body APCKG is
procedure PROC is
procedure "INNER/proc" is
begin
assert_eq( p_stack.whoAmI, '5: <USER>.PACKAGE BODY APCKG.PROCEDURE PROC.PROCEDURE "INNER/proc"' );
assert_eq( p_stack.getSubprogram( p_stack.whoAmI ), 'INNER/proc' );
assert_eq( p_stack.getConcatenatedSubprograms( p_stack.whoAmI ), 'APCKG.PROC."INNER/proc"' );
assert_eq( p_stack.whoCalledMe, '11: <USER>.PACKAGE BODY APCKG.PROCEDURE PROC' );
end;
begin
"INNER/proc";
end;
end;
/
begin
APCKG.PROC;
end;
/
drop package APCKG;
/
declare
procedure inner_proc is
begin
assert_eq( p_stack.whoAmI, '4: <USER>.ANONYMOUS BLOCK.PROCEDURE INNER_PROC' );
end;
begin
inner_proc;
end;
/
declare
procedure outer_proc is
procedure inner_proc is
tCallStack varchar2( 4000 );
tCallLine varchar2( 4000 );
begin
tCallStack := p_stack.getCallStack;
assert_eq( p_stack.getDynamicDepth( tCallStack ), 4 );
tCallLine := p_stack.getCallStackLine( tCallStack, 1 );
assert_eq( p_stack.getLexicalDepth( tCallLine ), 1 );
assert_eq( p_stack.getProgramType( tCallLine ), 'PACKAGE BODY' );
assert_eq( p_stack.getProgram( tCallLine ), 'P_STACK' );
assert_eq( p_stack.getSubprogramType( tCallLine ), 'FUNCTION' );
assert_eq( p_stack.getSubprogram( tCallLine ), 'GETCALLSTACK' );
assert_eq( p_stack.getConcatenatedSubprograms( tCallLine ), 'P_STACK.GETCALLSTACK' );
tCallLine := p_stack.getCallStackLine( tCallStack, 2 );
assert_eq( p_stack.getUnitLine( tCallLine ), 7 );
assert_eq( p_stack.getOwner( tCallLine ), '<USER>' );
assert_eq( p_stack.getLexicalDepth( tCallLine ), 2 );
assert_eq( p_stack.getProgramType( tCallLine ), 'ANONYMOUS BLOCK' );
assert_eq( p_stack.getProgram( tCallLine ), '' );
assert_eq( p_stack.getSubprogramType( tCallLine ), 'PROCEDURE' );
assert_eq( p_stack.getSubprogram( tCallLine ), 'INNER_PROC' );
assert_eq( p_stack.getConcatenatedSubprograms( tCallLine ), 'ANONYMOUS BLOCK.OUTER_PROC.INNER_PROC' );
tCallLine := p_stack.getCallStackLine( tCallStack, 3 );
assert_eq( p_stack.getOwner( tCallLine ), '<USER>' );
assert_eq( p_stack.getLexicalDepth( tCallLine ), 1 );
assert_eq( p_stack.getProgramType( tCallLine ), 'ANONYMOUS BLOCK' );
assert_eq( p_stack.getProgram( tCallLine ), '' );
assert_eq( p_stack.getSubprogramType( tCallLine ), 'PROCEDURE' );
assert_eq( p_stack.getSubprogram( tCallLine ), 'OUTER_PROC' );
assert_eq( p_stack.getConcatenatedSubprograms( tCallLine ), 'ANONYMOUS BLOCK.OUTER_PROC' );
tCallLine := p_stack.getCallStackLine( tCallStack, 4 );
assert_eq( p_stack.getOwner( tCallLine ), '<USER>' );
assert_eq( p_stack.getLexicalDepth( tCallLine ), 0 );
assert_eq( p_stack.getProgramType( tCallLine ), 'ANONYMOUS BLOCK' );
assert_eq( p_stack.getProgram( tCallLine ), '' );
assert_eq( p_stack.getSubprogramType( tCallLine ), 'ANONYMOUS BLOCK' );
assert_eq( p_stack.getSubprogram( tCallLine ), '' );
assert_eq( p_stack.getConcatenatedSubprograms( tCallLine ), 'ANONYMOUS BLOCK' );
tCallLine := p_stack.getCallStackLine( tCallStack, 5 );
assert_eq( p_stack.getUnitLine( tCallLine ), null );
assert_eq( p_stack.getOwner( tCallLine ), null );
assert_eq( p_stack.getLexicalDepth( tCallLine ), 0 );
assert_eq( p_stack.getProgramType( tCallLine ), 'PACKAGE' );
assert_eq( p_stack.getProgram( tCallLine ), null );
assert_eq( p_stack.getSubprogramType( tCallLine ), null );
assert_eq( p_stack.getSubprogram( tCallLine ), null );
assert_eq( p_stack.getConcatenatedSubprograms( tCallLine ), null );
end;
begin
inner_proc;
end;
begin
outer_proc;
end;
/
create or replace package JAVA_PKG is
procedure begin_test;
procedure test_java is
language java name 'TestClass.Method1()';
procedure end_test;
end;
/
create or replace package body JAVA_PKG is
procedure begin_test is
begin
assert_eq( p_stack.whoAmI, '4: <USER>.PACKAGE BODY JAVA_PKG.PROCEDURE BEGIN_TEST' );
end;
procedure test_java_1 is
language java name 'TestClass.Method1()';
procedure test_java_2 is
language java name 'TestClass.Method2(java.lang.String)';
procedure end_test is
begin
assert_eq( p_stack.whoAmI, '12: <USER>.PACKAGE BODY JAVA_PKG.PROCEDURE END_TEST' );
end;
end;
/
begin
JAVA_PKG.begin_test;
JAVA_PKG.end_test;
end;
/
drop package JAVA_PKG;
/
create or replace package EMPTY_DECLARE_PKG is
procedure GOOD;
procedure BAD;
end;
/
create or replace package body EMPTY_DECLARE_PKG is
procedure GOOD is
tCallStack varchar2( 4000 );
begin
declare
t number;
begin
null;
end;
tCallStack := p_stack.getCallStack(2);
assert_eq( p_stack.getConcatenatedSubprograms( tCallStack ), 'EMPTY_DECLARE_PKG.GOOD' );
end;
procedure BAD is
tCallStack varchar2( 4000 );
begin
declare
begin
null;
end;
tCallStack := p_stack.getCallStack(2);
assert_eq( p_stack.getConcatenatedSubprograms( tCallStack ), 'EMPTY_DECLARE_PKG.BAD' );
end;
end;
/
begin
EMPTY_DECLARE_PKG.GOOD;
EMPTY_DECLARE_PKG.BAD;
end;
/
drop package EMPTY_DECLARE_PKG;
/
drop procedure assert_eq;
|
#!/bin/bash -eE
# (C) Sergey Tyurin 2021-03-15 15:00:00
# Disclaimer
##################################################################################################################
# You running this script/function means you will not blame the author(s)
# if this breaks your stuff. This script/function is provided AS IS without warranty of any kind.
# Author(s) disclaim all implied warranties including, without limitation,
# any implied warranties of merchantability or of fitness for a particular purpose.
# The entire risk arising out of the use or performance of the sample scripts and documentation remains with you.
# In no event shall author(s) be held liable for any damages whatsoever
# (including, without limitation, damages for loss of business profits, business interruption,
# loss of business information, or other pecuniary loss) arising out of the use of or inability
# to use the script or documentation. Neither this script/function,
# nor any part of it other than those parts that are explicitly copied from others,
# may be republished without author(s) express written permission.
# Author(s) retain the right to alter this disclaimer at any time.
##################################################################################################################
BUILD_STRT_TIME=$(date +%s)
echo
echo "############################## FreeTON Rnode Tools build script ##################################"
echo "+++INFO: $(basename "$0") BEGIN $(date +%s) / $(date)"
SCRIPT_DIR=`cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P`
source "${SCRIPT_DIR}/env.sh"
source "${SCRIPT_DIR}/functions.shinc"
FEXEC_FLG="-executable"
OS_SYSTEM=`uname -s`
if [[ "$OS_SYSTEM" == "FreeBSD" ]];then
FEXEC_FLG="-perm +111"
fi
#=====================================================
# Build rnode console
[[ ! -z ${RCONS_SRC_DIR} ]] && rm -rf "${RCONS_SRC_DIR}"
git clone --recurse-submodules "${RCONS_GIT_REPO}" $RCONS_SRC_DIR
cd $RCONS_SRC_DIR
git checkout "${RCONS_GIT_COMMIT}"
cargo build --release
find $RCONS_SRC_DIR/target/release/ -maxdepth 1 -type f ${FEXEC_FLG} -exec cp -f {} $HOME/bin/ \;
echo
BUILD_END_TIME=$(date +%s)
Build_mins=$(( (BUILD_END_TIME - BUILD_STRT_TIME)/60 ))
Build_secs=$(( (BUILD_END_TIME - BUILD_STRT_TIME)%60 ))
echo "+++INFO: $(basename "$0") FINISHED $(date +%s) / $(date)"
echo "Builds took $Build_mins min $Build_secs secs"
echo "================================================================================================"
exit 0
|
using System.Diagnostics;
using System.Threading.Tasks;
namespace TabletFriend.Actions
{
public class CmdAction : ButtonAction
{
private readonly string _cmd;
public CmdAction(string cmd)
{
_cmd = cmd;
}
public async override Task Invoke()
{
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C " + _cmd;
process.StartInfo = startInfo;
process.Start();
}
}
}
|
package nl.pvanassen.highchart.api.utils;
import java.util.ArrayList;
import nl.pvanassen.highchart.api.base.GsonHelper;
import nl.pvanassen.highchart.api.shared.Jsonify;
public class JsonArray<E>
extends ArrayList<E>
implements Jsonify {
private static final long serialVersionUID = 1L;
public E getItem(int index) {
return get(index);
}
public Integer getLength() {
return size();
}
public int length() {
return size();
}
public JsonArray<E> pushElement(E value) {
pushItem(value);
return this;
}
public void pushItem(E value) {
add(value);
}
public JsonArray<E> setElement(int index, E value) {
setItem(index, value);
return this;
}
public void setItem(int index, E value) {
if (size() > index) {
set(index, value);
}
else if (size() == index) {
add(index, value);
}
else {
while (size() < index) {
add(null);
}
add(index, value);
}
}
@Override
public String toJson() {
return GsonHelper.toJson(this);
}
}
|
using System;
using System.Diagnostics;
namespace ReactGraph.PerfTests
{
class Program
{
public static void Main()
{
Console.WriteLine("Warm up...");
var data = new Data();
var algoGraph = new AlgoGraph(data);
RunWithGraph(algoGraph);
data = new Data();
var algoManual = new AlgoManual(data);
RunManually(algoManual);
Console.WriteLine("Running tests...");
Stopwatch sw;
int gc0;
const int runs = 3;
double sumGraphOpsPerSeconds = 0;
for (int i = 0; i < runs; i++)
{
data = new Data();
algoGraph = new AlgoGraph(data);
gc0 = GC.CollectionCount(0);
sw = Stopwatch.StartNew();
var ops = RunWithGraph(algoGraph);
var opsPerSecond = ops / sw.Elapsed.TotalSeconds;
sumGraphOpsPerSeconds += opsPerSecond;
Console.WriteLine("Run with graph: {0:F1}ops/sec, GC0: {1}", opsPerSecond, GC.CollectionCount(0) - gc0);
}
double sumManualOpsPerSeconds = 0;
for (int i = 0; i < runs; i++)
{
data = new Data();
algoManual = new AlgoManual(data);
gc0 = GC.CollectionCount(0);
sw = Stopwatch.StartNew();
var ops = RunManually(algoManual);
var opsPerSecond = ops / sw.Elapsed.TotalSeconds;
sumManualOpsPerSeconds += opsPerSecond;
Console.WriteLine("Run manually: {0:F1}ops/sec, GC0: {1}", opsPerSecond, GC.CollectionCount(0) - gc0);
}
Console.WriteLine();
Console.WriteLine("Graph is {0:F}x slower than manual code.", sumManualOpsPerSeconds / sumGraphOpsPerSeconds);
Console.ReadKey();
}
static int RunManually(AlgoManual algo)
{
const int iterations = 1000;
for (int i = 0; i < iterations; i++)
{
algo.Run();
}
// Console.WriteLine(algo.Data._499_1);
return iterations;
}
static int RunWithGraph(AlgoGraph algo)
{
const int iterations = 100;
for (int i = 0; i < iterations; i++)
{
algo.Run();
}
// Console.WriteLine(algo.Data._499_1);
return iterations;
}
}
}
|
<?php declare(strict_types=1);
namespace Swoft\Log\Helper;
use ReflectionException;
use function sprintf;
use Swoft\Bean\BeanFactory;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Log\Logger;
class Log
{
/**
* @param string $message
* @param array $params
*
* @return bool
* @throws ReflectionException
* @throws ContainerException
*/
public static function emergency(string $message, ...$params): bool
{
return self::getLogger()->emergency(sprintf($message, ...$params));
}
/**
* @param string $message
* @param array $params
*
* @return bool
* @throws ReflectionException
* @throws ContainerException
*/
public static function debug(string $message, ...$params): bool
{
if (APP_DEBUG) {
return self::getLogger()->debug(sprintf($message, ...$params));
}
return true;
}
/**
* @param string $message
* @param array $params
*
* @return bool
* @throws ReflectionException
* @throws ContainerException
*/
public static function alert(string $message, ...$params): bool
{
return self::getLogger()->alert(sprintf($message, ...$params));
}
/**
* @param string $message
* @param array $params
*
* @return bool
* @throws ReflectionException
* @throws ContainerException
*/
public static function info(string $message, ...$params): bool
{
return self::getLogger()->info(sprintf($message, ...$params));
}
/**
* @param string $message
* @param array $params
*
* @return bool
* @throws ReflectionException
* @throws ContainerException
*/
public static function warning(string $message, ...$params): bool
{
return self::getLogger()->warning(sprintf($message, ...$params));
}
/**
* @param string $message
* @param array $params
*
* @return bool
* @throws ReflectionException
* @throws ContainerException
*/
public static function error(string $message, ...$params): bool
{
return self::getLogger()->error(sprintf($message, ...$params));
}
/**
* Push log
*
* @param string $key
* @param mixed $val
*
* @throws ReflectionException
* @throws ContainerException
*/
public static function pushLog(string $key, $val): void
{
self::getLogger()->pushLog($key, $val);
}
/**
* Profile start
*
* @param string $name
* @param array $params
*
* @throws ReflectionException
* @throws ContainerException
*/
public static function profileStart(string $name, ...$params): void
{
self::getLogger()->profileStart(sprintf($name, ...$params));
}
/**
* @param string $name
* @param int $hit
* @param int|null $total
*
* @throws ReflectionException
* @throws ContainerException
*/
public static function counting(string $name, int $hit, int $total = null): void
{
self::getLogger()->counting($name, $hit, $total);
}
/**
* Profile end
*
* @param string $name
* @param array $params
*
* @throws ReflectionException
* @throws ContainerException
*/
public static function profileEnd(string $name, ...$params): void
{
self::getLogger()->profileEnd(sprintf($name, ...$params));
}
/**
* @return Logger
* @throws ReflectionException
* @throws ContainerException
*/
public static function getLogger(): Logger
{
return BeanFactory::getBean('logger');
}
}
|
import sbt.{Resolver, _}
import sbt.librarymanagement.MavenRepository
/** Advxml Created by geirolad on 26/07/2019.
*
* @author
* geirolad
*/
object Resolvers {
lazy val all: Seq[MavenRepository] = Seq(
Resolver.sonatypeRepo("public"),
Resolver.sonatypeRepo("snapshots"),
Resolver.sonatypeRepo("releases"),
"Maven repo1" at "https://repo1.maven.org/",
"Maven repo2" at "https://mvnrepository.com/artifact"
)
}
|
/*
* Copyright (c) 2020 the spinner contributors.
* See the project homepage at: https://jkobejs.github.io/spinner/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spinner.template
import spinner.ansi.{Attribute, BackgroundColor, ForegroundColor}
import fastparse._, NoWhitespace._
object Parser {
def spinner[_: P]: P[Key] = P("spinner").map(_ => Key.Spinner)
def msg[_: P]: P[Key] = P("msg").map(_ => Key.Message)
def elapsed_precise[_: P]: P[Key] = P("elapsed_precise").map(_ => Key.ElapsedPrecise)
def elapsed[_: P]: P[Key] = P("elapsed").map(_ => Key.Elapsed)
def prefix[_: P]: P[Key] = P("prefix").map(_ => Key.Prefix)
def bar[_: P]: P[Key] = P("bar").map(_ => Key.Bar)
def length[_: P]: P[Key] = P("len").map(_ => Key.Length)
def position[_: P]: P[Key] = P("pos").map(_ => Key.Position)
def eta[_: P]: P[Key] = P("eta").map(_ => Key.Eta)
def etaPrecise[_: P]: P[Key] = P("eta_precise").map(_ => Key.EtaPrecise)
def bytes[_: P]: P[Key] = P("bytes").map(_ => Key.Bytes)
def totalBytes[_: P]: P[Key] = P("total_bytes").map(_ => Key.TotalBytes)
def key[_: P]: P[Key] =
P(
spinner | msg | elapsed_precise | elapsed | prefix | bar | length
| position | etaPrecise | eta | totalBytes | bytes)
// Foreground Color
def black[_: P]: P[ForegroundColor] = P("black").map(_ => ForegroundColor.Black)
def red[_: P]: P[ForegroundColor] = P("red").map(_ => ForegroundColor.Red)
def green[_: P]: P[ForegroundColor] = P("green").map(_ => ForegroundColor.Green)
def yellow[_: P]: P[ForegroundColor] = P("yellow").map(_ => ForegroundColor.Yellow)
def magenta[_: P]: P[ForegroundColor] = P("magenta").map(_ => ForegroundColor.Magenta)
def white[_: P]: P[ForegroundColor] = P("white").map(_ => ForegroundColor.White)
def blue[_: P]: P[ForegroundColor] = P("blue").map(_ => ForegroundColor.Blue)
def cyan[_: P]: P[ForegroundColor] = P("cyan").map(_ => ForegroundColor.Cyan)
def brightRed[_: P]: P[ForegroundColor] = P("bright_red").map(_ => ForegroundColor.BrightRed)
def brightGreen[_: P]: P[ForegroundColor] = P("bright_green").map(_ => ForegroundColor.BrightGreen)
def brightYellow[_: P]: P[ForegroundColor] = P("bright_yellow").map(_ => ForegroundColor.BrightYellow)
def brightMagenta[_: P]: P[ForegroundColor] = P("bright_magenta").map(_ => ForegroundColor.BrightMagenta)
def brightBlue[_: P]: P[ForegroundColor] = P("bright_blue").map(_ => ForegroundColor.BrightBlue)
def brightCyan[_: P]: P[ForegroundColor] = P("bright_cyan").map(_ => ForegroundColor.BrightCyan)
def darkGray[_: P]: P[ForegroundColor] = P("dark_gray").map(_ => ForegroundColor.DarkGray)
def lightGray[_: P]: P[ForegroundColor] = P("light_gray").map(_ => ForegroundColor.LightGray)
def foregroundColor[_: P]: P[ForegroundColor] =
P(
black | red | green | yellow | blue | magenta | white | cyan
| brightRed | brightGreen | brightYellow | brightMagenta | brightBlue | brightCyan
| darkGray | lightGray
)
// Background Color
def onBlack[_: P]: P[BackgroundColor] = P("on_black").map(_ => BackgroundColor.Black)
def onRed[_: P]: P[BackgroundColor] = P("on_red").map(_ => BackgroundColor.Red)
def onGreen[_: P]: P[BackgroundColor] = P("on_green").map(_ => BackgroundColor.Green)
def onYellow[_: P]: P[BackgroundColor] = P("on_yellow").map(_ => BackgroundColor.Yellow)
def onMagenta[_: P]: P[BackgroundColor] = P("on_magenta").map(_ => BackgroundColor.Magenta)
def onWhite[_: P]: P[BackgroundColor] = P("on_white").map(_ => BackgroundColor.White)
def onBlue[_: P]: P[BackgroundColor] = P("on_blue").map(_ => BackgroundColor.Blue)
def onCyan[_: P]: P[BackgroundColor] = P("on_cyan").map(_ => BackgroundColor.Cyan)
def onBrightRed[_: P]: P[BackgroundColor] = P("on_bright_red").map(_ => BackgroundColor.BrightRed)
def onBrightGreen[_: P]: P[BackgroundColor] = P("on_bright_green").map(_ => BackgroundColor.BrightGreen)
def onBrightYellow[_: P]: P[BackgroundColor] = P("on_bright_yellow").map(_ => BackgroundColor.BrightYellow)
def onBrightMagenta[_: P]: P[BackgroundColor] = P("on_bright_magenta").map(_ => BackgroundColor.BrightMagenta)
def onBrightBlue[_: P]: P[BackgroundColor] = P("on_bright_blue").map(_ => BackgroundColor.BrightBlue)
def onBrightCyan[_: P]: P[BackgroundColor] = P("on_bright_cyan").map(_ => BackgroundColor.BrightCyan)
def onDarkGray[_: P]: P[BackgroundColor] = P("on_dark_gray").map(_ => BackgroundColor.DarkGray)
def onLightGray[_: P]: P[BackgroundColor] = P("on_light_gray").map(_ => BackgroundColor.LightGray)
def backgroundColor[_: P]: P[BackgroundColor] =
P(
onBlack | onRed | onGreen | onYellow | onBlue | onMagenta | onWhite | onCyan
| onBrightRed | onBrightGreen | onBrightYellow | onBrightBlue | onBrightCyan
| onDarkGray | onLightGray
)
// Alignment
def left[_: P]: P[Alignment] = P("<").map(_ => Alignment.Left)
def center[_: P]: P[Alignment] = P("^").map(_ => Alignment.Center)
def right[_: P]: P[Alignment] = P(">").map(_ => Alignment.Right)
def alignment[_: P]: P[Alignment] = P((left | center | right))
// Width
def width[_: P] = P(CharIn("0-9").rep(1).!.map(_.toInt))
// Attribute
def bold[_: P]: P[Attribute] = P("bold").map(_ => Attribute.Bold)
def underlined[_: P]: P[Attribute] = P("underlined").map(_ => Attribute.Underlined)
def reverse[_: P]: P[Attribute] = P("reverse").map(_ => Attribute.Reverse)
// def dim[_: P]: P[Attribute] = P("dim").map(_ => Attribute.Dim)
// def slowBlink[_: P]: P[Attribute] = P("slow_blink").map(_ => Attribute.SlowBlink)
// def rapidBlink[_: P]: P[Attribute] = P("rapid_blink").map(_ => Attribute.RapidBlink)
// def hidden[_: P]: P[Attribute] = P("hidden").map(_ => Attribute.Hidden)
def attribute[_: P]: P[Attribute] =
P(
bold | underlined | reverse
// | slowBlink | rapidBlink | hidden | dim
)
// Style
def style[_: P] =
P(("." ~ foregroundColor).? ~ ("." ~ backgroundColor).? ~ ("." ~ attribute).rep).map {
case (fgOpt, bgOpt, attrs) => Style(fg = fgOpt, bg = bgOpt, attributes = attrs)
}
// Variable
def variable[_: P]: P[TemplateElement] = P("{" ~ key ~ (":" ~ alignment.? ~ width.? ~ style.?).? ~ "}").map {
case (key, Some((alignmentOpt, widthOpt, styleOpt))) =>
TemplateElement.Var(
key = key,
align = alignmentOpt.getOrElse(Alignment.Left),
width = widthOpt,
style = styleOpt.getOrElse(Style.empty())
)
case (key, _) =>
TemplateElement.Var(
key = key,
align = Alignment.Left,
width = None,
style = Style.empty()
)
}
// def stringChars(c: Char) = c != '{' && c != '}'
def stringChars(c: Char) = c == c
// def value[_: P]: P[TemplateElement] = P(CharsWhile(stringChars).!).map(TemplateElement.Val(_))
def value[_: P]: P[TemplateElement] =
P(AnyChar.!).filter(str => !parse(str, variable(_)).isSuccess).map(TemplateElement.Val(_))
// Template
def template[_: P]: P[Template] =
P(Start ~ (variable | value).rep ~ End).map(Template(_))
}
|
// Copyright 2020 VinyMeuh. All rights reserved.
// Use of the source code is governed by a MIT-style license that can be found in the LICENSE file.
package graphql
import (
"net/http"
"github.com/99designs/gqlgen/handler"
"github.com/vinymeuh/gnucash-graphql/gnucash"
)
// NewHandler returns a new graphql endpoint handler.
func NewHandler(db *gnucash.Database) http.Handler {
return handler.GraphQL(NewExecutableSchema(Config{
Resolvers: &Resolver{
db: db,
},
}))
}
|
## Usage
```js
var Base = require('base');
var env = require('{%= name %}');
var base = new Base();
base.use(env());
```
## API
{%= apidocs("index.js") %}
{%= apidocs("lib/*.js") %}
|
package io.github.dylmeadows.commonkt.javafx.util
interface FxSubscription {
fun cancel()
}
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Role_chk extends CI_Model {
public function __construct()
{
}
public function acl($pram){
$uid=$this->session->userdata('id');
$udata = array( "id" => $uid );
$rid = $this->db->get_where("admin",$udata)->row();
$query=$this->db->query("SELECT * FROM acl WHERE role_id='$rid->role_id' LIMIT 1");
$r=$query->row();
$gets=explode(',',$r->widget);
if (!in_array($pram, $gets)) {
echo 'onclick="alert(\'দুঃখিত !!! আপনার এই লিংক দেখার জন্য অনুমতি নেই। \');return false;"';
}
}
public function acl_url($pram){
$role_id=$this->session->userdata('role_id');
$query=$this->db->query("SELECT * FROM acl WHERE role_id='$role_id' LIMIT 1");
$r=$query->row();
$gets=explode(',',$r->widget);
if (!in_array($pram, $gets)) {
echo '<script>alert("Sorry !!! You have no permission to access this page.");window.history.back();</script>';
exit;
}
}
}
|
(cl:in-package #:gene-mangler.process)
(defmethod run! ((process process))
(iterate
(with population-interface = (population-interface process))
(for population = (population process))
(until (finished-p process population-interface population))
(cycle! process)
(finally (return (population process)))))
(defmethod finished-p/proxy (process/proxy
population-interface/proxy
(process process)
population-interface
population)
(>= (generation process) (maximum-generation process)))
(defmethod cycle! ((process process))
(let ((new-generation (generation:new-generation
(conductor process)
(population-interface process)
(population process))))
(incf (generation process))
(setf (population process) (update-population-after-cycle!
process
(population-interface process)
new-generation)))
process)
(defmethod update-population-after-cycle!/proxy (process/proxy
population-interface/proxy
(process process)
population-interface
population)
population)
|
// Copyright Materialize, Inc. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
use differential_dataflow::operators::arrange::ShutdownButton;
use timely::dataflow::channels::pact::ParallelizationContract;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::operators::generic::{FrontieredInputHandle, OperatorInfo};
use timely::dataflow::{Scope, Stream};
use timely::Data;
pub fn sink_reschedule<G: Scope, D, B, L, P, T>(
s: &Stream<G, D>,
pact: P,
name: &str,
constructor: B,
) -> ShutdownButton<T>
where
D: Data,
B: FnOnce(OperatorInfo) -> (L, ShutdownButton<T>),
L: FnMut(&mut FrontieredInputHandle<G::Timestamp, D, P::Puller>) -> bool + 'static,
P: ParallelizationContract<G::Timestamp, D>,
{
let mut builder = OperatorBuilder::new(name.to_owned(), s.scope());
let operator_info = builder.operator_info();
let mut input = builder.new_input(s, pact);
let (mut logic, button) = constructor(operator_info);
builder.build_reschedule(|_capabilities| {
move |frontiers| {
let mut input_handle = FrontieredInputHandle::new(&mut input, &frontiers[0]);
logic(&mut input_handle)
}
});
button
}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SageMaker.Model
{
/// <summary>
/// Container for the parameters to the UpdateProject operation.
/// Updates a machine learning (ML) project that is created from a template that sets
/// up an ML pipeline from training to deploying an approved model.
///
/// <note>
/// <para>
/// You must not update a project that is in use. If you update the <code>ServiceCatalogProvisioningUpdateDetails</code>
/// of a project that is active or being created, or updated, you may lose resources already
/// created by the project.
/// </para>
/// </note>
/// </summary>
public partial class UpdateProjectRequest : AmazonSageMakerRequest
{
private string _projectDescription;
private string _projectName;
private ServiceCatalogProvisioningUpdateDetails _serviceCatalogProvisioningUpdateDetails;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Gets and sets the property ProjectDescription.
/// <para>
/// The description for the project.
/// </para>
/// </summary>
[AWSProperty(Max=1024)]
public string ProjectDescription
{
get { return this._projectDescription; }
set { this._projectDescription = value; }
}
// Check to see if ProjectDescription property is set
internal bool IsSetProjectDescription()
{
return this._projectDescription != null;
}
/// <summary>
/// Gets and sets the property ProjectName.
/// <para>
/// The name of the project.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=32)]
public string ProjectName
{
get { return this._projectName; }
set { this._projectName = value; }
}
// Check to see if ProjectName property is set
internal bool IsSetProjectName()
{
return this._projectName != null;
}
/// <summary>
/// Gets and sets the property ServiceCatalogProvisioningUpdateDetails.
/// <para>
/// The product ID and provisioning artifact ID to provision a service catalog. The provisioning
/// artifact ID will default to the latest provisioning artifact ID of the product, if
/// you don't provide the provisioning artifact ID. For more information, see <a href="https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html">What
/// is Amazon Web Services Service Catalog</a>.
/// </para>
/// </summary>
public ServiceCatalogProvisioningUpdateDetails ServiceCatalogProvisioningUpdateDetails
{
get { return this._serviceCatalogProvisioningUpdateDetails; }
set { this._serviceCatalogProvisioningUpdateDetails = value; }
}
// Check to see if ServiceCatalogProvisioningUpdateDetails property is set
internal bool IsSetServiceCatalogProvisioningUpdateDetails()
{
return this._serviceCatalogProvisioningUpdateDetails != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// An array of key-value pairs. You can use tags to categorize your Amazon Web Services
/// resources in different ways, for example, by purpose, owner, or environment. For more
/// information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging
/// Amazon Web Services Resources</a>.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=50)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
}
|
<?php
/**
* Copyright © Appboxo. All rights reserved.
* See LICENSE.txt for license details.
*/
namespace Appboxo\Connector\Setup;
use Appboxo\Connector\Model\Data\Connector;
use Magento\Framework\Setup\UninstallInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class Uninstall implements UninstallInterface
{
public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
$setup->getConnection()->dropColumn(
$setup->getTable('quote'),
Connector::COMMENT_FIELD_NAME
);
$setup->getConnection()->dropColumn(
$setup->getTable('sales_order'),
Connector::COMMENT_FIELD_NAME
);
$setup->getConnection()->dropColumn(
$setup->getTable('sales_order_grid'),
Connector::COMMENT_FIELD_NAME
);
$setup->endSetup();
}
}
|
package leetcode;
/**
* https://leetcode.com/problems/diet-plan-performance/
*/
public class Problem1176 {
public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
int answer = 0;
int[] sums = new int[calories.length];
for (int i = 0; i < k; i++) {
sums[k - 1] += calories[i];
}
for (int i = 0, j = k; j < calories.length; i++, j++) {
sums[j] = sums[j - 1] + calories[j] - calories[i];
}
for (int i = k - 1; i < sums.length; i++) {
if (sums[i] < lower) {
answer--;
} else if (sums[i] > upper) {
answer++;
}
}
return answer;
}
}
|
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import defaultdict
import re
from memoized import memoized
from django.utils.translation import ugettext_noop, ugettext
import os
import yaml
import six
from io import open
from corehq.apps.app_manager.util import app_doc_types
from corehq.util.python_compatibility import soft_assert_type_text
PROFILE_SETTINGS_TO_TRANSLATE = [
'name',
'description',
'value_names',
'disabled_txt',
'values_txt',
]
LAYOUT_SETTINGS_TO_TRANSLATE = [
'title'
]
def _translate_setting(setting, prop):
value = setting[prop]
if not isinstance(value, six.string_types):
return [ugettext(v) for v in value]
else:
if six.PY3:
soft_assert_type_text(value)
return ugettext(value)
def _load_custom_commcare_settings():
path = os.path.join(os.path.dirname(__file__), 'static', 'app_manager', 'json')
settings = []
with open(os.path.join(path, 'commcare-profile-settings.yaml'), encoding='utf-8') as f:
for setting in yaml.load(f):
if not setting.get('type'):
setting['type'] = 'properties'
settings.append(setting)
with open(os.path.join(path, 'commcare-app-settings.yaml'), encoding='utf-8') as f:
for setting in yaml.load(f):
if not setting.get('type'):
setting['type'] = 'hq'
settings.append(setting)
for setting in settings:
if not setting.get('widget'):
setting['widget'] = 'select'
for prop in PROFILE_SETTINGS_TO_TRANSLATE:
if prop in setting:
setting[prop] = _translate_setting(setting, prop)
return settings
def _load_commcare_settings_layout(doc_type):
settings = dict([
('{0}.{1}'.format(setting.get('type'), setting.get('id')), setting)
for setting in _load_custom_commcare_settings()
])
path = os.path.join(os.path.dirname(__file__), 'static', 'app_manager', 'json')
with open(os.path.join(path, 'commcare-settings-layout.yaml'), encoding='utf-8') as f:
layout = yaml.load(f)
for section in layout:
# i18n; not statically analyzable
section['title'] = ugettext_noop(section['title'])
for i, key in enumerate(section['settings']):
include = False
setting = settings.pop(key)
if doc_type == 'Application':
include = True
section['settings'][i] = setting
elif doc_type == 'LinkedApplication':
include = setting.get('supports_linked_app', False)
elif doc_type == 'RemoteApp':
include = setting['type'] == 'hq'
else:
raise Exception("Unexpected doc_type received: %s" % doc_type)
section['settings'][i] = setting if include else None
section['settings'] = [_f for _f in section['settings'] if _f]
for setting in section['settings']:
setting['value'] = None
for prop in LAYOUT_SETTINGS_TO_TRANSLATE:
if prop in setting:
setting[prop] = _translate_setting(setting, prop)
if settings:
raise Exception(
"CommCare settings layout should mention "
"all the available settings. "
"The following settings went unmentioned: %s" % (
', '.join(settings)
)
)
return layout
@memoized
def get_custom_commcare_settings():
return _load_custom_commcare_settings()
@memoized
def get_commcare_settings_layout(doc_type):
if doc_type in app_doc_types():
return _load_commcare_settings_layout(doc_type)
raise Exception("Unexpected doc_type received: %s" % doc_type)
@memoized
def get_commcare_settings_lookup():
settings_lookup = defaultdict(lambda: defaultdict(dict))
for setting in get_custom_commcare_settings():
settings_lookup[setting['type']][setting['id']] = setting
return settings_lookup
def parse_condition_string(condition_str):
pattern = re.compile(r"{(?P<type>[\w-]+?)\.(?P<id>[\w-]+?)}=(?P<equals>true|false|'[\w-]+')")
match = pattern.match(condition_str).groupdict()
if match["equals"] == 'true':
match["equals"] = True
elif match["equals"] == 'false':
match["equals"] = False
elif len(match["equals"]) > 1 and match["equals"][0] == "'" and match["equals"][-1] == "'":
match["equals"] = match["equals"][1:-1]
else:
raise Exception("Error parsing contingent condition")
return match
def check_condition(app, condition_str):
cond = parse_condition_string(condition_str)
attr_val = app.get_profile_setting(cond["type"], cond["id"])
return attr_val == cond["equals"] or \
(cond["equals"] == 'true' and attr_val is True) or (cond["equals"] == 'false' and attr_val is False)
def check_contingent_for_circular_dependency(contingent, yaml_lookup, deps=None):
deps = deps or []
cond = parse_condition_string(contingent["condition"])
dep = "%s.%s" % (cond["type"], cond["id"])
if dep in deps:
return True
deps.append(dep)
cond_setting = yaml_lookup[cond["type"]][cond["id"]]
return check_setting_for_circular_dependency(cond_setting, yaml_lookup, deps)
def check_setting_for_circular_dependency(setting, yaml_lookup, deps=None):
deps = deps or []
for contingent in setting.get("contingent_default", []):
if check_contingent_for_circular_dependency(contingent, yaml_lookup, deps):
return True
return False
def circular_dependencies(settings, yaml_lookup):
"""
Checks the settings yaml file for circular dependencies in the contingent_defaults.
This is here that we can test that SETTINGS has no cycles in our test suite.
"""
for s in settings:
if check_setting_for_circular_dependency(s, yaml_lookup):
return True
return False
|
page 20011 "APIV1 - Company Information"
{
APIVersion = 'v1.0';
Caption = 'companyInformation', Locked = true;
DelayedInsert = true;
DeleteAllowed = false;
EntityName = 'companyInformation';
EntitySetName = 'companyInformation';
InsertAllowed = false;
ODataKeyFields = SystemId;
PageType = API;
SaveValues = true;
SourceTable = "Company Information";
Extensible = false;
layout
{
area(content)
{
repeater(Group)
{
field(id; SystemId)
{
Caption = 'id', Locked = true;
Editable = false;
}
field(displayName; Name)
{
Caption = 'displayName', Locked = true;
}
field(address; PostalAddressJSON)
{
Caption = 'address', Locked = true;
ODataEDMType = 'POSTALADDRESS';
ToolTip = 'Specifies the company''s primary business address.';
}
field(phoneNumber; "Phone No.")
{
Caption = 'phoneNumber', Locked = true;
}
field(faxNumber; "Fax No.")
{
Caption = 'faxNumber', Locked = true;
}
field(email; "E-Mail")
{
Caption = 'email', Locked = true;
}
field(website; "Home Page")
{
Caption = 'website', Locked = true;
}
field(taxRegistrationNumber; "VAT Registration No.")
{
Caption = 'taxRegistrationNumber', Locked = true;
}
field(currencyCode; LCYCurrencyCode)
{
Caption = 'currencyCode', Locked = true;
Editable = false;
}
field(currentFiscalYearStartDate; FiscalYearStart)
{
Caption = 'currentFiscalYearStartDate', Locked = true;
Editable = false;
}
field(industry; "Industrial Classification")
{
Caption = 'industry', Locked = true;
}
field(picture; Picture)
{
Caption = 'picture', Locked = true;
Editable = false;
}
field(lastModifiedDateTime; "Last Modified Date Time")
{
Caption = 'lastModifiedDateTime', Locked = true;
}
}
}
}
actions
{
}
trigger OnAfterGetRecord()
begin
SetCalculatedFields();
end;
trigger OnModifyRecord(): Boolean
var
CompanyInformation: Record "Company Information";
GraphMgtCompanyInfo: Codeunit "Graph Mgt - Company Info.";
begin
CompanyInformation.GetBySystemId(SystemId);
GraphMgtCompanyInfo.ProcessComplexTypes(Rec, PostalAddressJSON);
MODIFY(TRUE);
SetCalculatedFields();
end;
trigger OnNewRecord(BelowxRec: Boolean)
begin
ClearCalculatedFields();
end;
var
LCYCurrencyCode: Code[10];
FiscalYearStart: Date;
PostalAddressJSON: Text;
local procedure SetCalculatedFields()
var
AccountingPeriod: Record "Accounting Period";
GeneralLedgerSetup: Record "General Ledger Setup";
GraphMgtCompanyInfo: Codeunit "Graph Mgt - Company Info.";
begin
PostalAddressJSON := GraphMgtCompanyInfo.PostalAddressToJSON(Rec);
GeneralLedgerSetup.GET();
LCYCurrencyCode := GeneralLedgerSetup."LCY Code";
AccountingPeriod.SETRANGE("New Fiscal Year", TRUE);
IF AccountingPeriod.FINDLAST() THEN
FiscalYearStart := AccountingPeriod."Starting Date";
end;
local procedure ClearCalculatedFields()
begin
CLEAR(SystemId);
CLEAR(PostalAddressJSON);
end;
}
|
#!/bin/sh
#
# date-menu.sh
#
# This is in the public domain. Honestly, how can you claim anything to something
# this simple?
#
# Outputs a simple openbox pipe menu to display the date, time, and calendar.
# You need 'date' and 'cal'. You should have these. Additionally, the calendar
# only appears properly formated if you use a mono spaced font.
# Outputs the selected row from the calender output.
# If you don't use a mono spaced font, you would have to play with spacing here.
# It would probably involve a very complicated mess. Is there a way to force a
# different font per menu?
calRow() {
cal|awk -v row=$1 '{ if (NR==row) { print $0 } }'
}
# Build the menu
cat << EOFMENU
<openbox_pipe_menu>
<separator label="`date +%A\ \ \ \ \ \ \ \ \ \ %I\:%M\ %p`" />
<item label="`date +%B\ %d,\ %Y`" />
<separator />
<item label="`calRow 2`" />
<item label="`calRow 3`" />
<item label="`calRow 4`" />
<item label="`calRow 5`" />
<item label="`calRow 6`" />
<item label="`calRow 7`" />
<item label="`calRow 8`" />
</openbox_pipe_menu>
EOFMENU
|
package prov;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class TimeHelper {
private static final DateTimeFormatter XML_DATE_TIME_FORMAT =
ISODateTimeFormat.dateTimeNoMillis();
public TimeHelper() {
}
public String now(){
MutableDateTime dNow = new MutableDateTime(DateTimeZone.UTC);
DateTimeFormatter ft = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss");
return ft.print(dNow);
//2012-03-02T10:30:00
}
public String before(int days){
MutableDateTime now = new MutableDateTime(DateTimeZone.UTC);
DateTime daysAgo = now.toDateTime();
daysAgo=daysAgo.minusDays(days);
DateTimeFormatter ft = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss");
return ft.print(daysAgo);
//2012-03-02T10:30:00
}
public String parseCIS(String text){
DateTime dt = XML_DATE_TIME_FORMAT.parseDateTime(text);
DateTimeFormatter ft = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
return ft.print(dt);
}
public String nowCIS(){
MutableDateTime dNow = new MutableDateTime(DateTimeZone.UTC);
DateTimeFormatter ft = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
return ft.print(dNow);
}
public String getDateCIS(String text){
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime dt = formatter.parseDateTime(text);
DateTimeFormatter ft = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss");
return ft.print(dt);
}
//yyyyMMddHHmm
//"createTime":"201503011826","lastTime":"2015-03-01 18:07:35.735" "timestamp":"2015-03-03 12:44:40.4440"
}
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/devtools/cloudtrace/v1/trace.proto
require 'google/protobuf'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/protobuf/empty_pb'
require 'google/protobuf/timestamp_pb'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/devtools/cloudtrace/v1/trace.proto", :syntax => :proto3) do
add_message "google.devtools.cloudtrace.v1.Trace" do
optional :project_id, :string, 1
optional :trace_id, :string, 2
repeated :spans, :message, 3, "google.devtools.cloudtrace.v1.TraceSpan"
end
add_message "google.devtools.cloudtrace.v1.Traces" do
repeated :traces, :message, 1, "google.devtools.cloudtrace.v1.Trace"
end
add_message "google.devtools.cloudtrace.v1.TraceSpan" do
optional :span_id, :fixed64, 1
optional :kind, :enum, 2, "google.devtools.cloudtrace.v1.TraceSpan.SpanKind"
optional :name, :string, 3
optional :start_time, :message, 4, "google.protobuf.Timestamp"
optional :end_time, :message, 5, "google.protobuf.Timestamp"
optional :parent_span_id, :fixed64, 6
map :labels, :string, :string, 7
end
add_enum "google.devtools.cloudtrace.v1.TraceSpan.SpanKind" do
value :SPAN_KIND_UNSPECIFIED, 0
value :RPC_SERVER, 1
value :RPC_CLIENT, 2
end
add_message "google.devtools.cloudtrace.v1.ListTracesRequest" do
optional :project_id, :string, 1
optional :view, :enum, 2, "google.devtools.cloudtrace.v1.ListTracesRequest.ViewType"
optional :page_size, :int32, 3
optional :page_token, :string, 4
optional :start_time, :message, 5, "google.protobuf.Timestamp"
optional :end_time, :message, 6, "google.protobuf.Timestamp"
optional :filter, :string, 7
optional :order_by, :string, 8
end
add_enum "google.devtools.cloudtrace.v1.ListTracesRequest.ViewType" do
value :VIEW_TYPE_UNSPECIFIED, 0
value :MINIMAL, 1
value :ROOTSPAN, 2
value :COMPLETE, 3
end
add_message "google.devtools.cloudtrace.v1.ListTracesResponse" do
repeated :traces, :message, 1, "google.devtools.cloudtrace.v1.Trace"
optional :next_page_token, :string, 2
end
add_message "google.devtools.cloudtrace.v1.GetTraceRequest" do
optional :project_id, :string, 1
optional :trace_id, :string, 2
end
add_message "google.devtools.cloudtrace.v1.PatchTracesRequest" do
optional :project_id, :string, 1
optional :traces, :message, 2, "google.devtools.cloudtrace.v1.Traces"
end
end
end
module Google
module Cloud
module Trace
module V1
Trace = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.Trace").msgclass
Traces = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.Traces").msgclass
TraceSpan = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.TraceSpan").msgclass
TraceSpan::SpanKind = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.TraceSpan.SpanKind").enummodule
ListTracesRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.ListTracesRequest").msgclass
ListTracesRequest::ViewType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.ListTracesRequest.ViewType").enummodule
ListTracesResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.ListTracesResponse").msgclass
GetTraceRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.GetTraceRequest").msgclass
PatchTracesRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.devtools.cloudtrace.v1.PatchTracesRequest").msgclass
end
end
end
end
|
{
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const file = {
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file-loader',
options: {
esModule: false,
outputPath: 'assets',
name: '[name].[contenthash].[ext]',
},
type: 'javascript/auto',
};
const vue = {
test: /\.vue$/,
loader: 'vue-loader',
};
const typescript = {
test: /\.ts$/,
loader: 'ts-loader',
};
const pug = {
test: /\.pug$/,
loader: [
{
loader: 'pug-loader',
options: {
pretty: true,
root: path.resolve(__dirname, '../src/pug'),
},
},
],
};
const css = (function () {
return {
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader' },
{ loader: 'sass-loader' },
],
};
})();
const node = {
test: /.node$/,
loader: 'node-loader',
};
exports.rules = {
file,
css,
pug,
typescript,
node,
vue,
};
}
|
require 'spec_helper'
module Bug0001Spec
class Thing < ActiveRecord::Base
end
class MyController < ActionController::Base
def respond_to?(method)
super(method)
end
resources_controller_for :things, :class => Thing
end
describe "Calling respond_to? when it has an old signature buried in there [#1]" do
it "should work just fine" do
c = MyController.new
expect(c.respond_to?(:foo)).to eq(false)
end
end
end
|
package c_StringProcessingExercises;
import java.util.*;
public class p05_Palindromes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().split("[\\s+.,?!]+");
Set<String> palindromes = new TreeSet<>();
for (int i = 0; i < input.length; i++) {
boolean isPalindrome = true;
for (int j = 0; j < input[i].length() / 2; j++) {
if (input[i].charAt(j) != input[i].charAt(input[i].length() - j - 1)) {
isPalindrome = false;
}
}
if (isPalindrome) {
palindromes.add(input[i]);
}
}
System.out.println(palindromes);
}
}
|
describe Fastlane::Actions::ReadXcconfigAction do
let(:basic) { read_config_path("basic.xcconfig") }
let(:parent) { read_config_path("parent.xcconfig") }
describe '#run' do
it 'expects input xcconfig file to exist' do
expect do
basic_read_test("nosuchfile")
end.to raise_error(/Couldn't find xcconfig at path:/)
end
it 'expects parent xcconfig file to exist' do
expect do
parent_read_test("basic.xcconfig", parent: "nosuchfile")
end.to raise_error(/Couldn't find parent xcconfig at path:/)
end
it 'reads basic xcconfig' do
basic_read_test("basic.xcconfig") do |config|
expect(config["SRCROOT"]).to eq(File.join(Dir.pwd, "fastlane"))
expect(config["A"]).to eq("1")
expect(config["B1"]).to eq("String Value 1")
expect(config["B2"]).to eq("String Value 2")
expect(config["B3"]).to eq("String Value 3")
expect(config["B4"]).to eq("String Value 4")
expect(config["C"]).to eq("X=1 1")
expect(config["EMPTY"]).to eq("")
end
end
it 'supports srcroot and target_name options' do
options = {
"srcroot" => "custom/srcroot/path",
"target_name" => "TestTargetName"
}
read_lane_test("basic.xcconfig", options: options) do |config|
expect(config["SRCROOT"]).to eq("custom/srcroot/path")
expect(config["TARGET_NAME"]).to eq("TestTargetName")
end
end
it 'supports :resolve option' do
config = Fastlane::FastFile.new.parse("lane :test do
read_xcconfig(
path: '#{basic}',
resolve: false
)
end").runner.execute(:test)
expect(config["C"]).to eq("X=1 $(A)")
end
it 'resolves variable overrides after include' do
basic_read_test("include_overrides_after_reference.xcconfig") do |config|
expect(config["A"]).to eq("Overridden 1")
expect(config["B"]).to eq("Overridden 1")
end
end
it 'resolves variable overrides before include' do
basic_read_test("include_overrides_before_reference.xcconfig") do |config|
expect(config["A"]).to eq("Overridden 1")
expect(config["B"]).to eq("Overridden 1")
end
end
it 'resolves variable overrides from multiple includes (order 1, 2)' do
basic_read_test("overrides_include_order_1.xcconfig") do |config|
expect(config["A"]).to eq("Overridden 2")
expect(config["B"]).to eq("Overridden 2")
end
end
it 'resolves variable overrides from multiple includes (order 2, 1)' do
basic_read_test("overrides_include_order_2.xcconfig") do |config|
expect(config["A"]).to eq("Overridden 1")
expect(config["B"]).to eq("Overridden 1")
end
end
it 'resolves $(inherited) properly when there is no parent config' do
basic_read_test("inheritance.xcconfig") do |config|
expect(config["A1"]).to eq("Added_A1")
expect(config["B1"]).to eq("BeforeAdded_A1After")
expect(config["A2"]).to eq(" Added_A2 ")
expect(config["B2"]).to eq("Before Added_A2 After")
expect(config["A3"]).to eq("Added_A3")
expect(config["B3"]).to eq("BeforeAdded_A3After")
expect(config["inherited"]).to eq("EVIL")
end
end
it 'resolves advanced xcconfig with nested variables and // escaping' do
basic_read_test("advanced.xcconfig") do |config|
expect(config["SLASH"]).to eq("/")
expect(config["URL1"]).to eq("http://t1.com")
expect(config["URL2"]).to eq("https://t2.com")
expect(config["URL_T1"]).to eq("http://t1.com")
expect(config["URL_T2"]).to eq("https://t2.com")
expect(config["VALUE"]).to eq("Value")
expect(config["VALUE2"]).to eq("Value")
end
end
it 'resolves $(inherited) values from parent config' do
parent_read_test("inheritance.xcconfig", parent: "parent.xcconfig") do |config|
expect(config["A"]).to eq("Parent_A")
expect(config["A1"]).to eq("Parent_A1Added_A1Parent_A1")
expect(config["A2"]).to eq("Parent_A2 Added_A2 Parent_A2")
expect(config["A3"]).to eq("Added_A3")
expect(config["B1"]).to eq("BeforeParent_A1Added_A1Parent_A1After")
expect(config["B2"]).to eq("BeforeParent_A2 Added_A2 Parent_A2After")
expect(config["B3"]).to eq("BeforeAdded_A3After")
end
end
end
if FastlaneCore::Helper.mac?
describe 'run and compare with Xcode behavior directly' do
it 'resolves advanced xcconfig with nested variables and // escaping just like Xcode' do
path = "advanced.xcconfig"
basic_read_test(path) do |config|
project = project(path, configuration: "InheritanceOff")
["SLASH", "URL1", "URL2", "URL_T1", "URL_T2", "VALUE", "VALUE2"].each do |key|
expect(config[key]).to eq(project.build_settings(key: key))
end
end
end
it 'resolves $(inherited) values from parent config just like Xcode' do
path = "inheritance.xcconfig"
parent_read_test(path, parent: "parent.xcconfig") do |config|
project = project(path, configuration: "InheritanceOn")
["A", "A1", "A2", "A3", "B1", "B2", "B3"].each do |key|
expect(config[key]).to eq(project.build_settings(key: key))
end
end
end
it 'adds XCODE_VERSION_MAJOR to xcconfig' do
basic_read_test("basic.xcconfig") do |config|
expect(config["XCODE_VERSION_MAJOR"]).not_to(be_empty)
end
end
end
end
end
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Behaviours
{
public class FollowGameObject : MonoBehaviour
{
public string tagToFollow;
public GameObject objectToFollow;
public Vector3 targetPosition;
// Use this for initialization
void Start ()
{
objectToFollow = GameObject.FindWithTag (tagToFollow);
}
// Update is called once per frame
void Update () {
if (objectToFollow)
{
targetPosition = objectToFollow.transform.position;
transform.position = new Vector3 (targetPosition.x, targetPosition.y, transform.position.z);
}
else
{
objectToFollow = GameObject.FindWithTag (tagToFollow);
}
}
}
}
|
using System;
using System.Collections.Generic;
using NUnit.Framework;
using SpiceSharp;
using SpiceSharp.Components;
using SpiceSharp.IntegrationMethods;
using SpiceSharp.Simulations;
using SpiceSharpTest.Models;
namespace SpiceSharpTest.Simulations
{
[TestFixture]
public class TransientTests : Framework
{
[Test]
public void When_RCFilterConstantTransient_Expect_Reference()
{
// Create the circuit
var ckt = new Circuit(
new VoltageSource("V1", "in", "0", 10.0),
new Resistor("R1", "in", "out", 10),
new Capacitor("C1", "out", "0", 20)
);
// Create the transient analysis
var tran = new Transient("tran 1", 1.0, 10.0);
tran.Configurations.Get<TimeConfiguration>().InitTime = 0.0;
tran.Configurations.Get<TimeConfiguration>().Method = new Gear();
tran.ExportSimulationData += (sender, args) =>
{
Assert.AreEqual(10.0, args.GetVoltage("out"), 1e-9);
};
tran.Run(ckt);
// Let's run the simulation twice to check if it is consistent
try
{
tran.Run(ckt);
}
catch (Exception)
{
throw new Exception(@"Cannot run transient analysis twice");
}
}
[Test]
public void When_RCFilterConstantTransientGear_Expect_Reference()
{
// Create the circuit
var ckt = new Circuit(
new VoltageSource("V1", "in", "0", 10.0),
new Resistor("R1", "in", "out", 10),
new Capacitor("C1", "out", "0", 20));
// Create the transient analysis
var tran = new Transient("tran 1", 1.0, 10.0);
// TODO: review this test
// tran.Configurations.Get<TimeConfiguration>().Method = new Gear();
tran.ExportSimulationData += (sender, args) => { Assert.AreEqual(args.GetVoltage("out"), 10.0, 1e-12); };
tran.Run(ckt);
// Let's run the simulation twice to check if it is consistent
try
{
tran.Run(ckt);
}
catch (Exception)
{
throw new Exception(@"Cannot run transient analysis twice");
}
}
[Test]
public void When_FloatingRTransient_Expect_Reference()
{
// Create the circuit
var ckt = new Circuit(
new VoltageSource("V1", "in", "0", 10.0),
new Resistor("R1", "in", "out", 10.0)
);
// Create the transient analysis
var tran = new Transient("Tran 1", 1e-6, 10.0);
tran.ExportSimulationData += (sender, args) =>
{
Assert.AreEqual(args.GetVoltage("out"), 10.0, 1e-12);
};
tran.Run(ckt);
}
[Test]
public void When_LazyLoadExport_Expect_Reference()
{
// Create the circuit
var ckt = new Circuit(
new VoltageSource("V1", "in", "0", 10),
new Resistor("R1", "in", "0", 1e3));
// Create the transient analysis
var tran = new Transient("Tran 1", 1e-6, 10.0);
Export<double> export = null;
tran.ExportSimulationData += (sender, args) =>
{
// If the time > 5.0 then start exporting our stuff
if (args.Time > 5.0)
{
if (export == null)
export = new RealPropertyExport((Simulation) sender, "R1", "i");
Assert.AreEqual(10.0 / 1e3, export.Value, 1e-12);
}
};
tran.Run(ckt);
}
[Test]
public void When_FixedEuler_Expect_NoException()
{
// Create a circuit with a nonlinear component
var ckt = new Circuit(
new VoltageSource("V1", "in", "0", new Pulse(0, 5, 1e-6, 1e-6, 1e-6, 1e-5, 2e-5)),
new NonlinearResistor("NLR1", "in", "out")
.SetParameter("a", 100.0)
.SetParameter("b", 0.7),
new Capacitor("C1", "out", "0", 1.0e-9)
);
// Create a transient analysis using Backward Euler with fixed timesteps
var tran = new Transient("tran", 1e-7, 10e-5);
tran.Configurations.Get<TimeConfiguration>().Method = new FixedEuler();
tran.Run(ckt);
}
[Test]
public void When_FloatingCapacitor_Expect_Reference()
{
// Build the circuit
var ckt = new Circuit(
new CurrentSource("I1", "in", "0", 0.1),
new Capacitor("C1", "in", "out", 1e-6),
new Resistor("R2", "out", "0", 2.0e3)
);
// Build the simulation
var tran = new Transient("tran", 1e-6, 10e-6);
var exports = new Export<double>[]
{
new RealVoltageExport(tran, "in"),
new RealVoltageExport(tran, "out")
};
var references = new Func<double, double>[]
{
time => time > 0 ? -0.1 / 1e-6 * time - 200.0 : 0.0,
time => time > 0 ? -200.0 : 0.0
};
// Set initial conditions
var ic = tran.Configurations.Get<TimeConfiguration>().InitialConditions;
ic["in"] = 0.0;
// Analyze
AnalyzeTransient(tran, ckt, exports, references);
}
[Test]
public void When_LargeExample_Expect_Reference()
{
// First create the models
var diodeModelA = new DiodeModel("DA")
.SetParameter("n", 0.1e-3);
var diodeModelB = new DiodeModel("DB")
.SetParameter("is", 100e-14);
var bjtModelQp1 = new BipolarJunctionTransistorModel("QP1")
.SetParameter("pnp", true)
.SetParameter("is", 16e-15)
.SetParameter("bf", 1700.0);
var bjtModelQp2 = new BipolarJunctionTransistorModel("QP2")
.SetParameter("pnp", true)
.SetParameter("is", 16e-15)
.SetParameter("bf", 1610.5);
var ckt = new Circuit(
new NodeMapper(new[]
{
"VDD", "test:11", "test:12", "VEE", "test:91", "test:92", "test:13",
"test:15", "test:14", "test:16", "test:20", "test:32", "test:111",
"test:17", "test:112", "test:113", "test:114", "test:115", "INP",
"INN", "test:21", "test:22", "test:23", "test:110", "test:33",
"test:59", "test:34", "test:60", "test:61", "test:63", "test:62",
"test:65", "test:66", "test:64", "test:67", "test:68", "test:69",
"test:70", "OUT", "test:77", "test:78", "test:79", "test:80",
"test:81", "test:83", "test:84", "test:85", "test:86", "test:87",
"test:88", "test:89", "test:90"
}),
diodeModelA,
diodeModelB,
bjtModelQp1,
bjtModelQp2,
new VoltageSource("test:VS1", "VDD", "test:11", 0),
new CurrentSource("test:IBIAS", "test:11", "test:12", 61.3e-6),
new Diode("test:DBIAS", "VEE", "test:12", "DA"),
new Resistor("test:RE1", "test:12", "test:91", 1.005e3),
new Resistor("test:RE2", "test:12", "test:92", 1.005e3),
new BipolarJunctionTransistor("test:QI1", "test:13", "test:15", "test:91", "test:91", "QP1"),
new BipolarJunctionTransistor("test:QI2", "test:14", "test:16", "test:92", "test:92", "QP2"),
new Resistor("test:RIN1", "test:15", "test:20", 3e6),
new Resistor("test:RIN2", "test:16", "test:20", 3e6),
new Diode("test:DIN1", "test:15", "VDD", "DB"),
new Diode("test:DIN2", "VEE", "test:15", "DB"),
new Diode("test:DIN3", "test:16", "VDD", "DB"),
new Diode("test:DIN4", "VEE", "test:16", "DB"),
new VoltageControlledVoltageSource("test:ECR1", "test:15", "test:32", "test:111", "test:20", 1),
new VoltageSource("test:VOS", "test:17", "test:32", 1e-3),
new Diode("test:DP1", "test:17", "test:112", "DB"),
new Diode("test:DP2", "test:112", "test:113", "DB"),
new Diode("test:DP3", "test:113", "test:16", "DB"),
new Diode("test:DP4", "test:16", "test:114", "DB"),
new Diode("test:DP5", "test:114", "test:115", "DB"),
new Diode("test:DP6", "test:115", "test:17", "DB"),
new Resistor("test:RP1", "test:17", "INP", 3.5e3),
new Resistor("test:RP2", "test:16", "INN", 3.5e3),
new Resistor("test:RC1", "test:13", "VEE", 1.856e3),
new Resistor("test:RC2", "test:14", "VEE", 1.856e3),
new Capacitor("test:C1", "test:13", "test:14", 14.0e-12),
new VoltageControlledCurrentSource("test:GA", "test:21", "test:20", "test:14", "test:13",
326.8e-6),
new CurrentControlledCurrentSource("test:FSUP", "VEE", "VDD", "test:VS1", 1),
new Resistor("test:RO1", "test:21", "test:20", 30606),
new VoltageControlledCurrentSource("test:GB", "test:22", "test:20", "test:21", "test:20", 1),
new Resistor("test:RO2", "test:22", "test:20", 20e3),
new VoltageControlledVoltageSource("test:EF", "test:23", "test:20", "test:22", "test:20", 1),
new Capacitor("test:CC", "test:23", "test:21", 36.8e-12),
new VoltageControlledVoltageSource("test:EG", "test:20", "VEE", "VDD", "VEE", 0.5),
new VoltageControlledCurrentSource("test:GCP", "test:22", "test:20", "test:110", "test:20", 10),
new Diode("test:DVL1", "test:22", "test:33", "DA"),
new VoltageSource("test:VMIN1", "test:59", "test:33", 6.85e-3),
new Diode("test:DVL2", "test:34", "test:22", "DA"),
new VoltageSource("test:VMIN2", "test:34", "test:60", 4e-3),
new VoltageControlledVoltageSource("test:ELIM2", "test:59", "test:61", "VDD", "VEE", 0.5),
new VoltageControlledVoltageSource("test:ELIM1", "test:63", "test:60", "VDD", "VEE", 0.5),
new VoltageControlledVoltageSource("test:ECOMP2", "test:62", "test:20", "test:65", "test:66", 1),
new VoltageControlledVoltageSource("test:ECOMP1", "test:64", "test:20", "test:65", "test:66", 1),
new VoltageControlledVoltageSource("test:EOUT", "test:65", "test:20", "test:22", "test:20", 1),
new Resistor("test:ROUT1", "test:65", "test:66", 150),
new VoltageSource("test:VIS3", "test:66", "test:67", 0),
new Diode("test:DSC1", "test:67", "test:68", "DA"),
new Diode("test:DSC2", "test:69", "test:67", "DA"),
new Diode("test:DSC3", "test:69", "test:70", "DA"),
new Diode("test:DSC4", "test:70", "test:68", "DA"),
new CurrentSource("test:ISC1", "test:68", "test:69", 25e-3),
new Resistor("test:RSC", "test:68", "test:69", 10e6),
new Resistor("test:ROUT2", "test:70", "OUT", 0.1e-3),
new Resistor("test:RLOAD", "OUT", "test:20", 10e6),
new Diode("test:DSUP", "VEE", "VDD", "DB"),
new Resistor("test:RSUP", "VDD", "VEE", 200e3),
new CurrentSource("test:ISUP", "VDD", "VEE", 95e-6),
new CurrentControlledCurrentSource("test:FSUP1", "test:20", "test:77", "test:VIS3", 1),
new Capacitor("test:CSUP", "test:77", "test:20", 1e-12),
new Diode("test:DSUP1", "test:20", "test:77", "DB"),
new Diode("test:DSUP2", "test:77", "test:78", "DB"),
new VoltageSource("test:VIS4", "test:78", "test:20", 0),
new CurrentControlledCurrentSource("test:FSUP2", "VDD", "VEE", "test:VIS4", 1),
new VoltageControlledVoltageSource("test:ESUP1", "test:79", "test:20", "VDD", "VEE", 1),
new Capacitor("test:CPSRR", "test:79", "test:80", 7.5e-12),
new Resistor("test:RPSRR", "test:80", "test:20", 5e3),
new VoltageControlledCurrentSource("test:GPSRR1", "test:20", "test:110", "test:80", "test:20",
0.05),
new VoltageControlledCurrentSource("test:GPSRR2", "test:20", "test:111", "test:79", "test:20",
10.5e-6),
new Resistor("test:RRDC", "test:111", "test:20", 1),
new Resistor("test:RRR", "test:110", "test:20", 1),
new VoltageControlledVoltageSource("test:ECM1", "test:81", "test:20", "test:12", "VEE", 1),
new VoltageControlledCurrentSource("test:GCM2", "test:20", "test:111", "test:81", "test:20", 10e-6),
new Diode("test:DIL", "test:12", "test:83", "DA"),
new Resistor("test:RIL", "test:83", "test:84", 50),
new VoltageSource("test:VIL", "test:85", "test:84", 0.9),
new VoltageControlledVoltageSource("test:EIL", "test:85", "VEE", "VDD", "VEE", 1),
new Diode("test:DVL3", "VEE", "test:12", "DA"),
new Diode("test:DVL4", "test:12", "test:86", "DA"),
new CurrentControlledCurrentSource("test:FVL", "test:86", "VEE", "test:VIS5", 1),
new VoltageSource("test:VVL", "test:87", "VEE", 2.3),
new VoltageSource("test:VIS5", "test:87", "test:88", 0),
new Diode("test:DVL5", "test:88", "test:89", "DA"),
new Resistor("test:RVL", "test:89", "test:90", 300),
new VoltageControlledVoltageSource("test:EVL1", "test:90", "VEE", "VDD", "VEE", 1),
new Resistor("RF", "OUT", "INN", 10),
new VoltageSource("VSIG", "INP", "0", new Pulse(-1.5, 1.5, 1e-6, 10e-9, 10e-9, 5e-6, 10e-6)),
new VoltageSource("VSUP", "VDD", "VEE", 5),
new VoltageControlledVoltageSource("EG1", "0", "VEE", "VDD", "VEE", 0.2)
);
// Calculate the operating point
var tran = new Transient("tran", 1e-9, 10e-6);
tran.Run(ckt);
}
[Test]
public void When_ExportSwitch_Expect_Reference()
{
var ckt = new Circuit(
new VoltageSource("V1", "in", "0", new Sine(1, 1, 10)),
new Resistor("R1", "in", "out", 1e3),
new Resistor("R2", "out", "0", 1e3));
var sim1 = new DC("dc", "V1", 0, 2, 0.2);
var sim2 = new Transient("tran", 1e-3, 0.5);
var vexport = new RealVoltageExport(sim1, "out");
var iexport = new RealCurrentExport(sim1, "V1");
var pexport = new RealPropertyExport(sim1, "R1", "p");
sim1.ExportSimulationData += (sender, e) =>
{
var input = e.GetVoltage("in");
Assert.AreEqual(input * 0.5, vexport.Value, 1e-9);
Assert.AreEqual(-input / 2.0e3, iexport.Value, 1e-9);
Assert.AreEqual(input * input / 4.0 / 1.0e3, pexport.Value, 1e-9);
};
sim2.ExportSimulationData += (sender, e) =>
{
var input = e.GetVoltage("in");
Assert.AreEqual(Math.Sin(2 * Math.PI * 10 * e.Time) + 1.0, input, 1e-9);
Assert.AreEqual(input * 0.5, vexport.Value, 1e-9);
Assert.AreEqual(-input / 2.0e3, iexport.Value, 1e-9);
Assert.AreEqual(input * input / 4.0 / 1.0e3, pexport.Value, 1e-9);
};
sim1.Run(ckt);
// Switch exports
vexport.Simulation = sim2;
iexport.Simulation = sim2;
pexport.Simulation = sim2;
sim2.Run(ckt);
}
}
}
|
module WizardryHelper
def wizardry_content(w)
case w.current_page
when Wizardry::Pages::QuestionPage
render_form(w)
when Wizardry::Pages::CheckYourAnswersPage
safe_join([render_check_your_answers(w), render_form(w)])
when Wizardry::Pages::CompletionPage
render_completion(w)
end
end
private
def render_form(w)
capture do
try_partial(w, 'page') do
wizard_form(w) do |f|
try_partial(w, 'form', locals: { f: f }) do
concat(f.govuk_error_summary)
w.current_page.questions.map do |q|
concat(f.send(q.form_method, q.name, *q.extra_args, **q.extra_kwargs))
end
concat(f.govuk_submit)
end
end
end
end
end
def render_check_your_answers(w)
capture do
try_partial(w, 'page') do
safe_join(
[
render(GovukComponent::SummaryListComponent.new) do |summary_list|
w.route.each do |page|
page.questions.each do |question|
summary_list.row do |sl|
sl.key(text: check_your_answers_key(w.object.class.name, question.name))
sl.value(text: w.object.send(question.name))
sl.action(href: send(w.framework.edit_path_helper, page.name))
end
end
end
end
]
)
end
end
end
def render_completion(w)
capture do
try_partial(w, 'page') do
safe_join(
[
tag.h1('Completed'),
tag.p do
[
'Add a partial called',
tag.code(%(_completion_page.html.erb)),
'to override this message'
].join(' ').html_safe
end
]
)
end
end
end
def wizard_form(w, turbo_frame_id: 'wizardry-form', &block)
turbo_frame_tag(turbo_frame_id) do
safe_join(
[
form_for(
w.object,
url: send(
w.framework.update_path_helper,
page: w.current_page.name
),
method: :patch,
builder: GOVUKDesignSystemFormBuilder::FormBuilder,
&block
)
]
)
end
end
def try_partial(w, section, locals: {}, &block)
if lookup_context.template_exists?(partial_file_path(w, section))
Rails.logger.debug("🧙 Page partial #{partial_file_path(w, section)} found; rendering entire page")
concat(render(partial: partial_render_path(w, section), locals: locals))
else
Rails.logger.debug('🧙 No overriding form partial found; automatically building form')
block.call
end
end
def check_your_answers_key(class_name, question_name)
I18n.t!("helpers.legend.#{class_name.underscore}.#{question_name}")
rescue I18n::MissingTranslationData
I18n.t("helpers.label.#{class_name.underscore}.#{question_name}")
end
def partial_file_path(w, suffix)
"#{w.framework.name}/_#{w.current_page.name}_#{suffix}"
end
def partial_render_path(w, suffix)
"#{w.framework.name}/#{w.current_page.name}_#{suffix}"
end
end
ActiveSupport.on_load(:action_view) { include WizardryHelper }
|
class Details {
List<Corona> corona;
Details({this.corona});
Details.fromJson(Map<String, dynamic> json) {
if (json['Corona'] != null) {
corona = new List<Corona>();
json['Corona'].forEach((v) {
corona.add(new Corona.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.corona != null) {
data['Corona'] = this.corona.map((v) => v.toJson()).toList();
}
return data;
}
}
class Corona {
String activeCases;
String average;
String code;
String flag;
String country;
String newCases;
String newDeaths;
String serious;
String totalCases;
String totalDeaths;
String totalRecoverd;
Corona(
{this.activeCases,
this.average,
this.code,
this.flag,
this.country,
this.newCases,
this.newDeaths,
this.serious,
this.totalCases,
this.totalDeaths,
this.totalRecoverd});
Corona.fromJson(Map<String, dynamic> json) {
activeCases = json['ActiveCases'];
average = json['Average'];
code = json['Code'];
flag = 'assests/flags/'+code+'.png';
country = json['Country'];
newCases = json['NewCases'];
newDeaths = json['NewDeaths'];
serious = json['Serious'];
totalCases = json['TotalCases'];
totalDeaths = json['TotalDeaths'];
totalRecoverd = json['TotalRecoverd'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ActiveCases'] = this.activeCases;
data['Average'] = this.average;
data['Code'] = this.code;
data['assests/flags/'+code+'.png'] =this.flag;
data['Country'] = this.country;
data['NewCases'] = this.newCases;
data['NewDeaths'] = this.newDeaths;
data['Serious'] = this.serious;
data['TotalCases'] = this.totalCases;
data['TotalDeaths'] = this.totalDeaths;
data['TotalRecoverd'] = this.totalRecoverd;
return data;
}
}
|
package com.brins.lightmusic.model.onlinemusic
import android.os.Parcel
import android.os.Parcelable
/*
* 在线歌单
*/
class MusicListBean : Parcelable {
var name: String = ""
var id: String = ""
var userid: String = ""
var createTime: Long = 0
var subscribedCount: Long = 0
var coverImgUrl: String = ""
var description: String = ""
var tags = arrayOf("")
var playCount: Long = 0
var shareCount: Int = 0
var commentCount: Int = 0
var bitmap: String = ""
constructor(source: Parcel){
name = source.readString()
id = source.readString()
userid = source.readString()
createTime = source.readLong()
subscribedCount = source.readLong()
coverImgUrl = source.readString()
description = source.readString()
// source.readStringArray(tags)
playCount = source.readLong()
shareCount = source.readInt()
commentCount = source.readInt()
bitmap = source.readString()
}
constructor()
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
this.writeString(name)
this.writeString(id)
this.writeString(userid)
this.writeLong(createTime)
this.writeLong(subscribedCount)
this.writeString(coverImgUrl)
this.writeString(description)
// this.writeStringArray(tags)
this.writeLong(playCount)
this.writeInt(shareCount)
this.writeInt(commentCount)
this.writeString(bitmap)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<MusicListBean> = object : Parcelable.Creator<MusicListBean> {
override fun createFromParcel(source: Parcel): MusicListBean =
MusicListBean(source)
override fun newArray(size: Int): Array<MusicListBean?> = arrayOfNulls(size)
}
}
}
|
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
abstract class HomeEvent extends Equatable {
HomeEvent([List props = const []]) : super(props);
}
class ItemUsed extends HomeEvent {
final String itemId;
ItemUsed(@required this.itemId);
@override
String toString() => 'Item Used Event';
}
class Test extends HomeEvent {
@override
String toString() => 'Test';
}
|
//
// YLBScrollContentConst.h
// YLBScrollViewNest
//
// Created by yulibo on 2020/10/19.
//
#import <Foundation/Foundation.h>
UIKIT_EXTERN NSString * const YLBMineLeaveTopNotification;
|
comprehension1 = [x*2 | x <- [1..10]]
-- predicates are separated by a comma
predicate1 = [x*2 | x <- [1..10], x*2 >=12]
predicate2 = [ x | x <- [50..100], mod x 7 == 3]
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
--multople predicates
predicate3 = [ x | x <- [10..20], x /= 13, x /= 15, x /= 19]
--multiple input lists combine each other
combined = [ x*y | x <- [2,5,10], y <- [8,10,11]]
combined2 = [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50]
combined3 = [ x ++" "++y | x <- ["hello", "world"], y <- ["just", "another", "list"]]
--unimportant parameter with underscore
length' xs = sum [1 | _ <- xs]
removeNonUppercase st = [c | c <- st, elem c ['A'..'Z']]
--several levels
listOfLists = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
evenLists lls = [ [l|l <- ls, even l] | ls <- lls]
|
(ns com.yetanalytics.dave
(:require [clojure.spec.alpha :as s]
[com.yetanalytics.dave.workbook :as workbook]
[com.yetanalytics.dave.func :as func]))
;; DAVE Object Specs
(s/def ::workbook
workbook/workbook-spec)
(s/def ::function
func/func-spec)
|
'use strict'
const fs = require('fs')
const path = require('path')
const { promisify } = require('util')
const readFile = promisify(fs.readFile)
module.exports = function darkMode(mainWindow) {
mainWindow.webContents.on('dom-ready', () => {
Promise.all([
// Generated overrides for SoundCloud's "app.css"
readFile(path.join(__dirname, 'dark-mode.app.css'), 'utf-8'),
// Generated overrides for SoundCloud's inline styles
readFile(path.join(__dirname, 'dark-mode.inline.css'), 'utf-8'),
// Manual overrides
readFile(path.join(__dirname, 'dark-mode.css'), 'utf-8')
])
.then((cssFiles) => {
mainWindow.webContents.insertCSS(
`
@media (prefers-color-scheme: dark) {
${cssFiles.join('\n')}
}
`,
{ cssOrigin: 'user' }
)
})
.catch(console.error)
})
}
|
package com.braintreegateway;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Provides a fluent interface to build up requests around {@link Customer Customers}.
*/
public class CustomerRequest extends Request {
private String deviceData;
private String company;
private String customerId;
private String deviceSessionId;
private String fraudMerchantId;
private String email;
private String fax;
private String firstName;
private String id;
private String lastName;
private String phone;
private String website;
private String paymentMethodNonce;
private String defaultPaymentMethodToken;
private Map<String, String> customFields;
private CreditCardRequest creditCardRequest;
private RiskDataCustomerRequest riskDataCustomerRequest;
private CustomerOptionsRequest optionsRequest;
private TransactionRequest parent;
private List<TaxIdentifierRequest> taxIdentifierRequests;
public CustomerRequest() {
this.customFields = new HashMap<String, String>();
this.taxIdentifierRequests = new ArrayList<TaxIdentifierRequest>();
}
public CustomerRequest(TransactionRequest transactionRequest) {
this();
this.parent = transactionRequest;
}
public CustomerRequest deviceData(String deviceData) {
this.deviceData = deviceData;
return this;
}
public CustomerRequest company(String company) {
this.company = company;
return this;
}
public CreditCardRequest creditCard() {
creditCardRequest = new CreditCardRequest(this);
return this.creditCardRequest;
}
public CustomerRequest customerId(String customerId) {
this.customerId = customerId;
return this;
}
public CustomerRequest customField(String apiName, String value) {
customFields.put(apiName, value);
return this;
}
@Deprecated
// Merchants should be using deviceData only
public CustomerRequest deviceSessionId(String deviceSessionId) {
this.deviceSessionId = deviceSessionId;
return this;
}
@Deprecated
// Merchants should be using deviceData only
public CustomerRequest fraudMerchantId(String fraudMerchantId) {
this.fraudMerchantId = fraudMerchantId;
return this;
}
public TransactionRequest done() {
return parent;
}
public CustomerRequest email(String email) {
this.email = email;
return this;
}
public CustomerRequest fax(String fax) {
this.fax = fax;
return this;
}
public CustomerRequest firstName(String firstName) {
this.firstName = firstName;
return this;
}
public RiskDataCustomerRequest riskData() {
riskDataCustomerRequest = new RiskDataCustomerRequest(this);
return this.riskDataCustomerRequest;
}
public CustomerOptionsRequest options() {
this.optionsRequest = new CustomerOptionsRequest(this);
return optionsRequest;
}
public CustomerRequest lastName(String lastName) {
this.lastName = lastName;
return this;
}
public CustomerRequest id(String id) {
this.id = id;
return this;
}
public String getId() {
return id;
}
public CustomerRequest phone(String phone) {
this.phone = phone;
return this;
}
public CustomerRequest website(String website) {
this.website = website;
return this;
}
public CustomerRequest paymentMethodNonce(String nonce) {
this.paymentMethodNonce = nonce;
return this;
}
public CustomerRequest defaultPaymentMethodToken(String token) {
this.defaultPaymentMethodToken = token;
return this;
}
public TaxIdentifierRequest taxIdentifier() {
TaxIdentifierRequest taxIdentiferRequest = new TaxIdentifierRequest(this);
taxIdentifierRequests.add(taxIdentiferRequest);
return taxIdentiferRequest;
}
@Override
public String toXML() {
return buildRequest("customer").toXML();
}
@Override
public String toQueryString() {
return toQueryString("customer");
}
@Override
public String toQueryString(String root) {
return buildRequest(root)
.addTopLevelElement("customerId", customerId)
.toQueryString();
}
protected RequestBuilder buildRequest(String root) {
RequestBuilder builder = new RequestBuilder(root)
.addElement("deviceData", deviceData)
.addElement("company", company)
.addElement("email", email)
.addElement("fax", fax)
.addElement("firstName", firstName)
.addElement("id", id)
.addElement("lastName", lastName)
.addElement("phone", phone)
.addElement("website", website)
.addElement("paymentMethodNonce", paymentMethodNonce)
.addElement("defaultPaymentMethodToken", defaultPaymentMethodToken)
.addElement("creditCard", creditCardRequest)
.addElement("options", optionsRequest)
.addElement("riskData", riskDataCustomerRequest);
if (customFields.size() > 0) {
builder.addElement("customFields", customFields);
}
if (!taxIdentifierRequests.isEmpty()) {
builder.addElement("taxIdentifiers", taxIdentifierRequests);
}
return builder;
}
}
|
(ns ^:no-doc xtdb.morton
(:import xtdb.morton.UInt128))
;; Start here:
;; https://en.wikipedia.org/wiki/Z-order_curve
;; https://en.wikipedia.org/wiki/Z-order_curve#Use_with_one-dimensional_data_structures_for_range_searching
;; Based on this paper and the decision tables on page 76:
;; https://www.vision-tools.com/h-tropf/multidimensionalrangequery.pdf
;; Further resources:
;; https://github.com/locationtech/geotrellis/tree/master/spark/src/main/scala/geotrellis/spark/io/index/zcurve
;; https://raima.com/wp-content/uploads/COTS_embedded_database_solving_dynamic_pois_2012.pdf
;; https://github.com/hadeaninc/libzinc/blob/master/libzinc/AABB.hh
;; http://cppedinburgh.uk/slides/201603-zcurves.pdf
;; https://aws.amazon.com/blogs/database/z-order-indexing-for-multifaceted-queries-in-amazon-dynamodb-part-1/
;; https://redis.io/topics/indexes#multi-dimensional-indexes
;; http://www.dcs.bbk.ac.uk/~jkl/thesis.pdf
;; NOTE: Many papers use y/x order for coordinates, so some tests are
;; a bit confusing. We, and the original paper use x/y:
;; https://www.vision-tools.com/h-tropf/multidimensionalrangequery.pdf
;; Internally its first and second dimension, x and y are just names
;; for these which may change depending on context.
(def ^:dynamic *use-space-filling-curve-index?* (not (Boolean/parseBoolean (System/getenv "XTDB_DISABLE_SPACE_FILLING_CURVE_INDEX"))))
(set! *unchecked-math* :warn-on-boxed)
;; http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN
(defn- bit-spread-int ^long [^long x]
(let [x (bit-and (bit-or x (bit-shift-left x 16)) 0x0000ffff0000ffff)
x (bit-and (bit-or x (bit-shift-left x 8)) 0x00ff00ff00ff00ff)
x (bit-and (bit-or x (bit-shift-left x 4)) 0x0f0f0f0f0f0f0f0f)
x (bit-and (bit-or x (bit-shift-left x 2)) 0x3333333333333333)
x (bit-and (bit-or x (bit-shift-left x 1)) 0x5555555555555555)]
x))
(defn- bit-unspread-int ^long [^long x]
(let [x (bit-and x 0x5555555555555555)
x (bit-and (bit-or x (bit-shift-right x 1)) 0x3333333333333333)
x (bit-and (bit-or x (bit-shift-right x 2)) 0x0f0f0f0f0f0f0f0f)
x (bit-and (bit-or x (bit-shift-right x 4)) 0x00ff00ff00ff00ff)
x (bit-and (bit-or x (bit-shift-right x 8)) 0x0000ffff0000ffff)
x (bit-and (bit-or x (bit-shift-right x 16)) 0xffffffff)]
x))
(defn- bit-interleave-ints ^long [^long d1 ^long d2]
(bit-or (bit-shift-left (bit-spread-int (Integer/toUnsignedLong (unchecked-int d1))) 1)
(bit-spread-int (Integer/toUnsignedLong (unchecked-int d2)))))
(defn- bit-uninterleave-ints [^long x]
(int-array [(bit-unspread-int (unsigned-bit-shift-right x 1))
(bit-unspread-int x)]))
(defn interleaved-longs->morton-number ^xtdb.morton.UInt128 [^long upper ^long lower]
(UInt128. upper lower))
(defn longs->morton-number ^xtdb.morton.UInt128 [^long d1 ^long d2]
(let [lower (bit-interleave-ints d1 d2)
upper (bit-interleave-ints (unsigned-bit-shift-right d1 Integer/SIZE)
(unsigned-bit-shift-right d2 Integer/SIZE))]
(interleaved-longs->morton-number upper lower)))
(defn morton-number->interleaved-longs [^UInt128 z]
[(.upper z) (.lower z)])
(defn morton-number->longs [^Number z]
(let [z (UInt128/fromNumber z)
lower ^ints (bit-uninterleave-ints (.lower z))
upper ^ints (bit-uninterleave-ints (.upper z))]
[(bit-or (bit-shift-left (Integer/toUnsignedLong (aget upper 0)) Integer/SIZE)
(Integer/toUnsignedLong (aget lower 0)))
(bit-or (bit-shift-left (Integer/toUnsignedLong (aget upper 1)) Integer/SIZE)
(Integer/toUnsignedLong (aget lower 1)))]))
(def ^:private ^UInt128 morton-d1-mask (UInt128/fromBigInteger (biginteger 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)))
(def ^:private ^UInt128 morton-d2-mask (UInt128/fromBigInteger (biginteger 0x55555555555555555555555555555555)))
(defn morton-number-within-range? [^Number min ^Number max ^Number z]
(let [min (UInt128/fromNumber min)
max (UInt128/fromNumber max)
z (UInt128/fromNumber z)
z-d1 (.and z morton-d1-mask)
z-d2 (.and z morton-d2-mask)]
(and (not (pos? (.compareTo (.and min morton-d1-mask) z-d1)))
(not (pos? (.compareTo (.and min morton-d2-mask) z-d2)))
(not (pos? (.compareTo z-d1 (.and max morton-d1-mask))))
(not (pos? (.compareTo z-d2 (.and max morton-d2-mask)))))))
(def ^UInt128 z-max-mask UInt128/MAX)
(def ^UInt128 z-max-mask-spread (UInt128/fromBigInteger (biginteger 0x55555555555555555555555555555555)))
(def ^:const z-max-bits UInt128/SIZE)
(defrecord MortonRange [litmax bigmin])
(defn- morton-get-next-address-internal ^xtdb.morton.MortonRange [^UInt128 start ^UInt128 end]
(let [first-differing-bit (.numberOfLeadingZeros (.xor start end))
split-dimension (bit-and 1 first-differing-bit)
dimension-inherit-mask (if (zero? split-dimension)
morton-d2-mask
morton-d1-mask)
common-most-significant-bits-mask (.shiftLeft UInt128/MAX (- UInt128/SIZE first-differing-bit))
all-common-bits-mask (.or dimension-inherit-mask common-most-significant-bits-mask)
;; 1000 -> 1000000
other-dimension-above (.shiftLeft UInt128/ONE (dec (- UInt128/SIZE first-differing-bit)))
bigmin (.or (.and all-common-bits-mask start) other-dimension-above)
;; 0111 -> 0010101
other-dimension-below (.and (.dec other-dimension-above)
(if (zero? split-dimension)
morton-d1-mask
morton-d2-mask))
litmax (.or (.and all-common-bits-mask end) other-dimension-below)]
(MortonRange. litmax bigmin)))
(defn morton-get-next-address [^Number start ^Number end]
(let [start (UInt128/fromNumber start)
end (UInt128/fromNumber end)
range (morton-get-next-address-internal start end)]
[(.litmax range) (.bigmin range)]))
(defn morton-range-search [^Number start ^Number end ^Number z]
(let [z (UInt128/fromNumber z)]
(loop [start (UInt128/fromNumber start)
end (UInt128/fromNumber end)]
(cond
(neg? (.compareTo ^UInt128 end z))
[end 0]
(neg? (.compareTo ^UInt128 z start))
[0 start]
:else
(let [range (morton-get-next-address-internal start end)
litmax (.litmax range)
bigmin (.bigmin range)]
(cond
(neg? (.compareTo ^UInt128 bigmin z))
(recur bigmin end)
(neg? (.compareTo ^UInt128 z litmax))
(recur start litmax)
:else
[litmax bigmin]))))))
|
//===- OpGenHelpers.cpp - MLIR operation generator helpers ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines helpers used in the op generators.
//
//===----------------------------------------------------------------------===//
#include "OpGenHelpers.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Regex.h"
#include "llvm/TableGen/Error.h"
using namespace llvm;
using namespace mlir;
using namespace mlir::tblgen;
cl::OptionCategory opDefGenCat("Options for op definition generators");
static cl::opt<std::string> opIncFilter(
"op-include-regex",
cl::desc("Regex of name of op's to include (no filter if empty)"),
cl::cat(opDefGenCat));
static cl::opt<std::string> opExcFilter(
"op-exclude-regex",
cl::desc("Regex of name of op's to exclude (no filter if empty)"),
cl::cat(opDefGenCat));
static std::string getOperationName(const Record &def) {
auto prefix = def.getValueAsDef("opDialect")->getValueAsString("name");
auto opName = def.getValueAsString("opName");
if (prefix.empty())
return std::string(opName);
return std::string(llvm::formatv("{0}.{1}", prefix, opName));
}
std::vector<Record *>
mlir::tblgen::getRequestedOpDefinitions(const RecordKeeper &recordKeeper) {
Record *classDef = recordKeeper.getClass("Op");
if (!classDef)
PrintFatalError("ERROR: Couldn't find the 'Op' class!\n");
llvm::Regex includeRegex(opIncFilter), excludeRegex(opExcFilter);
std::vector<Record *> defs;
for (const auto &def : recordKeeper.getDefs()) {
if (!def.second->isSubClassOf(classDef))
continue;
// Include if no include filter or include filter matches.
if (!opIncFilter.empty() &&
!includeRegex.match(getOperationName(*def.second)))
continue;
// Unless there is an exclude filter and it matches.
if (!opExcFilter.empty() &&
excludeRegex.match(getOperationName(*def.second)))
continue;
defs.push_back(def.second.get());
}
return defs;
}
|
package vistas;
import com.vaadin.flow.templatemodel.TemplateModel;
import basededatos.Cliente;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.polymertemplate.PolymerTemplate;
import com.vaadin.flow.dom.Element;
import com.vaadin.flow.component.polymertemplate.Id;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.textfield.TextField;
/**
* A Designer generated component for the vista-poner-cliente template.
*
* Designer will add and remove fields with @Id mappings but
* does not overwrite or otherwise change this file.
*/
@Tag("vista-poner-cliente")
@JsModule("./src/vista-poner-cliente.js")
public class VistaPonerCliente extends PolymerTemplate<VistaPonerCliente.VistaPonerClienteModel> {
@Id("vaadinVerticalLayout")
private Element vaadinVerticalLayout;
@Id("nuevo")
private Button nuevo;
@Id("nuevoCliente")
private TextField nuevoCliente;
@Id("nuevaDireccion")
private TextField nuevaDireccion;
@Id("nuevoTelefono")
private TextField nuevoTelefono;
@Id("seleccionCliente")
private ComboBox<Cliente> seleccionCliente;
/**
* Creates a new VistaPonerCliente.
*/
public VistaPonerCliente() {
// You can initialise any data required for the connected UI components here.
}
/**
* This model binds properties between VistaPonerCliente and vista-poner-cliente
*/
public interface VistaPonerClienteModel extends TemplateModel {
// Add setters and getters for template properties here.
}
public Element getVaadinVerticalLayout() {
return vaadinVerticalLayout;
}
public void setVaadinVerticalLayout(Element vaadinVerticalLayout) {
this.vaadinVerticalLayout = vaadinVerticalLayout;
}
public ComboBox<Cliente> getSeleccionCliente() {
return seleccionCliente;
}
public void setSeleccionCliente(ComboBox<Cliente> seleccionCliente) {
this.seleccionCliente = seleccionCliente;
}
public Button getNuevo() {
return nuevo;
}
public void setNuevo(Button nuevo) {
this.nuevo = nuevo;
}
public TextField getNuevoCliente() {
return nuevoCliente;
}
public void setNuevoCliente(TextField nuevoCliente) {
this.nuevoCliente = nuevoCliente;
}
public TextField getNuevaDireccion() {
return nuevaDireccion;
}
public void setNuevaDireccion(TextField nuevaDireccion) {
this.nuevaDireccion = nuevaDireccion;
}
public TextField getNuevoTelefono() {
return nuevoTelefono;
}
public void setNuevoTelefono(TextField nuevoTelefono) {
this.nuevoTelefono = nuevoTelefono;
}
}
|
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="viewport" content="initial-scale=1,maximum-scale=1">
<!-- CSS SECTION -->
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/css/main.css">
<!-- TOOLS CSS -->
<link rel="stylesheet" type="text/css" href="/fa/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/datepicker/dist/css/bootstrap-datepicker3.standalone.min.css">
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<!-- TOOLS JS -->
<script type="text/javascript" src="/datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<script type="text/javascript" src="/datatables/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="/datatables/js/dataTables.bootstrap4.min.js"></script>
|
package nl.fifthpostulate.shortener.jackson
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
class CompoundKeyDeserializer(vararg val keyTypes: KeyType): StdDeserializer<CompoundKey>(CompoundKey::class.java) {
override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): CompoundKey {
val node: JsonNode? = p?.getCodec()?.readTree(p)
val compoundKey = CompoundKey()
keyTypes.forEachIndexed {index, keyType ->
compoundKey.register(index, keyType.value(node?.get(index)))
}
return compoundKey
}
}
sealed class KeyType {
abstract fun value(node: JsonNode?): Any?
}
class StringKey: KeyType() {
override fun value(node: JsonNode?): Any? {
return node?.asText()
}
}
class IntKey: KeyType() {
override fun value(node: JsonNode?): Any? {
return node?.asInt()
}
}
|
--
-- Database version 31 Update script
--
-- 2013-06-25
--
-- Adds support for programmatically defined page & post types
ALTER TABLE pagetemplate ADD pagetemplate_type VARCHAR(255) NULL;
ALTER TABLE posttemplate ADD posttemplate_type VARCHAR(255) NULL;
|
module Problem18Tests
( problem18Tests
) where
import Test.HUnit
import Problem18
sampleTriangle = [ [ 3 ]
, [ 7, 4 ]
, [ 2, 4, 6 ]
, [ 8, 5, 9, 3 ] ]
leftS = [ [ 7 ]
, [ 2, 4 ]
, [ 8, 5, 9 ] ]
rightS = [ [ 4 ]
, [ 4, 6 ]
, [ 5, 9, 3 ] ]
testLeftSubTriangle :: Test
testLeftSubTriangle = TestCase $ do
assertEqual "left sub-triangle" leftS (leftSubTriangle sampleTriangle)
testRightSubTriangle :: Test
testRightSubTriangle = TestCase $ do
assertEqual "right sub-triangle" rightS (rightSubTriangle sampleTriangle)
testWeight :: Test
testWeight = TestCase $ do
assertEqual "triangle weight" 51 (weight sampleTriangle)
testMaxPathSum :: Test
testMaxPathSum = TestCase $ do
assertEqual "max path sum" (23, [3, 7, 4, 9]) (maxTrianglePathSum sampleTriangle)
problem18Tests = TestList [ testLeftSubTriangle, testRightSubTriangle, testWeight, testMaxPathSum ]
|
/*-
* BSD LICENSE
*
* Copyright (c) Intel Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Simple JSON "cat" utility */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "spdk/json.h"
static void
usage(const char *prog)
{
printf("usage: %s [-c] [-f] file.json\n", prog);
printf("Options:\n");
printf("-c\tallow comments in input (non-standard)\n");
printf("-f\tformatted output (default: compact output)\n");
}
static void
print_json_error(FILE *pf, int rc, const char *filename)
{
switch (rc) {
case SPDK_JSON_PARSE_INVALID:
fprintf(pf, "%s: invalid JSON\n", filename);
break;
case SPDK_JSON_PARSE_INCOMPLETE:
fprintf(pf, "%s: incomplete JSON\n", filename);
break;
case SPDK_JSON_PARSE_MAX_DEPTH_EXCEEDED:
fprintf(pf, "%s: maximum nesting depth exceeded\n", filename);
break;
default:
fprintf(pf, "%s: unknown JSON parse error\n", filename);
break;
}
}
static int
json_write_cb(void *cb_ctx, const void *data, size_t size)
{
FILE *f = cb_ctx;
size_t rc;
rc = fwrite(data, 1, size, f);
return rc == size ? 0 : -1;
}
static void *
read_file(FILE *f, size_t *psize)
{
void *buf, *newbuf;
size_t cur_size, buf_size, rc;
buf = NULL;
cur_size = 0;
buf_size = 128 * 1024;
while (buf_size <= 1024 * 1024 * 1024) {
newbuf = realloc(buf, buf_size);
if (newbuf == NULL) {
free(buf);
return NULL;
}
buf = newbuf;
rc = fread(buf + cur_size, 1, buf_size - cur_size, f);
cur_size += rc;
if (feof(f)) {
*psize = cur_size;
return buf;
}
if (ferror(f)) {
free(buf);
return NULL;
}
buf_size *= 2;
}
free(buf);
return NULL;
}
static int
process_file(const char *filename, FILE *f, uint32_t parse_flags, uint32_t write_flags)
{
size_t size;
void *buf, *end;
ssize_t rc;
struct spdk_json_val *values;
size_t num_values;
struct spdk_json_write_ctx *w;
buf = read_file(f, &size);
if (buf == NULL) {
fprintf(stderr, "%s: file read error\n", filename);
return 1;
}
rc = spdk_json_parse(buf, size, NULL, 0, NULL, parse_flags);
if (rc <= 0) {
print_json_error(stderr, rc, filename);
free(buf);
return 1;
}
num_values = (size_t)rc;
values = calloc(num_values, sizeof(*values));
if (values == NULL) {
perror("values calloc");
free(buf);
return 1;
}
rc = spdk_json_parse(buf, size, values, num_values, &end,
parse_flags | SPDK_JSON_PARSE_FLAG_DECODE_IN_PLACE);
if (rc <= 0) {
print_json_error(stderr, rc, filename);
free(values);
free(buf);
return 1;
}
w = spdk_json_write_begin(json_write_cb, stdout, write_flags);
if (w == NULL) {
fprintf(stderr, "json_write_begin failed\n");
free(values);
free(buf);
return 1;
}
spdk_json_write_val(w, values);
spdk_json_write_end(w);
printf("\n");
if (end != buf + size) {
fprintf(stderr, "%s: garbage at end of file\n", filename);
free(values);
free(buf);
return 1;
}
free(values);
free(buf);
return 0;
}
int
main(int argc, char **argv)
{
FILE *f;
int ch;
int rc;
uint32_t parse_flags = 0, write_flags = 0;
const char *filename;
while ((ch = getopt(argc, argv, "cf")) != -1) {
switch (ch) {
case 'c':
parse_flags |= SPDK_JSON_PARSE_FLAG_ALLOW_COMMENTS;
break;
case 'f':
write_flags |= SPDK_JSON_WRITE_FLAG_FORMATTED;
break;
default:
usage(argv[0]);
return 1;
}
}
if (optind == argc) {
filename = "-";
} else if (optind == argc - 1) {
filename = argv[optind];
} else {
usage(argv[0]);
return 1;
}
if (strcmp(filename, "-") == 0) {
f = stdin;
} else {
f = fopen(filename, "r");
if (f == NULL) {
perror("fopen");
return 1;
}
}
rc = process_file(filename, f, parse_flags, write_flags);
if (f != stdin) {
fclose(f);
}
return rc;
}
|
import React from "react"
import { graphql, Link } from "gatsby"
import styled from "styled-components"
import Layout from "../../components/Layout"
import RichText from "../../components/RichText"
import PageTitleSection from "../../components/PageTitleSection"
import "./index.css"
export const query = graphql`
{
prismic {
allCasa_autonomas {
edges {
node {
background_image
content
subtitle
title
}
}
}
}
}
`
const PageWrapper = styled.section<any>`
::after {
content: " ";
display: block;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.05;
background-image: url("${(props: any) => props.backgroundImage}");
background-repeat: no-repeat;
background-position: 50% 0;
background-size: cover;
}
.house-content {
.contact-section {
display: flex;
margin: auto;
padding-bottom: 80px;
align-items: center;
justify-content: center;
div {
width: 100%;
}
.contact-text {
p {
margin: 0;
}
}
.contact-button {
display: flex;
align-items: center;
justify-content: center;
}
}
.section {
display: flex;
div {
width: 100%;
margin: auto;
}
.section-one-image {
div {
margin: 0 10px;
background: white;
padding: 10px;
border-radius: 10px;
margin-left: auto;
display: flex;
align-self: center;
width: fit-content;
img {
margin: 0;
}
}
}
.section-two-images {
div {
display: flex;
div {
margin: 0 10px;
background: white;
padding: 10px;
border-radius: 10px;
display: flex;
align-self: center;
width: fit-content;
img {
margin: 0;
}
}
}
.image-two {
justify-content: flex-end;
}
}
}
}
`
const CasaAutonomaPage = (props: any) => {
const pageContent = props.data.prismic.allCasa_autonomas.edges[0].node
return (
<Layout>
<PageTitleSection title={pageContent.title} />
<PageWrapper
className="casa-page-wrapper"
backgroundImage={pageContent.background_image.url}
>
<div className="house-content">
<div className="section">
<div className="section-text">
<div>
<RichText render={pageContent.subtitle} />
<RichText render={[pageContent.content[0]]} />
</div>
</div>
<div className="section-one-image">
<div>
<img src={pageContent.background_image.url} />
</div>
</div>
</div>
<div className="section">
<div className="section-two-images">
<div className="image-one ">
<div>
<img src={pageContent.content[3].url} />
</div>
</div>
<div className="image-two">
<div>
<img src={pageContent.content[4].url} />
</div>
</div>
</div>
<div className="section-text">
<div>
<RichText render={[pageContent.content[1]]} />
<RichText render={[pageContent.content[2]]} />
</div>
</div>
</div>
<div className="section">
<div className="section-text">
<div>
<RichText render={[pageContent.content[5]]} />
<RichText render={[pageContent.content[6]]} />
</div>
</div>
<div className="section-two-images">
<div className="image-one ">
<div>
<img src={pageContent.content[8].url} />
</div>
</div>
<div className="image-two">
<div>
<img src={pageContent.content[7].url} />
</div>
</div>
</div>
</div>
<div className="section">
<div className="section-one-image">
<div>
<img src={pageContent.content[15].url} />
</div>
</div>
<div className="section-text">
<div>
<RichText render={[pageContent.content[9]]} />
<RichText render={pageContent.content.slice(10, 15)} />
</div>
</div>
</div>
<div className="contact-section">
<div className="contact-text">
<RichText render={[pageContent.content[19]]} />
</div>
<div className="contact-button">
<div className="btn-wrapper">
<Link to={"/contact-page"}>¡Empecemos!</Link>
</div>
</div>
</div>
</div>
</PageWrapper>
</Layout>
)
}
export default CasaAutonomaPage
|
import { ObjectId } from 'mongodb';
export function normalizeDocument(
doc?: any & { _id: ObjectId },
): any & { _id: string } {
if (!doc) {
return null;
}
if (doc._id) {
doc._id = doc._id.toString();
}
return doc;
}
|
/**
* @jest-environment jsdom
*/
import createAMSClient from "../../src";
import FramedClient from "../../src/FramedClient";
jest.mock("../../src/FramedClient");
jest.mock("../../src/FramedlessClient");
describe('createAMSClient', () => {
it('Creating AMSClient on framed mode should return FramedClient', async () => {
const client = await createAMSClient({
framedMode: true,
});
expect(client.constructor.name).toEqual(FramedClient.name);;
});
it('Creating AMSClient on framedless mode should return FramedlessClient', async () => {
const client = await createAMSClient({
framedMode: false,
});
expect((client as any).iframeLoaded).toBe(undefined);
});
});
|
namespace FasTnT.Domain
{
public class EpcisMasterdataDocument : Request
{
}
}
|
# coding: utf-8
from quepy.tagger import Word
from quepy.encodingpolicy import assert_valid_encoding
import re
import logging
log = logging.getLogger( 'quepy.spacytagger' )
from neuroarch_nlp.data import neuropils, subregions, colors_values
import spacy
from spacy.attrs import LOWER
nlp = spacy.load('en')
# Go through the accepted (English) string representations of neuropil names
# and add the multi-word names to spaCy's rule-based Matcher, so we can merge
# each name as a single token (later), which will slightly simplify the grammar
for db_rep, string_reps in neuropils:
for string in string_reps:
lexes = string.split()
if len( lexes ) > 1:
# NOTE: The first parameter, the ID, could be specified as the "canonical" neuropil name
nlp.matcher.add_pattern( 'NEUROPIL',
[ {LOWER: lex.lower()} for lex in lexes ],
label='NEUROPIL' )
# Also merge multi-word subregion names and accepted (English; HTML) color names
for phrase in subregions.keys() + colors_values.keys():
phrase = phrase.split()
if len( phrase ) > 1:
nlp.matcher.add_pattern( 'SUBREGION',
[ {LOWER: lex.lower()} for lex in phrase ],
label='SUBREGION' )
compilers = [
('presynaptic', re.compile(
"pre-synaptic|pre- synaptic|pre -synaptic|pre synaptic|pre - synaptic", re.IGNORECASE )),
('postsynaptic', re.compile(
"post-synaptic|post- synaptic|post -synaptic|post synaptic|post - synaptic", re.IGNORECASE ))
]
def collapse( string ):
for substr, compiler in compilers:
string = compiler.sub( substr, string )
return string
def run_spacytagger( string ):
"""
Runs spacy on `string` and returns a list of
:class:`quepy.tagger.Word` objects.
"""
assert_valid_encoding(string)
# For now, at least, perform our own pre-processing
# --to ensure terms like "presynaptic" are easily found later.
string = ' '.join( string.split() )
string = collapse( string )
doc = nlp( string ) # NOTE: spaCy expects and returns unicode
spans = [ (ent_id, label_id, doc[start:end])
for ent_id, label_id, start, end in nlp.matcher( doc ) ]
for ent_id, label_id, span in spans:
span.merge( label=label_id, tag='NNP' if label_id else span.root.tag_ )
# tag_ is the "fine-grained" POS
words = [ Word(x.text, x.lemma_, x.tag_) for x in doc ]
# The following is only for logging purposes; if necessary, it could be removed for production
log.info( ' '.join([ t.text +'['+ str(t.i) +']' for t in doc ]) )
indent = " "
longest = max( len(t.text) for t in doc )
column = (len(doc) - 1) * len(indent) + longest + 2
wout = '{:'+ str(column) +'}| '
def trav_tree( indents, node ):
log.info( wout.format((indent * indents) + node.text) + ', '.join(
[ str(x) for x in [
node.i, node.is_oov, node.lemma_, node.tag_, \
"<-"+ str(node.left_edge), str(node.right_edge) +"->"] ]) )
for el in node.children:
# NOTE: Could also change display based on node.lefts and node.rights
trav_tree( indents + 1, el )
for sent in doc.sents:
trav_tree( 0, sent.root )
log.info( 'Ents: '+ str(doc.ents) )
log.info( 'NPs: '+ str(list(doc.noun_chunks)) )
return words
|
@model HouseholdManager.Web.Areas.Comments.Models.CommentsViewModel
@{
Layout = null;
}
@foreach (var comment in Model.Comments)
{
<div class="single-comment">
<div class="cmt-header text-left">
<strong>@comment.User</strong>
<span>Created on: @comment.CreatedOnDate.ToShortDateString()</span>
</div>
<div class="cmt-body">
<p>@comment.CommentContent</p>
</div>
</div>
}
<div class="row">
<div class="col-md-12">
@Html.Action("Create", "Comments", new { expenceId = Model.ExpenseId })
</div>
</div>
|
// File was generated from based on docs/cookbooks/scala-versions.md, do not edit manually!
object ScalaVersion extends App {
def props(url: java.net.URL): java.util.Properties = {
val properties = new java.util.Properties()
val is = url.openStream()
try {
properties.load(is)
properties
} finally is.close()
}
def scala2Version: String =
props(getClass.getResource("/library.properties")).getProperty("version.number")
def checkScala3(res: java.util.Enumeration[java.net.URL]): String =
if (!res.hasMoreElements) scala2Version else {
val manifest = props(res.nextElement)
manifest.getProperty("Specification-Title") match {
case "scala3-library-bootstrapped" =>
manifest.getProperty("Implementation-Version")
case _ => checkScala3(res)
}
}
val manifests = getClass.getClassLoader.getResources("META-INF/MANIFEST.MF")
val scalaVersion = checkScala3(manifests)
val javaVersion = System.getProperty("java.version")
println(s"Scala: $scalaVersion")
}
|
package com.lucianghimpu.matchmefy.data.networking.shared.connectivityInterceptor
import com.lucianghimpu.matchmefy.appServices.Connectivity.ConnectivityService
import okhttp3.Interceptor
import okhttp3.Response
class ConnectivityInterceptorImpl(
private val connectivityService: ConnectivityService
) : ConnectivityInterceptor {
override fun intercept(chain: Interceptor.Chain): Response {
if (!connectivityService.hasConnection()) {
throw NoConnectivityException()
}
return chain.proceed(chain.request())
}
}
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SementaraUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
// "stok" => "1"
// "tgl" => "03/22/2017"
// "kode" => "BA00001"
return [
'qty' => 'required|numeric|min:1',
'harga' => 'required|numeric|min:1',
];
}
public function messages()
{
return [
'qty.required' => 'QTY harus ada',
'qty.numeric' => 'QTY harus berupa angka',
'qty.min' => 'QTY minimal :min',
'harga.required' => 'Harga beli harus ada',
'harga.numeric' => 'Harga beli harus berupa angka',
'harga.min' => 'Harga beli minimal :min',
];
}
}
|
// Include the plugin build (composite build)
rootProject.name = "examples"
pluginManagement {
includeBuild("../plugin")
}
include("default-task")
val isCiServer = System.getenv().containsKey("CI")
// Cache build artifacts, so expensive operations do not need to be re-computed
buildCache {
local {
isEnabled = !isCiServer
}
}
|
/*
* @author : Jagepard <jagepard@yandex.ru>
* @license https://mit-license.org/ MIT
*/
using System;
namespace CsDesignPatterns_Mediator
{
public interface IMediator
{
void AddListener(AbstractListener listener, string methodName);
void Notify(string name, IHandler handler);
}
}
|
// DO NOT MODIFY FOR BASIC SUBMISSION
// scalastyle:off
package snake.game
import java.awt.event
import processing.core.{PApplet, PConstants}
import processing.event.KeyEvent
import java.awt.event.KeyEvent._
import engine.GameBase
import engine.graphics.{Color, Point, Rectangle}
import snake.game.SnakeGame._
import engine.graphics.Color._
import snake.logic.SnakeLogic
class SnakeGame extends GameBase {
var gameLogic = new SnakeLogic()
val updateTimer = new UpdateTimer(FramesPerSecond)
val widthInPixels: Int = WidthCellInPixels * gameLogic.nrColumns
val heightInPixels: Int = HeightCellInPixels * gameLogic.nrRows
val screenArea: Rectangle = Rectangle(Point(0, 0), widthInPixels, heightInPixels)
// this function is wrongly named draw by processing (is called on each update next to drawing)
override def draw(): Unit = {
updateState()
drawGrid()
if (gameLogic.isGameOver) drawGameOverScreen()
}
def drawGameOverScreen(): Unit = {
setFillColor(Red)
drawTextCentered("GAME OVER!", 20, screenArea.center)
}
def drawGrid(): Unit = {
val widthPerCell = screenArea.width / gameLogic.nrColumns
val heightPerCell = screenArea.height / gameLogic.nrRows
def getCell(colIndex: Int, rowIndex: Int): Rectangle = {
val leftUp = Point(screenArea.left + colIndex * widthPerCell,
screenArea.top + rowIndex * heightPerCell)
Rectangle(leftUp, widthPerCell, heightPerCell)
}
def getTriangleForDirection(dir: Direction, area: Rectangle) = {
dir match {
case West() => area.trianglePointingLeft
case North() => area.trianglePointingUp
case East() => area.trianglePointingRight
case South() => area.trianglePointingDown
}
}
def drawCell(area: Rectangle, cell: GridType): Unit = {
cell match {
case SnakeHead(direction) =>
setFillColor(Color.LawnGreen)
drawTriangle(getTriangleForDirection(direction, area))
case SnakeBody(p) =>
val color = Color.LawnGreen.interpolate(p,Color.DarkGreen)
setFillColor(color)
drawRectangle(area)
case Apple() =>
setFillColor(Color.Red)
drawEllipse(area)
case Empty() => ()
}
}
setFillColor(White)
drawRectangle(screenArea)
for (y <- 0 until gameLogic.nrRows;
x <- 0 until gameLogic.nrColumns) {
drawCell(getCell(x, y), gameLogic.getGridTypeAt(x, y))
}
}
/** Method that calls handlers for different key press events.
* You may add extra functionality for other keys here.
* See [[event.KeyEvent]] for all defined keycodes.
*
* @param event The key press event to handle
*/
override def keyPressed(event: KeyEvent): Unit = {
def changeDir(dir: Direction): Unit =
gameLogic.changeDir(dir)
event.getKeyCode match {
case VK_UP => changeDir(North())
case VK_DOWN => changeDir(South())
case VK_LEFT => changeDir(West())
case VK_RIGHT => changeDir(East())
case VK_R => gameLogic.setReverseTime(true)
case _ => ()
}
}
override def keyReleased(event: KeyEvent): Unit = {
event.getKeyCode match {
case VK_R => gameLogic.setReverseTime(false)
case _ => ()
}
}
override def settings(): Unit = {
pixelDensity(displayDensity())
size(widthInPixels, heightInPixels, PConstants.P2D)
}
override def setup(): Unit = {
// Fonts are loaded lazily, so when we call text()
// for the first time, there is significant lag.
// This prevents it from happening during gameplay.
text("", 0, 0)
// This should be called last, since the game
// clock is officially ticking at this point
updateTimer.init()
}
def updateState(): Unit = {
if (updateTimer.timeForNextFrame()) {
gameLogic.step()
updateTimer.advanceFrame()
}
}
}
object SnakeGame {
val FramesPerSecond: Int = 5
val WidthCellInPixels: Int = 15
val HeightCellInPixels: Int = WidthCellInPixels
def main(args: Array[String]): Unit = {
// This is needed for Processing, using the name
// of the class in a string is not very beautiful...
PApplet.main("snake.game.SnakeGame")
}
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/blob/deletable_file_reference.h"
#include <map>
#include "base/file_util.h"
#include "base/file_util_proxy.h"
#include "base/lazy_instance.h"
#include "base/message_loop_proxy.h"
namespace webkit_blob {
namespace {
typedef std::map<FilePath, DeletableFileReference*> DeleteableFileMap;
static base::LazyInstance<DeleteableFileMap> g_deletable_file_map(
base::LINKER_INITIALIZED);
} // namespace
// static
scoped_refptr<DeletableFileReference> DeletableFileReference::Get(
const FilePath& path) {
DeleteableFileMap::iterator found = g_deletable_file_map.Get().find(path);
DeletableFileReference* reference =
(found == g_deletable_file_map.Get().end()) ? NULL : found->second;
return scoped_refptr<DeletableFileReference>(reference);
}
// static
scoped_refptr<DeletableFileReference> DeletableFileReference::GetOrCreate(
const FilePath& path, base::MessageLoopProxy* file_thread) {
DCHECK(file_thread);
typedef std::pair<DeleteableFileMap::iterator, bool> InsertResult;
InsertResult result = g_deletable_file_map.Get().insert(
DeleteableFileMap::value_type(path, NULL));
if (result.second == false)
return scoped_refptr<DeletableFileReference>(result.first->second);
// Wasn't in the map, create a new reference and store the pointer.
scoped_refptr<DeletableFileReference> reference(
new DeletableFileReference(path, file_thread));
result.first->second = reference.get();
return reference;
}
DeletableFileReference::DeletableFileReference(
const FilePath& path, base::MessageLoopProxy* file_thread)
: path_(path), file_thread_(file_thread) {
DCHECK(g_deletable_file_map.Get().find(path_)->second == NULL);
}
DeletableFileReference::~DeletableFileReference() {
DCHECK(g_deletable_file_map.Get().find(path_)->second == this);
g_deletable_file_map.Get().erase(path_);
base::FileUtilProxy::Delete(file_thread_, path_, false /* recursive */, NULL);
}
} // namespace webkit_blob
|
// Copyright (c) Johnny Z. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace NetUV.Core.Requests
{
using System;
using NetUV.Core.Handles;
using NetUV.Core.Logging;
using NetUV.Core.Native;
public abstract class ScheduleRequest : IDisposable
{
internal static readonly ILog Log = LogFactory.ForContext<ScheduleHandle>();
internal ScheduleRequest(uv_req_type requestType)
{
this.RequestType = requestType;
}
public bool IsValid => this.InternalHandle != IntPtr.Zero;
public object UserToken { get; set; }
internal abstract IntPtr InternalHandle { get; }
internal uv_req_type RequestType { get; }
protected bool Cancel() =>
this.IsValid && NativeMethods.Cancel(this.InternalHandle);
protected abstract void Close();
public override string ToString() =>
$"{this.RequestType} {this.InternalHandle}";
public void Dispose()
{
if (!this.IsValid)
{
return;
}
this.UserToken = null;
this.Close();
}
}
}
|
"""
Name: TagGame
Version: 0.1
Author: D0Nater
GitHub: https://github.com/D0Nater/TagGame/
Date: 07.02.2021 (day/month/year)
Last update: 07.02.2021 (day/month/year)
Lang: Python 3.6.7
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.