text
stringlengths
27
775k
package com.programmableproduction.kafka.kotlin.testing import java.net.InetAddress import java.net.ServerSocket object PortProvider { fun appy(count: Int): Array<Int>{ return Array<Int>(count) { _ -> val serverSocket =ServerSocket(0, 0, InetAddress.getLocalHost()) val port = serverSocket.localPort serverSocket.close() port } } val one: Int = appy(1).first() }
# hr() # # Usage: # hr # # Description: # Print a horizontal line with a length matching the width of the terminal. hr() { printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' - }
package ch.hsr.ifs.gcs.mission.need.parameter import ch.hsr.ifs.gcs.support.geo.GPSPosition /** * This [Parameter] implementation is used to define a region in which a need has to take place. * * @since 1.0.0 * @author IFS Institute for Software */ class Region : Parameter<List<GPSPosition>> { override val id = "ch.hsr.ifs.gcs.mission.need.parameter.region" override lateinit var result: List<GPSPosition> override fun resultToString() = "${result.size} waypoints" override fun copy(): Region { val copy = Region() copy.result = result return copy } }
import 'package:args/command_runner.dart'; import 'package:theta/theta.dart'; class CheckForIdle extends Command { @override final name = 'checkForIdle'; @override final description = 'wait for camera to be idle after startCapture or self timer for next command'; @override void run() async { String response = await checkForIdle(); print(response); } }
package io.grpc.routeguide import java.util.logging.Logger import akka.actor.ActorSystem import akka.stream.ActorMaterializer import io.grpc.{Server, ServerBuilder} class RouteGuideServer(server: Server) { val logger: Logger = Logger.getLogger(classOf[RouteGuideServer].getName) def start(): Unit = { server.start() logger.info(s"Server started, listening on ${server.getPort}") sys.addShutdownHook { // Use stderr here since the logger may has been reset by its JVM shutdown hook. System.err.println("*** shutting down gRPC server since JVM is shutting down") stop() System.err.println("*** server shut down") } () } def stop(): Unit = { server.shutdown() } /** * Await termination on the main thread since the grpc library uses daemon threads. */ def blockUntilShutdown(): Unit = { server.awaitTermination() } } object RouteGuideServer extends App { val features = RouteGuidePersistence.parseFeatures( Thread.currentThread.getContextClassLoader.getResource("route_guide.json") ) val server = new RouteGuideServer( ServerBuilder .forPort(8980) .addService( RouteGuideGrpc.bindService( new RouteGuideService(features), scala.concurrent.ExecutionContext.global ) ) .build() ) server.start() server.blockUntilShutdown() } object RouteGuideMonixServer extends App { val features = RouteGuidePersistence.parseFeatures( Thread.currentThread.getContextClassLoader.getResource("route_guide.json") ) val server = new RouteGuideServer( ServerBuilder .forPort(8980) .addService( RouteGuideGrpcMonix.bindService( new RouteGuideMonixService(features), monix.execution.Scheduler.global ) ) .build() ) server.start() server.blockUntilShutdown() } object RouteGuideAkkaStreamServer extends App { val features = RouteGuidePersistence.parseFeatures( Thread.currentThread.getContextClassLoader.getResource("route_guide.json") ) val system = ActorSystem("RouteGuideAkkaStreamServer") implicit val materializer = ActorMaterializer.create(system) val server = new RouteGuideServer( ServerBuilder .forPort(8980) .addService( RouteGuideGrpcAkkaStream.bindService( new RouteGuideAkkaStreamService(features) ) ) .build() ) server.start() server.blockUntilShutdown() system.terminate() }
using System; using System.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NPoco; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Infrastructure.Migrations.Install; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Mappers; using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax; using Umbraco.Cms.Persistence.SqlCe; using Umbraco.Web.Composing; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Tests.TestHelpers { /// <summary> /// Provides objects for tests. /// </summary> internal partial class TestObjects { public TestObjects() { } /// <summary> /// Gets an UmbracoDatabase. /// </summary> /// <param name="logger">A logger.</param> /// <returns>An UmbracoDatabase.</returns> /// <remarks>This is just a void database that has no actual database but pretends to have an open connection /// that can begin a transaction.</remarks> public UmbracoDatabase GetUmbracoSqlCeDatabase(ILogger<UmbracoDatabase> logger) { var syntax = new SqlCeSyntaxProvider(Options.Create(new GlobalSettings())); var connection = GetDbConnection(); var sqlContext = new SqlContext(syntax, DatabaseType.SQLCe, Mock.Of<IPocoDataFactory>()); return new UmbracoDatabase(connection, sqlContext, logger, TestHelper.BulkSqlInsertProvider); } /// <summary> /// Gets an UmbracoDatabase. /// </summary> /// <param name="logger">A logger.</param> /// <returns>An UmbracoDatabase.</returns> /// <remarks>This is just a void database that has no actual database but pretends to have an open connection /// that can begin a transaction.</remarks> public UmbracoDatabase GetUmbracoSqlServerDatabase(ILogger<UmbracoDatabase> logger) { var syntax = new SqlServerSyntaxProvider(Options.Create(new GlobalSettings())); // do NOT try to get the server's version! var connection = GetDbConnection(); var sqlContext = new SqlContext(syntax, DatabaseType.SqlServer2008, Mock.Of<IPocoDataFactory>()); return new UmbracoDatabase(connection, sqlContext, logger, TestHelper.BulkSqlInsertProvider); } public IScopeProvider GetScopeProvider(ILoggerFactory loggerFactory, FileSystems fileSystems = null, IUmbracoDatabaseFactory databaseFactory = null) { var globalSettings = Options.Create(new GlobalSettings()); var connectionString = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName].ConnectionString; var connectionStrings = Options.Create(new ConnectionStrings { UmbracoConnectionString = new ConfigConnectionString(Constants.System.UmbracoConnectionName, connectionString) }); var coreDebugSettings = new CoreDebugSettings(); if (databaseFactory == null) { // var mappersBuilder = new MapperCollectionBuilder(Current.Container); // FIXME: // mappersBuilder.AddCore(); // var mappers = mappersBuilder.CreateCollection(); var mappers = Current.Factory.GetRequiredService<IMapperCollection>(); databaseFactory = new UmbracoDatabaseFactory( loggerFactory.CreateLogger<UmbracoDatabaseFactory>(), loggerFactory, globalSettings, connectionStrings, new Lazy<IMapperCollection>(() => mappers), TestHelper.DbProviderFactoryCreator, new DatabaseSchemaCreatorFactory(Mock.Of<ILogger<DatabaseSchemaCreator>>(),loggerFactory, new UmbracoVersion(), Mock.Of<IEventAggregator>())); } fileSystems ??= new FileSystems(loggerFactory, TestHelper.IOHelper, globalSettings, TestHelper.GetHostingEnvironment()); var coreDebug = TestHelper.CoreDebugSettings; var mediaFileManager = Mock.Of<MediaFileManager>(); var eventAggregator = Mock.Of<IEventAggregator>(); return new ScopeProvider(databaseFactory, fileSystems, Options.Create(coreDebugSettings), mediaFileManager, loggerFactory.CreateLogger<ScopeProvider>(), loggerFactory, NoAppCache.Instance, eventAggregator); } } }
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiHttpResponseHeader.h" PiiHttpResponseHeader::Data::Data() : httpVersion(1,1), iStatusCode(200), strReasonPhrase("OK"), bValid(true) {} PiiHttpResponseHeader::Data::Data(const Data& other) : PiiMimeHeader::Data(other), httpVersion(other.httpVersion), iStatusCode(other.iStatusCode), strReasonPhrase(other.strReasonPhrase), bValid(other.bValid) {} PiiHttpResponseHeader::Data::~Data() {} PiiHttpResponseHeader::Data* PiiHttpResponseHeader::Data::clone() const { return new Data(*this); } PiiHttpResponseHeader::PiiHttpResponseHeader() : PiiMimeHeader(new Data) {} PiiHttpResponseHeader::PiiHttpResponseHeader(const QByteArray& headerData) : PiiMimeHeader(new Data) { PII_D; QRegExp responseRe("^HTTP/(\\d\\.\\d)\\s+(\\d+)\\s+(\\S.*)\\r?$"); responseRe.setMinimal(true); int iLineBreakPos = headerData.indexOf('\n'); if (iLineBreakPos != -1 && responseRe.indexIn(QString(headerData.left(iLineBreakPos))) != -1) { d->httpVersion = PiiVersionNumber(responseRe.cap(1)); bool bStatusOk = false; d->iStatusCode = responseRe.cap(2).toInt(&bStatusOk); if (bStatusOk) { d->strReasonPhrase = responseRe.cap(3); int iRemainingLength = headerData.size() - iLineBreakPos - 1; if (iRemainingLength > 0 && !addValues(headerData.constData() + iLineBreakPos + 1, iRemainingLength)) d->bValid = false; } else d->bValid = false; } else d->bValid = false; } PiiHttpResponseHeader::PiiHttpResponseHeader(const PiiHttpResponseHeader& other) : PiiMimeHeader(other) {} PiiHttpResponseHeader::~PiiHttpResponseHeader() {} PiiHttpResponseHeader& PiiHttpResponseHeader::operator= (const PiiHttpResponseHeader& other) { PiiMimeHeader::operator= (other); return *this; } void PiiHttpResponseHeader::setStatusCode(int statusCode) { _d()->iStatusCode = statusCode; } int PiiHttpResponseHeader::statusCode() const { return _d()->iStatusCode; } void PiiHttpResponseHeader::setReasonPhrase(const QString& reasonPhrase) { _d()->strReasonPhrase = reasonPhrase; } QString PiiHttpResponseHeader::reasonPhrase() const { return _d()->strReasonPhrase; } void PiiHttpResponseHeader::setHttpVersion(const PiiVersionNumber& httpVersion) { _d()->httpVersion = httpVersion; } PiiVersionNumber PiiHttpResponseHeader::httpVersion() const { return _d()->httpVersion; } void PiiHttpResponseHeader::setStatusLine(int statusCode, const QString& reasonPhrase) { PII_D; d->iStatusCode = statusCode; d->strReasonPhrase = reasonPhrase; } QByteArray PiiHttpResponseHeader::toByteArray() const { const PII_D; QByteArray aResult; aResult.append("HTTP/"); aResult.append(d->httpVersion.toString().toLatin1()); aResult.append(' '); aResult.append(QByteArray::number(d->iStatusCode)); aResult.append(' '); aResult.append(d->strReasonPhrase.toLatin1()); aResult.append("\r\n"); aResult.append(PiiMimeHeader::toByteArray()); return aResult; } bool PiiHttpResponseHeader::isValid() const { return _d()->bValid; }
#include <catch.hpp> #include <rapidcheck/catch.h> #include <sstream> #include "util/Generators.h" #include "util/TemplateProps.h" #include "util/Serialization.h" using namespace rc; using namespace rc::test; using namespace rc::detail; namespace { template <typename T> bool messageContains(const T &msg, const std::string &substr) { std::ostringstream ss; printResultMessage(msg, ss); return ss.str().find(substr) != std::string::npos; } } // namespace TEST_CASE("CaseResult") { SECTION("operator==/operator!=") { propConformsToEquals<CaseResult>(); PROP_REPLACE_MEMBER_INEQUAL(CaseResult, type); PROP_REPLACE_MEMBER_INEQUAL(CaseResult, description); } SECTION("operator<<") { propConformsToOutputOperator<CaseResult>(); } } TEST_CASE("SuccessResult") { SECTION("operator==/operator!=") { propConformsToEquals<SuccessResult>(); PROP_REPLACE_MEMBER_INEQUAL(SuccessResult, numSuccess); PROP_REPLACE_MEMBER_INEQUAL(SuccessResult, distribution); } SECTION("operator<<") { propConformsToOutputOperator<SuccessResult>(); } SECTION("printResultMessage") { prop("message contains relevant parts of the result", [](const SuccessResult &result) { RC_ASSERT(messageContains(result, "OK")); RC_ASSERT( messageContains(result, std::to_string(result.numSuccess))); if (!result.distribution.empty()) { const auto someTag = gen::mapcat(gen::elementOf(result.distribution), [](const std::pair<const Tags, int> &entry) { return gen::elementOf(entry.first); }); RC_ASSERT(messageContains(result, *someTag)); } }); } } TEST_CASE("Reproduce") { SECTION("operator==/operator!=") { propConformsToEquals<Reproduce>(); PROP_REPLACE_MEMBER_INEQUAL(Reproduce, random); PROP_REPLACE_MEMBER_INEQUAL(Reproduce, size); PROP_REPLACE_MEMBER_INEQUAL(Reproduce, shrinkPath); } SECTION("operator<<") { propConformsToOutputOperator<Reproduce>(); } SECTION("serialization") { SerializationProperties::exec<Reproduce>(); } } TEST_CASE("FailureResult") { SECTION("operator==/operator!=") { propConformsToEquals<FailureResult>(); PROP_REPLACE_MEMBER_INEQUAL(FailureResult, numSuccess); PROP_REPLACE_MEMBER_INEQUAL(FailureResult, description); PROP_REPLACE_MEMBER_INEQUAL(FailureResult, reproduce); PROP_REPLACE_MEMBER_INEQUAL(FailureResult, counterExample); } SECTION("operator<<") { propConformsToOutputOperator<FailureResult>(); } SECTION("printResultMessage") { prop("message contains relevant parts of result", [](const FailureResult &result) { RC_ASSERT( messageContains(result, std::to_string(result.numSuccess + 1))); RC_ASSERT(messageContains(result, result.description)); RC_ASSERT( result.reproduce.shrinkPath.empty() || messageContains( result, std::to_string(result.reproduce.shrinkPath.size()))); for (const auto &item : result.counterExample) { messageContains(result, item.first); messageContains(result, item.second); } }); } } TEST_CASE("GaveUpResult") { SECTION("operator==/operator!=") { propConformsToEquals<GaveUpResult>(); PROP_REPLACE_MEMBER_INEQUAL(GaveUpResult, numSuccess); PROP_REPLACE_MEMBER_INEQUAL(GaveUpResult, description); } SECTION("operator<<") { propConformsToOutputOperator<GaveUpResult>(); } SECTION("printResultMessage") { prop("message contains relevant parts of result", [](const GaveUpResult &result) { RC_ASSERT( messageContains(result, std::to_string(result.numSuccess))); RC_ASSERT(messageContains(result, result.description)); }); } } TEST_CASE("Error") { SECTION("operator==/operator!=") { propConformsToEquals<Error>(); PROP_REPLACE_MEMBER_INEQUAL(Error, description); } SECTION("operator<<") { propConformsToOutputOperator<Error>(); } SECTION("printResultMessage") { prop("message contains relevant parts of result", [](const Error &result) { RC_ASSERT(messageContains(result, result.description)); }); } }
# Requirements - Java SDK (8) - Scala Build Tool (sbt) - http://www.scala-sbt.org/1.0/docs/Setup.html - Spark (2.2.1) - https://spark.apache.org/downloads.html - local mode Developed on an Ubuntu 16.04 linux system, using Oracle Java 8. # Usage This project uses the Scala Build Tool (sbt). To run examples, install and run the `sbt` REPL in this project directory (where the `build.sbt` file is located). The `sbt` should download all the project dependencies (any warnings about dependency conflicts can be ignored, they arise from 3rd-party dependency resolution). ### Email Spark Analysis Package a jar containing the application ```bash sbt package ... [info] Packaging {..}/{..}/target/scala-2.11/enron-emails_2.11-1.0.jar ``` Use spark-submit to run analysis (see `bin/spark_analysis.sh` for updated code) ```bash PACKAGE_JAR="target/scala-2.11/enron-emails_2.11-1.0.jar" SPARK_HOME=/opt/spark-2.2.1-bin-hadoop2.7 ${SPARK_HOME}/bin/spark-submit \ --class "SparkAnalysisApp" \ --master local[2] \ ${PACKAGE_JAR} \ enron_email_records.parquet 2> spark_analysis.log ``` # Some Resources - http://www.enronemail.com/enron-story/ ### Enron Email Data - https://www.cs.cmu.edu/~./enron/ - http://bailando.sims.berkeley.edu/enron_email.html - http://www.ahschulz.de/enron-email-data/ - http://info.nuix.com/Enron.html - "Nuix and EDRM worked together to cleanse the Enron data set of private information." - "The complete EDRM Enron Data Set is 18GB in total." ### Spark - https://www.linkedin.com/pulse/using-apache-spark-perform-sentiment-analysis-enrons-email-saunders - https://lucidworks.com/2016/12/13/analyzing-enron-with-solr-spark-and-fusion/ - https://github.com/medale/spark-mail ### Graphs - https://github.com/okram/graph-bootcamp/wiki/Enron (neo4j) - https://linkurio.us/blog/investigating-the-enron-email-dataset/ (neo4j) - https://gist.github.com/rjurney/969814 (ruby project) ### Akka - streams - https://doc.akka.io/docs/akka/current/stream/index.html - connectors - https://developer.lightbend.com/docs/alpakka/current/index.html - https://doc.akka.io/docs/akka-stream-kafka/current/home.html ### Avro - https://github.com/sksamuel/avro4s - https://github.com/hopped/akka-avro-serializer/ - https://dzone.com/articles/kafka-avro-scala-example - Kafka producer and consumer examples using AVRO data - https://hortonworks.com/blog/the-data-lifecycle-part-one-avroizing-the-enron-emails/ - https://s3.amazonaws.com/rjurney.public/enron.avro - https://github.com/rjurney/Agile_Data_Code/blob/master/ch03/gmail/email.avro.schema ### Eel - https://github.com/51zero/eel-sdk "Eel is a toolkit for manipulating data in the hadoop ecosystem. By hadoop ecosystem we mean file formats common to the big-data world, such as parquet, orc, csv in locations such as HDFS or Hive tables. In contrast to distributed batch or streaming engines such as Spark or Flink, Eel is an SDK intended to be used directly in process." ### ElasticSearch - https://github.com/sksamuel/elastic4s ### Gmail analysis - https://github.com/rjurney/Agile_Data_Code/tree/master/ch03 - Pig, MongoDB, ElasticSearch ### Scala SQL - https://github.com/aselab/scala-activerecord - https://github.com/aselab/scala-activerecord-sample/tree/master/sample/src/main/scala
package Aula07 class Atleta(var nome: String, var nivel: Int, var energia: Int) { }
/* * Copyright (C) 2015 - 2020 Lightbend Inc. <https://www.lightbend.com> */ package com.typesafe.sslconfig.ssl import java.security.KeyStore import javax.net.ssl._ object FakeSSLTools { /** * NOT FOR PRODUCTION USE. Builds a "TLS" `SSLContext` and `X509TrustManager` initializing both with the keys and * certificates in the provided `KeyStore`. This means the `SSLContext` will produce `SSLEngine`'s, `SSLSocket``s * and `SSLServerSocket`'s that will use a `KeyPair` from the `KeyStore`, and will trust any `trustedCertEntry` * in the `KeyStore`. * * This is a naïve implementation for testing purposes only. */ def buildContextAndTrust(keyStore: KeyStore): (SSLContext, X509TrustManager) = { val kmf: KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm) kmf.init(keyStore, Array.emptyCharArray) val kms: Array[KeyManager] = kmf.getKeyManagers val tmf: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm) tmf.init(keyStore) val tms: Array[TrustManager] = tmf.getTrustManagers val x509TrustManager: X509TrustManager = tms(0).asInstanceOf[X509TrustManager] val sslContext: SSLContext = SSLContext.getInstance("TLS") sslContext.init(kms, tms, null) (sslContext, x509TrustManager) } }
export const getHistory = state => state.history; export const getId = state => state.history.id; export const getAnnotationId = state => state.history.annotationstartId; export const getAnnotationEntry = state => state.history.annotationstartEntry; export const getAllAnnotations = state => state.history.annotations;
{ So does anyone have any good read-write routines that will read/write words of bit legnths 9-13? } function add_code : integer; const Input_bit_count : integer = 0; Inbuf : longint =0; var i : longint; begin while input_bit_count <= 24 do begin i := getnextbyte; { shftL/R is an asm longint shift } InBuf := InBuf or shftL(i,24-input_bit_count); inc(input_bit_count,8); end; i := shftR(InBuf,32-num_bits); InBuf := shftL(InBuf,num_bits); input_bit_count := input_bit_count -num_bits; add_code := i; end; procedure add_code (code:word); const bits : integer = 0; begin lz_buffer[lz_cnt] := lo(bit_buf or (code shl bits)); inc(lz_cnt); if (code_len + bits) < 16 then begin bit_buf := lo(code shr (8-bits)); bits := bits +code_len -8; end else begin lz_buffer[lz_cnt] := lo(code shr (8-bits)); inc(lz_cnt); bit_buf := lo(code shr (16-bits)); bits := (bits + code_len -16); end; end; 
Snd_DDZ2_Header: smpsHeaderStartSong 3, 1 smpsHeaderVoice Snd_DDZ2_Voices smpsHeaderChan $06, $03 smpsHeaderTempo $01, $1D smpsHeaderDAC Snd_DDZ2_DAC smpsHeaderFM Snd_DDZ2_FM1, $00, $0E smpsHeaderFM Snd_DDZ2_FM2, $0C, $0E smpsHeaderFM Snd_DDZ2_FM3, $00, $1B smpsHeaderFM Snd_DDZ2_FM4, $00, $1B smpsHeaderFM Snd_DDZ2_FM5, $00, $14 smpsHeaderPSG Snd_DDZ2_PSG1, $E8, $03, $00, $00 smpsHeaderPSG Snd_DDZ2_PSG2, $E8, $03, $00, $00 smpsHeaderPSG Snd_DDZ2_PSG3, $23, $02, $00, $00 ; FM1 Data Snd_DDZ2_FM1: smpsPan panCenter, $00 smpsModSet $01, $01, $01, $04 dc.b nRst, $60, nRst Snd_DDZ2_Jump01: smpsSetvoice $00 dc.b nC6, $09, nB5, $03, nA5, $02, nG5, nF5, nE5, nD5, $01, nC5 dc.b $02, nB4, $01, nF4, $06, nRst, nE4, nRst, nD4, $12, nE4, $06 dc.b nRst, $0C, nF4, $06, nRst, nF4, nRst, nE4, nRst, nD4, $12, nE4 dc.b $06, nRst, nG3, $12, nC4, $06, nRst, nE4, nRst, nEb4, $12, nF4 dc.b $06, nRst, $0C, nC4, nRst, $06, nAb3, $12, nC4, $0C, nEb4, nD4 dc.b $12, nBb3, nF4, $06, nRst, $0C, $06, nRst, $0C, nBb4, $18 smpsLoop $00, $02, Snd_DDZ2_Jump01 dc.b nC5, $44, nRst, $04, nB4, $10, nG4, $08, smpsNoAttack, $24, nF4, $02 dc.b nG4, $16, nF4, $0C, nE4, nF4, nG4, nFs4, nG4, nC4, $10, nRst dc.b $08, $06, nRst, $06, nD4, nRst, nE4, nRst, nD4, $18, $06, nRst dc.b $06, nBb3, $3C, nC5, $30, nB4, $0C, nC5, nB4, nC5, $06, nG4 dc.b smpsNoAttack, nG4, $24, nFs4, $05, nG4, $13, nF4, $0C, nE4, nF4, nG4 dc.b $12, nC5, $06, nRst, $0C, nC4, nRst, nC4, nD4, nE4, nF4, $12 dc.b nE4, nF4, $06, nRst, $0C, $12, nG4, $18, nC4, $09, nB3, $03 dc.b nA3, $02, nG3, nF3, nE3, nD3, nC3, nB2, nA2, $03, nG2, $04 dc.b nRst, $24, nG4, $03, nC5, $12, nC4, $06, nRst, $60, nC4, $0C dc.b nRst, $39, nG4, $03, nC5, $12, nC4, $06, nRst, $60, nRst smpsSetvoice $03 dc.b nG4, $24, nAb4, $0C, $30, nRst, $0C, nG4, nAb4, nBb4, nC5, $12 dc.b nCs5, nCs5, $06, nEb5, nEb5, $30, $03, nF5, $15, nEb5, $0C, nCs5 dc.b nC5, $2A, nRst, $06, $18, nBb4, $0C, nAb4, nG4, $24, nAb4, $06 dc.b nRst, nAb4, $30, nRst, $0C, nG4, nAb4, nC5, nEb5, $12, nCs5, nC5 dc.b $06, nRst, nG5, $24, nEb5, nBb5, $0C, nEb5, smpsNoAttack, nEb5, $2A, nRst dc.b $06, nCs5, $1A, nC5, $0C, nRst, $0A, nC5, $24, nCs5, $04, nRst dc.b $08, $30, smpsNoAttack, nCs5, $2A, nRst, $06, nC5, $10, nRst, $08, nBb4 dc.b $0C, nAb4, nAb4, $25, nG4, $06, nRst, nG4, $12, nEb5, nCs5, $0B dc.b nC5, $30, $18, nBb4, $0C, nAb4, nF4, $30, nAb4, nCs5, nF5, nG4 dc.b nEb5, nAb5, nG5, nAb5, $60, smpsNoAttack, nAb5, smpsNoAttack, nAb5, nAb3, $18, nB3 dc.b nCs4, nEb4 smpsJump Snd_DDZ2_Jump01 ; FM2 Data Snd_DDZ2_FM2: smpsPan panCenter, $00 smpsModSet $01, $01, $01, $02 smpsSetvoice $01 dc.b nC1, $06, nRst, nC1, nRst, nC2, $0C, nC1, $06, $0C, nC2, $06 dc.b nC1, nRst, nC2, $0C, nC1, nC1, $06, nRst, nC1, nRst, nC2, $0C dc.b nC1, $06, $0C, nC2, $06, nC1, nRst, nC2, $0C, nC1, $06, nC1 Snd_DDZ2_Loop03: dc.b nC1, $06, nRst, nC1, nRst, nC2, $0C, nC1, $06, $0C, nC2, $06 dc.b nC1, nRst, nC2, $0C, nC1, $06, nC1, nC1, nRst, nC1, nRst, nC2 dc.b $0C, nC1, $06, $0C, nC2, $06, nC1, nRst, nG1, nC2, nG2, nG1 dc.b nAb1, nRst, nAb1, nRst, nAb2, $0C, nAb1, $06, nAb1, nRst, nAb2, nAb2 dc.b nRst, nAb1, nEb2, nAb2, nAb1, nBb1, $0C, nRst, $06, nAb1, $0C, nRst dc.b $06, nG1, $0C, nRst, $06, nF1, $0C, nRst, $06, nF2, nEb2, nD2 dc.b nBb1 smpsLoop $00, $02, Snd_DDZ2_Loop03 dc.b nC1, $0C, $06, nC1, nBb1, nC2, nC1, nC1, $0C, $06, nC2, nRst dc.b nBb1, nA1, nG1, nF1, nC1, $0C, $06, nC1, nBb1, nC2, nC1, nC1 dc.b nRst, nC1, nC2, nRst, nEb2, nE2, nG2, nBb1, nF1, $0C, $06, nF1 dc.b nEb2, nF2, nF1, nF1, nRst, nF1, nF2, nF1, nC2, nA1, nF2, nRst dc.b nG1, $0C, $06, nG1, nF2, nG2, nG1, nG1, nRst, nG1, nG2, nG1 dc.b nF2, nE2, nD2, nBb1, nC1, $0C, $06, nC1, nBb1, nC2, nC1, nC1 dc.b $0C, $06, nC2, nRst, nBb1, nA1, nG1, nF1, nC1, $0C, $06, nC1 dc.b nBb1, nC2, nC1, nC1, nRst, nC1, nC2, nRst, nEb2, nE2, nG2, nBb1 dc.b nF1, $0C, $06, nF1, nEb2, nF2, nF1, nF1, nRst, nF1, nF2, nF1 dc.b nC2, nA1, nF2, nRst, nD2, $12, nC2, nB1, nG1, nG1, $06, nD2 dc.b nG2, nG1 Snd_DDZ2_Loop04: dc.b nC1, $06, nRst, nC1, nRst, nC2, $0C, nC1, $06, $0C, nC2, $06 dc.b nC1, nRst, nC2, $0C, nC1 smpsLoop $00, $03, Snd_DDZ2_Loop04 dc.b nEb2, $12, nEb2, $06, nRst, $0C, $12, nF2, nF2, $06, nRst, nRst dc.b $0C, nRst, $60, nCs1, $12, $06, nAb1, nRst, nCs2, $3C, nRst, $0C dc.b nCs1, $06, nRst, nCs1, nAb1, nCs2, nAb1, nF2, $12, nEb2, nAb1, $0C dc.b nCs1, $12, $06, nAb1, nRst, nCs2, $3C, nRst, $0C, nCs1, nAb1, nCs2 dc.b nEb2, $03, nF2, $0F, nEb2, $12, nAb1, $0C, nCs1, $12, $06, nAb1 dc.b nRst, nCs2, $3C, nA2, $03, nBb2, $15, nAb2, $18, nG2, $12, nCs2 dc.b nAb1, $0C, nCs1, $12, $06, nG1, nAb1, nCs2, $3C, nRst, $0C, nCs1 dc.b nAb1, nCs2, nEb2, $03, nF2, $0F, nEb2, $12, nAb1, $0C, nCs2, $12 dc.b $06, nAb2, nRst, nCs3, $18, nCs2, $06, nRst, nAb2, nRst, nCs3, $0C dc.b nCs2, $12, $06, nAb2, nRst, nCs3, $18, nCs2, $06, nRst, nAb2, nRst dc.b nCs3, nRst, nC2, $12, $06, nG2, nBb2, nC3, $18, $0C, nBb2, nG2 dc.b nF2, $06, nRst, nF2, nRst, nAb2, nRst, nF2, nRst, nC3, $12, nBb2 dc.b nAb2, $0C, nCs2, $12, $06, nAb2, nRst, nCs3, $3C, nCs2, $12, $06 dc.b nG2, nAb2, nCs3, $18, $0C, nC3, nAb2, nEb2, $12, $06, nG2, nRst dc.b nBb2, $18, nEb2, $06, nRst, nEb2, nG2, nBb2, $0C, nCs3, $03, nEb3 dc.b $15, nCs3, $18, $03, nEb3, nCs3, $06, nC3, nAb2, nBb2, nAb2, nG2 dc.b nEb2, nAb1, nRst, nAb1, nRst, $12, nFs2, $06, nAb2, nRst, nAb1, $0C dc.b nRst, $06, $0C, nRst, $06, nAb1, nRst, $0C, nAb1, $06, nRst, $12 dc.b nFs2, $06, nAb2, nRst, nAb1, $0C, $06, nFs1, nCs1, nEb1, nFs1, nAb1 dc.b nRst, nAb1, nRst, $12, nFs2, $06, nAb2, nRst, nAb1, $0C, nRst, $06 dc.b $0C, nRst, $06, nAb1, nAb1, $18, nB1, nCs2, nEb2 smpsJump Snd_DDZ2_Loop03 ; FM3 Data Snd_DDZ2_FM3: smpsPan panLeft, $00 smpsModSet $01, $01, $01, $06 smpsSetvoice $02 smpsFMAlterVol $03 dc.b nC4, $06, nC4, nC5, nC5, nC4, nC5, nC5, nC4, nG5, nG5, nC4 dc.b nC5, nC4, nE5, nC5, nG4, nG5, nG5, nG4, nC5, nE4, nC5, nC5 dc.b nC4, nG5, nG5, nG4, nC5, nG4, nG4, nG4, nC4 smpsFMAlterVol $FD Snd_DDZ2_Loop02: dc.b nC4, $06, nC4, nC5, nC5, nC4, nC5, nC5, nC4, nE5, nE5, nC4 dc.b nE5, $12, $06, nE5, nC4, nC4, nC5, nC5, nC4, nC5, nC5, nC4 dc.b nE5, nE5, nC4, nE5, $0C, nRst, $06, nG4, nE4, nAb3, nAb3, nEb4 dc.b nEb4, nAb3, nG4, nG4, nAb3, nAb4, nAb4, nC4, nEb4, nEb4, nAb3, nAb3 dc.b nAb3, nBb4, $12, nAb4, nG4, nF4, nD4, $18 smpsLoop $00, $02, Snd_DDZ2_Loop02 dc.b nC3, $18, nC4, nG4, nC5, nC6, nG5, nC5, nC4, nF3, nC4, nA4 dc.b nF5, nD4, nG4, nBb4, nG5, nC3, nC4, nG4, nC5, nC6, nG5, nC5 dc.b nC4, nF3, nC4, nA4, nF5, nG3, $12, nD4, nB4, $06, nRst, $0C dc.b nD5, $06, nRst, $0C, $18, nC4, $60, smpsNoAttack, nC4, nC4, nEb4, $12 dc.b nEb4, $06, nRst, $0C, $06, nRst, $0C, nD4, $06, nRst, $0C, $18 dc.b nRst, $60 smpsSetvoice $04 smpsPan panCenter, $00 smpsFMAlterVol $FD dc.b nCs2, $18, nAb2, $06, nCs3, nEb3, nF3, nAb3, nCs4, nEb4, nF4, nAb4 dc.b nCs5, nEb5, nF5, nAb5, $60, nEb2, $18, nBb2, $06, nEb3, nG3, nBb3 dc.b nEb4, nG3, nBb3, nEb4, nG4, nBb4, nEb5, nG5, nBb5, nAb5, nG5, nEb5 dc.b nBb4, nG4, nEb4, nBb3, nG4, nEb4, nBb3, nG3, nEb3, nBb2, nG2, nEb2 dc.b nCs2, nF2, nAb2, nCs3, nF3, nAb3, nCs4, nEb4, nF4, nCs3, nF3, nAb3 dc.b nCs4, nEb4, nAb4, nCs5, nF5, nCs5, nAb4, nF4, nCs5, nAb4, nF4, nCs4 dc.b nAb4, nF4, nCs4, nAb3, nF4, nCs4, nAb3, nF3, nBb4, $18, nAb4, nG4 dc.b nEb4, nEb5, nCs5, nBb4, nG4 smpsFMAlterVol $03 smpsPan panLeft, $00 smpsSetvoice $02 dc.b nAb3, $0C, nAb3, nCs4, nF4, nAb4, $12, nF5, nCs5, $0C, nBb3, nBb3 dc.b nEb4, nG4, nBb4, $12, nG5, nEb5, $0C, nG3, nG3, nC4, nEb4, nC5 dc.b $12, nG4, nEb4, $0C, nF3, nF3, nC4, nF4, nC5, $12, nAb4, nF4 dc.b $0C, $06, nF4, nF4, nRst, $0C, $06, nRst, $0C, $16, nRst, $1A dc.b $06, nF4, nF4, nRst, $0C, $06, nRst, $0C, $16, nRst, $1A, nG4 dc.b $06, nG4, nG4, nRst, $0C, $06, nRst, $0C, $16, nRst, $1A, nBb4 dc.b $18, nAb4, nG4, nEb4, nEb4, $60, nD4, $5A, nRst, $06, nEb4, $60 dc.b nEb3, $18, nFs3, nF3, nBb3 smpsJump Snd_DDZ2_Loop02 ; FM4 Data Snd_DDZ2_FM4: smpsPan panRight, $00 smpsModSet $01, $01, $01, $05 smpsSetvoice $02 smpsFMAlterVol $03 dc.b nG3, $06, nG3, nG4, nG4, nG3, nG4, nG4, nG3, nC5, nC5, nG3 dc.b nG4, nG3, nC5, nG4, nC4, nC5, nC5, nC4, nG4, nC4, nG4, nG4 dc.b nG3, nC5, nC5, nC4, nG4, nC4, nE4, nE4, nG3 smpsFMAlterVol $FD Snd_DDZ2_Loop01: dc.b nG3, $06, nG3, nG4, nG4, nG3, nG4, nG4, nG3, nG4, nG4, nG3 dc.b nG4, $12, $06, nG4, nG3, nG3, nG4, nG4, nG3, nG4, nG4, nG3 dc.b nG4, nG4, nG3, nG4, $0C, nRst, $06, nC4, nC4, nEb3, nEb3, nC4 dc.b nC4, nEb3, nEb4, nEb4, nEb3, nEb4, nEb4, nAb3, nC4, nC4, nEb3, nEb3 dc.b nEb3, nF4, $12, nEb4, nEb4, nD4, nBb3, $18 smpsLoop $00, $02, Snd_DDZ2_Loop01 dc.b nC2, $18, nG3, nC4, nG4, nG5, nC5, nG4, nG3, nC3, nA3, nF4 dc.b nC5, nG3, nBb3, nD4, nD5, nC2, nG3, nC4, nG4, nG5, nC5, nG4 dc.b nG3, nC3, nA3, nF4, nC5, nD3, $12, nB3, nG4, $06, nRst, $0C dc.b $06, nRst, $0C, $18, nG3, $60, smpsNoAttack, nG3, nG3, nAb3, $12, nAb3 dc.b $06, nRst, $0C, $06, nRst, $0C, nBb3, $06, nRst, $0C, $18, nRst dc.b $60 smpsSetvoice $04 smpsFMAlterVol $FD smpsFMAlterVol $05 smpsPan panCenter, $00 dc.b nRst, $0B, nCs2, $18, nAb2, $06, nCs3, nEb3, nF3, nAb3, nCs4, nEb4 dc.b nF4, nAb4, nCs5, nEb5, nF5, nAb5, $60, nEb2, $18, nBb2, $06, nEb3 dc.b nG3, nBb3, nEb4, nG3, nBb3, nEb4, nG4, nBb4, nEb5, nG5, nBb5, nAb5 dc.b nG5, nEb5, nBb4, nG4, nEb4, nBb3, nG4, nEb4, nBb3, nG3, nEb3, nBb2 dc.b nG2, nEb2, nCs2, nF2, nAb2, nCs3, nF3, nAb3, nCs4, nEb4, nF4, nCs3 dc.b nF3, nAb3, nCs4, nEb4, nAb4, nCs5, nF5, nCs5, nAb4, nF4, nCs5, nAb4 dc.b nF4, nCs4, nAb4, nF4, nCs4, nAb3, nF4, nCs4, nAb3, nF3, nEb4, $18 dc.b nEb4, nEb4, nBb3, nBb4, nBb4, nG4, nEb4, $0D smpsFMAlterVol $FB smpsFMAlterVol $03 smpsPan panRight, $00 smpsSetvoice $02 dc.b nAb3, $0C, nAb3, nCs4, nF4, nAb4, $12, nF5, nCs5, $0C, nBb3, nBb3 dc.b nEb4, nG4, nBb4, $12, nG5, nEb5, $0C, nG3, nG3, nC4, nEb4, nC5 dc.b $12, nG4, nEb4, $0C, nF3, nF3, nC4, nF4, nC5, $12, nAb4, nF4 dc.b $0C, nCs4, $06, nCs4, nCs4, nRst, $0C, $06, nRst, $0C, $16, nRst dc.b $1A, $06, nCs4, nCs4, nRst, $0C, $06, nRst, $0C, $16, nRst, $1A dc.b nEb4, $06, nEb4, nEb4, nRst, $0C, $06, nRst, $0C, $16, nRst, $1A dc.b $18, nEb4, nBb3, nBb3, nAb3, $60, nAb3, $5A, nRst, $06, nAb3, $60 dc.b nC4, $18, nEb4, nCs4, nG3 smpsJump Snd_DDZ2_Loop01 ; FM5 Data Snd_DDZ2_FM5: smpsModSet $01, $01, $01, $08 dc.b nRst, $0B, nRst, $60, nRst smpsAlterNote $01 smpsJump Snd_DDZ2_Jump01 ; Unreachable smpsStop ; PSG1 Data Snd_DDZ2_PSG1: smpsModSet $02, $01, $01, $05 smpsPSGvoice sTone_11 dc.b nRst, $60, nRst Snd_DDZ2_Jump03: dc.b nC6, $09, nB5, $03, nA5, $02, nG5, nF5, nE5, nD5, nC5, nB4 dc.b nA4, nG4, nF4, $01, nE4, $02, nD4, nC4, $01, nB3, nA3, nG3 dc.b $02, nRst, $38, nRst, $60, nC5, nAb5, $12, nG5, nF5, $06, nRst dc.b $0C, nEb5, $06, nRst, $0C, nD5, $18, nC6, $09, nB5, $03, nA5 dc.b $02, nG5, nF5, nE5, nD5, nC5, nB4, nA4, nG4, nF4, $01, nE4 dc.b $02, nD4, nC4, $01, nB3, nA3, nG3, $02, nRst, $38, nRst, $60 dc.b nC5, $24, nG5, $18, nF5, nEb5, $0C, nBb5, $12, nAb5, $06, nRst dc.b $0C, nG5, $06, nRst, $0C, nF5, $12, nEb5, $06, nD5, nBb4, $0C dc.b nC4, $60, nC5, nC4, nD4, nC4, nC5, nC4, nD4, $06, nRst, $0C dc.b $06, nRst, $0C, $06, nRst, $0C, nG4, $06, nRst, $0C, $18, nC4 dc.b $30, nG4, nF5, nE5, nC4, nG4, nEb4, $12, nEb4, $06, nRst, $0C dc.b $06, nRst, $0C, nD4, $06, nRst, $0C, $18, nRst, $60, nF4, $60 dc.b smpsNoAttack, nF4, nG4, smpsNoAttack, nG4, nF4, smpsNoAttack, nF4, nG4, smpsNoAttack, nG4, nCs5 dc.b $12, nCs5, $06, nRst, $0C, $3C, nEb5, $12, nEb5, $06, nRst, $0C dc.b nEb5, nEb5, $18, nCs5, nC5, $12, nC5, $06, nRst, $0C, $24, nG5 dc.b $18, nF5, $0C, nG5, nAb5, $48, nCs5, $12, $06, nRst, $06, nC5 dc.b $12, nCs5, $30, $12, $06, nRst, $06, nC5, $12, nCs5, $30, nEb5 dc.b $06, nEb5, nEb5, nRst, $0C, nCs5, $12, nEb5, $16, nRst, $1A, nBb4 dc.b $18, nBb4, nEb5, nEb5, nAb5, $30, nC5, nD5, $5A, nRst, $06, nAb5 dc.b $30, nC5, nAb4, $18, nB4, nCs5, nEb5 smpsJump Snd_DDZ2_Jump03 ; PSG2 Data Snd_DDZ2_PSG2: smpsModSet $02, $01, $01, $05 smpsPSGvoice sTone_11 dc.b nRst, $60, nRst Snd_DDZ2_Jump02: smpsPSGvoice sTone_11 dc.b nRst, $0D smpsPSGAlterVol $02 dc.b nC6, $09, nB5, $03, nA5, $02, nG5, nF5, nE5, nD5, nC5, nB4 dc.b nA4, nG4, nF4, $01, nE4, $02, nD4, nC4, $01, nB3, nA3, nG3 dc.b $02, nRst, $38, nRst, $60, nAb4, nF5, $12, nEb5, nD5, $06, nRst dc.b $0C, nC5, $06, nRst, $0C, nBb4, $18, nC6, $09, nB5, $03, nA5 dc.b $02, nG5, nF5, nE5, nD5, nC5, nB4, nA4, nG4, nF4, $01, nE4 dc.b $02, nD4, nC4, $01, nB3, nA3, nG3, $02, nRst, $38, nRst, $60 dc.b nAb4, $24, nEb5, $18, nD5, nC5, $0C, nG5, $12, nF5, $06, nRst dc.b $0C, nEb5, $06, nRst, $0C, nD5, $12, nC5, $06, nBb4, nG4, $0C smpsPSGAlterVol $FE dc.b nG3, $53, nG4, $60, nF3, nG3, nG3, nG4, nF3, nG3, $06, nRst dc.b $0C, $06, nRst, $0C, $06, nRst, $0C, nD4, $06, nRst, $0C, $18 dc.b nRst, $0D smpsPSGAlterVol $02 dc.b nC4, $30, nG4, nF5, nE5, nC4, nG4, nEb4, $12, nEb4, $06, nRst dc.b $0C, $06, nRst, $0C, nD4, $06, nRst, $0C, $18, nRst, $53 smpsPSGAlterVol $FE dc.b nCs4, $60, smpsNoAttack, nCs4, nEb4, smpsNoAttack, nEb4, nCs4, smpsNoAttack, nCs4, nEb4, smpsNoAttack dc.b nEb4, nAb4, $12, nAb4, $06, nRst, $0C, $3C, nBb4, $12, nBb4, $06 dc.b nRst, $0C, nBb4, nBb4, $18, nBb4, nG4, $12, nG4, $06, nRst, $0C dc.b $24, nC5, $18, $0C, nC5, nC5, $48, nAb4, $12, $06, nRst, $06 dc.b $12, $30, $12, $06, nRst, $06, $12, $30, nBb4, $06, nBb4, nBb4 dc.b nRst, $0C, $12, $16, nRst, $1A, nG4, $18, nG4, nG4, nG4, nC5 dc.b $30, nEb4, nF4, $5A, nRst, $06, nC5, $30, nEb4, nEb4, $18, nFs4 dc.b nAb4, nBb4 smpsJump Snd_DDZ2_Jump02 ; PSG3 Data Snd_DDZ2_PSG3: smpsPSGform $E7 smpsNoteFill $16 Snd_DDZ2_Loop05: smpsCall Snd_DDZ2_Call00 smpsLoop $00, $02, Snd_DDZ2_Loop05 Snd_DDZ2_Loop06: smpsCall Snd_DDZ2_Call00 smpsLoop $00, $03, Snd_DDZ2_Loop06 smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF, $12, (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF, $06, nRst, nRst, (nMaxPSG2-$23)&$FF, nRst, nRst smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF, $18 smpsLoop $01, $02, Snd_DDZ2_Loop06 Snd_DDZ2_Loop07: smpsCall Snd_DDZ2_Call00 smpsLoop $00, $0B, Snd_DDZ2_Loop07 smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF, $12 smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF, $06, nRst, nRst, (nMaxPSG2-$23)&$FF, nRst, nRst, nRst, (nMaxPSG2-$23)&$FF, nRst smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF, $18, nRst, $60 Snd_DDZ2_Loop08: smpsCall Snd_DDZ2_Call00 smpsLoop $00, $08, Snd_DDZ2_Loop08 Snd_DDZ2_Loop09: smpsCall Snd_DDZ2_Call00 smpsLoop $00, $08, Snd_DDZ2_Loop09 Snd_DDZ2_Loop0A: smpsCall Snd_DDZ2_Call00 smpsLoop $00, $03, Snd_DDZ2_Loop0A smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF, $18, (nMaxPSG2-$23)&$FF, (nMaxPSG2-$23)&$FF, (nMaxPSG2-$23)&$FF smpsJump Snd_DDZ2_Loop06 Snd_DDZ2_Call00: smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF, $0C smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_0F dc.b (nMaxPSG2-$23)&$FF smpsPSGvoice sTone_12 dc.b (nMaxPSG2-$23)&$FF smpsReturn ; DAC Data Snd_DDZ2_DAC: dc.b dCrashCymbal, $18, dSnareS3, dKickS3, dSnareS3, dKickS3, dSnareS3, dKickS3, dSnareS3 Snd_DDZ2_Jump00: dc.b dCrashCymbal, $18, dSnareS3, dKickS3, dSnareS3, dKickS3, $18, dSnareS3, dKickS3, dSnareS3, dKickS3, $18 dc.b dSnareS3, dKickS3, dSnareS3, dKickS3, $06, nRst, nRst, dSnareS3, nRst, nRst, dKickS3, nRst dc.b nRst, dSnareS3, nRst, nRst smpsPan panLeft, $00 dc.b dElectricHighTom, dElectricMidTom smpsPan panCenter, $00 dc.b dElectricLowTom smpsPan panRight, $00 dc.b dElectricFloorTom smpsPan panCenter, $00 dc.b dCrashCymbal, $18, dSnareS3, dKickS3, dSnareS3, dKickS3, $18, dSnareS3, dKickS3, dSnareS3, dKickS3, $18 dc.b dSnareS3, dKickS3, dSnareS3, dSnareS3, $03, dSnareS3, $03, nRst, $06, dKickS3, dSnareS3, $03 dc.b dSnareS3, $03, nRst, $06, dKickS3, dKickS3, nRst, nRst, dSnareS3, nRst, nRst smpsPan panLeft, $00 dc.b dElectricMidTom smpsPan panCenter, $00 dc.b dElectricLowTom smpsPan panRight, $00 dc.b dElectricFloorTom, nRst smpsPan panCenter, $00 dc.b dKickS3, $06, nRst, nRst, nRst, dSnareS3, nRst, nRst, dKickS3, nRst, nRst, dKickS3 dc.b nRst, dSnareS3, nRst, nRst, nRst, dKickS3, $06, nRst, nRst, nRst, dSnareS3, nRst dc.b nRst, dKickS3, nRst, dSnareS3, dKickS3, nRst, dSnareS3, nRst, nRst, nRst, dKickS3, $06 dc.b nRst, nRst, nRst, dSnareS3, nRst, nRst, dKickS3, nRst, nRst, dKickS3, nRst, dSnareS3 dc.b nRst, nRst, nRst, dKickS3, $06, nRst, nRst, nRst, dSnareS3, nRst, nRst, dKickS3 dc.b nRst, dSnareS3, dKickS3, nRst, dSnareS3, nRst, dSnareS3, dSnareS3, dCrashCymbal, $06, nRst, nRst dc.b nRst, dSnareS3, nRst, nRst, dKickS3, nRst, nRst, dKickS3, nRst, dSnareS3, nRst, nRst dc.b nRst, dKickS3, $06, nRst, nRst, nRst, dSnareS3, nRst, nRst, dKickS3, nRst, dSnareS3 dc.b dKickS3, nRst, dSnareS3, nRst, nRst, nRst, dKickS3, $06, nRst, nRst, nRst, dSnareS3 dc.b nRst, nRst, dKickS3, nRst, nRst, dKickS3, nRst, dSnareS3, nRst, nRst, nRst, dKickS3 dc.b $06, nRst, nRst, nRst, dSnareS3, nRst, nRst, dKickS3, nRst, nRst, dKickS3, nRst dc.b dSnareS3, nRst, nRst, nRst, dKickS3, $06, nRst, nRst, nRst, dSnareS3, nRst, nRst dc.b dKickS3, nRst, nRst, dKickS3, nRst, dSnareS3, nRst, nRst, nRst, dKickS3, nRst, nRst dc.b nRst, dSnareS3, nRst, nRst, dKickS3, nRst, dSnareS3, dKickS3, nRst, dSnareS3, nRst, nRst dc.b nRst, dKickS3, nRst, nRst, nRst, dSnareS3, nRst, nRst, dKickS3, nRst, nRst, dKickS3 dc.b nRst, dSnareS3, nRst, nRst, nRst, dSnareS3, nRst, dKickS3, dSnareS3, nRst, dKickS3, dSnareS3 dc.b nRst, nRst, dKickS3, nRst, nRst, dKickS3, nRst, dKickS3, nRst, dKickS3, dKickS3, nRst dc.b dKickS3, dSnareS3, $04, dSnareS3, $02, nRst, $06, nRst, dSnareS3 smpsPan panLeft, $00 dc.b dElectricMidTom, $03, dElectricMidTom, $03, nRst, $06, nRst, dElectricMidTom smpsPan panRight, $00 dc.b dElectricLowTom, dElectricLowTom, dElectricFloorTom, nRst smpsPan panCenter, $00 dc.b dKickS3, $12, dKickS3, dKickS3, $3C, nRst, $0C, dKickS3, dSnareS3, $24, dKickS3, $0C dc.b dSnareS3, $02, $16, dKickS3, $12, dKickS3, dKickS3, $3C, nRst, $0C, dKickS3, dSnareS3 dc.b $24, dKickS3, $0C, dSnareS3, $02, $16, dKickS3, $12, dKickS3, dKickS3, $0C smpsPan panLeft, $00 dc.b dElectricHighTom, $12, dElectricMidTom, dElectricMidTom, $0C, nRst smpsPan panCenter, $00 dc.b dElectricLowTom, $06 smpsPan panRight, $00 dc.b dElectricFloorTom, dElectricFloorTom, $24 smpsPan panCenter, $00 dc.b dKickS3, $0C, dSnareS3, $02, $16, dKickS3, $12, dKickS3, dKickS3, $24, dSnareS3, $18 dc.b dKickS3, $06, dSnareS3, $12, $18, dKickS3, $06, dSnareS3, $12, $06, dSnareS3, dSnareS3 dc.b dSnareS3, dCrashCymbal, $18, dSnareS3, dKickS3, dSnareS3 Snd_DDZ2_Loop00: dc.b dKickS3, $18, dSnareS3, dKickS3, dSnareS3 smpsLoop $00, $05, Snd_DDZ2_Loop00 dc.b dKickS3, $18, dSnareS3, dKickS3, dSnareS3, $0C, $06, dSnareS3, dKickS3, $12, $06, dCrashCymbal dc.b $18 smpsPan panLeft, $00 dc.b dElectricMidTom, $06, $0C, $06, dElectricLowTom, $0C smpsPan panRight, $00 dc.b dElectricFloorTom, $06, dElectricFloorTom smpsPan panCenter, $00 dc.b dCrashCymbal, $18, dSnareS3, dKickS3, dSnareS3, dKickS3, dSnareS3, dKickS3, dSnareS3, dKickS3, dSnareS3, dKickS3 dc.b dSnareS3, dKickS3, $06, dSnareS3, dKickS3, dKickS3, dCrashCymbal, nRst, nRst, dKickS3, dSnareS3, dSnareS3 dc.b dSnareS3, dSnareS3, dSnareS3, dSnareS3, dSnareS3, dSnareS3 smpsJump Snd_DDZ2_Jump00 Snd_DDZ2_Voices: ; Voice $00 ; $3A ; $3F, $7D, $73, $31, $9F, $5F, $54, $17, $0D, $14, $0A, $05 ; $01, $05, $01, $01, $FF, $9F, $8F, $FF, $29, $39, $23, $80 smpsVcAlgorithm $02 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $03, $07, $07, $03 smpsVcCoarseFreq $01, $03, $0D, $0F smpsVcRateScale $00, $01, $01, $02 smpsVcAttackRate $17, $14, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $05, $0A, $14, $0D smpsVcDecayRate2 $01, $01, $05, $01 smpsVcDecayLevel $0F, $08, $09, $0F smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $80, $23, $39, $29 ; Voice $01 ; $3C ; $01, $00, $00, $00, $1F, $1F, $15, $1F, $11, $0D, $12, $05 ; $07, $04, $09, $02, $55, $3A, $25, $1A, $1A, $80, $07, $80 smpsVcAlgorithm $04 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $00, $00, $00, $00 smpsVcCoarseFreq $00, $00, $00, $01 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $15, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $05, $12, $0D, $11 smpsVcDecayRate2 $02, $09, $04, $07 smpsVcDecayLevel $01, $02, $03, $05 smpsVcReleaseRate $0A, $05, $0A, $05 smpsVcTotalLevel $80, $07, $80, $1A ; Voice $02 ; $3E ; $07, $01, $02, $01, $1F, $1F, $1F, $1F, $0D, $06, $00, $00 ; $08, $06, $00, $00, $15, $0A, $0A, $0A, $1B, $80, $80, $80 smpsVcAlgorithm $06 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $00, $00, $00, $00 smpsVcCoarseFreq $01, $02, $01, $07 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $1F, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $00, $00, $06, $0D smpsVcDecayRate2 $00, $00, $06, $08 smpsVcDecayLevel $00, $00, $00, $01 smpsVcReleaseRate $0A, $0A, $0A, $05 smpsVcTotalLevel $80, $80, $80, $1B ; Voice $03 ; $16 ; $79, $71, $32, $33, $1F, $1F, $1F, $1F, $0A, $08, $0C, $0A ; $07, $0A, $07, $05, $2F, $AF, $AF, $5F, $24, $80, $82, $80 smpsVcAlgorithm $06 smpsVcFeedback $02 smpsVcUnusedBits $00 smpsVcDetune $03, $03, $07, $07 smpsVcCoarseFreq $03, $02, $01, $09 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $1F, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $0A, $0C, $08, $0A smpsVcDecayRate2 $05, $07, $0A, $07 smpsVcDecayLevel $05, $0A, $0A, $02 smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $80, $82, $80, $24 ; Voice $04 ; $45 ; $01, $06, $02, $01, $1F, $1F, $1F, $1F, $0D, $06, $00, $00 ; $08, $06, $00, $00, $15, $0A, $0A, $0A, $6B, $80, $80, $80 smpsVcAlgorithm $05 smpsVcFeedback $00 smpsVcUnusedBits $01 smpsVcDetune $00, $00, $00, $00 smpsVcCoarseFreq $01, $02, $06, $01 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $1F, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $00, $00, $06, $0D smpsVcDecayRate2 $00, $00, $06, $08 smpsVcDecayLevel $00, $00, $00, $01 smpsVcReleaseRate $0A, $0A, $0A, $05 smpsVcTotalLevel $80, $80, $80, $6B ; Unused voice ; Voice $05 ; $F5 ; $24, $30, $10, $32, $1F, $1F, $1F, $1F, $05, $18, $09, $02 ; $06, $0F, $06, $02, $1F, $2F, $4F, $2F, $0F, $0E, $0E, $80 smpsVcAlgorithm $05 smpsVcFeedback $06 smpsVcUnusedBits $03 smpsVcDetune $03, $01, $03, $02 smpsVcCoarseFreq $02, $00, $00, $04 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $1F, $1F, $1F, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $02, $09, $18, $05 smpsVcDecayRate2 $02, $06, $0F, $06 smpsVcDecayLevel $02, $04, $02, $01 smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $80, $0E, $0E, $0F ; Unused voice ; Voice $06 ; $3C ; $64, $64, $22, $24, $1F, $0C, $19, $0C, $05, $04, $05, $04 ; $05, $05, $05, $05, $4F, $4F, $4F, $4F, $20, $80, $2A, $80 smpsVcAlgorithm $04 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $02, $02, $06, $06 smpsVcCoarseFreq $04, $02, $04, $04 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $0C, $19, $0C, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $04, $05, $04, $05 smpsVcDecayRate2 $05, $05, $05, $05 smpsVcDecayLevel $04, $04, $04, $04 smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $80, $2A, $80, $20 ; Unused voice ; Voice $07 ; $3D ; $01, $02, $02, $02, $1F, $08, $8A, $0A, $08, $08, $08, $08 ; $00, $01, $00, $00, $0F, $1F, $1F, $1F, $1F, $88, $88, $87 smpsVcAlgorithm $05 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $00, $00, $00, $00 smpsVcCoarseFreq $02, $02, $02, $01 smpsVcRateScale $00, $02, $00, $00 smpsVcAttackRate $0A, $0A, $08, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $08, $08, $08, $08 smpsVcDecayRate2 $00, $00, $01, $00 smpsVcDecayLevel $01, $01, $01, $00 smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $87, $88, $88, $1F
module Rel8.Query.Null ( catNull ) where -- base import Prelude -- rel8 import Rel8.Expr ( Expr ) import Rel8.Expr.Null ( isNonNull, unsafeUnnullify ) import Rel8.Query ( Query ) import Rel8.Query.Filter ( where_ ) -- | Filter a 'Query' that might return @null@ to a 'Query' without any -- @null@s. -- -- Corresponds to 'Data.Maybe.catMaybes'. catNull :: Expr (Maybe a) -> Query (Expr a) catNull a = do where_ $ isNonNull a pure $ unsafeUnnullify a
#include "sketch/mod.h" #include <iostream> using namespace sketch; int main() { modsketch_t<hash::WangHash, uint64_t, policy::SizeDivPolicy<uint64_t>, std::allocator<uint64_t> > mod(16); std::cerr << "div: " << mod.mod_.nelem() << '\n'; assert(mod.add(1 << 16)); assert(mod.finalize().size() == 1); std::mt19937_64 mt; for(size_t i = 0; i < 10000; ++i) { mod.addh(mt()); } auto f = mod.finalize(); std::cerr << "Now, out of 10001 items, f has size " << f.size() << '\n'; auto modfocus = mod.reduce(2); std::cerr << "Now, out of 10001 items, f (reduced by 2) has size " << modfocus.finalize().size() << '\n'; }
class Order < ApplicationRecord belongs_to :food, optional: true belongs_to :user def self.unique_id (Faker::Number.number(4) + Time.now.utc.to_i.to_s) end end
package org.miage.Entity; import java.util.HashSet; import java.util.Set; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; @Entity @Table( name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = "email") }) public class User { @NotBlank @Size(max = 20) private String username; private boolean admin; @NotBlank @Size(max = 20) private String userlastname; @Id @Size(max = 50) @Email private String email; @NotBlank @Size(max = 120) private String password; @OneToMany private Set<coursAssign> idCours= new HashSet<coursAssign>(); public User() { } public User(String username,String userlastname, String email, String password, boolean admin) { this.username = username; this.userlastname = userlastname; this.email = email; this.password = password; this.admin = admin; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isAdmin() { return admin; } public void setAdmin(boolean admin) { this.admin = admin; } public String getUserlastname() { return userlastname; } public void setUserlastname(String userlastname) { this.userlastname = userlastname; } public Set<coursAssign> getIdCours() { return idCours; } public void setIdCours(Set<coursAssign> idCours) { this.idCours = idCours; } }
using FluentValidation; using Paxstore.OpenApi.Model; namespace Paxstore.OpenApi.Validator.MerchantCategory { public class MerchantCategoryCreateValidator: AbstractValidator<MerchantCategoryCreateRequest> { public MerchantCategoryCreateValidator(){ RuleFor(x => x.Name).NotEmpty().MaximumLength(128); RuleFor(x => x.Remarks).MaximumLength(255); } } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttendanceImportsTable extends Migration { /** * Run the migrations. * * @return void */ /* Date Employee Code Employee Name Company Department Category Degination Shift Early By Status Punch Records Overtime */ public function up() { Schema::create('attendance_imports', function (Blueprint $table) { $table->id(); $table->string("Date"); $table->string("EmployeeCode"); $table->string("EmployeeName"); $table->string("Company"); $table->string("Department"); $table->string("Category"); $table->string("Designation"); $table->string("Shift"); $table->string("EarlyBy"); $table->string("Status"); $table->string("PunchRecords"); $table->string("Overtime"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('attendance_imports'); } }
#include <boost/asio.hpp> #include <functional> #include <libdialler/listener.h> #include <libdialler/listener_client.h> #include <string> using namespace boost::asio; using namespace boost::asio::ip; using namespace dialler; listener_client::listener_client(uint64_t id_, async_io_ptr async_io, listener *s) : id(id_) , _listener(s) { _async_connection = async_io; } listener_client::~listener_client() { _async_connection = nullptr; } void listener_client::start() { initialisation_begin(); auto self = shared_from_this(); async_io::data_handler_t on_d = [self](std::vector<message_ptr> &d, bool &cancel) { self->on_data_recv(d, cancel); }; async_io::error_handler_t on_n = [self](auto err) { self->on_network_error(err); self->close(); }; _async_connection->start(on_d, on_n); initialisation_complete(); } void listener_client::close() { if (!is_stopping_started() && !is_stoped()) { stopping_started(true); if (_async_connection != nullptr) { _async_connection->full_stop(); _async_connection = nullptr; this->_listener->erase_client_description(this->shared_from_this()); } } } void listener_client::on_network_error(const boost::system::error_code &err) { this->_listener->on_network_error(this->shared_from_this(), err); } void listener_client::on_data_recv(std::vector<message_ptr> &d, bool &cancel) { _listener->on_new_message(this->shared_from_this(), d, cancel); } void listener_client::send_data(const message_ptr &d) { _async_connection->send(d); } void listener_client::send_data(const std::vector<message_ptr> &d) { _async_connection->send(d); }
// Package ntp provides ntp synchronized time package ntp import ( "context" gotime "time" "github.com/beevik/ntp" "github.com/TarsCloud/TarsGo/tars/sync/time" ) type ntpTime struct { server string } type ntpServerKey struct{} func (n *ntpTime) Now() (gotime.Time, error) { return ntp.Time(n.server) } // NewTime returns ntp time func NewTime(opts ...time.Option) time.Time { options := time.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } server := "time.google.com" if k, ok := options.Context.Value(ntpServerKey{}).(string); ok { server = k } return &ntpTime{ server: server, } } // WithServer sets the ntp server func WithServer(s string) time.Option { return func(o *time.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, ntpServerKey{}, s) } }
using TMPro; using UnityEngine; using UnityEngine.UI; namespace Knockback.Structs { }
package com.badoo.reaktive.coroutinesinterop import com.badoo.reaktive.test.base.assertError import com.badoo.reaktive.test.completable.assertComplete import com.badoo.reaktive.test.completable.test import kotlin.test.Test class CompletableFromCoroutineTest { @Test fun completes_WHEN_coroutine_finished() { val observer = completableFromCoroutine {}.test() observer.assertComplete() } @Test fun produces_error_WHEN_coroutine_thrown_exception() { val error = Exception() val observer = completableFromCoroutine { throw error }.test() observer.assertError(error) } }
/* * Licensed Materials - Property of IBM * * trousers - An open source TCG Software Stack * * (C) Copyright International Business Machines Corp. 2004, 2005 * */ #ifndef _TDDL_H_ #define _TDDL_H_ #include <threads.h> #include "tcsd_wrap.h" #include "tcsd.h" struct tpm_device_node { char *path; #define TDDL_TRANSMIT_IOCTL 1 #define TDDL_TRANSMIT_RW 2 int transmit; int fd; }; #define TDDL_TXBUF_SIZE 2048 #define TDDL_UNDEF -1 TSS_RESULT Tddli_Open(void); TSS_RESULT Tddli_TransmitData(BYTE *pTransmitBuf, UINT32 TransmitBufLen, BYTE *pReceiveBuf, UINT32 *pReceiveBufLen); TSS_RESULT Tddli_Close(void); #endif
#!/bin/sh # Copyright (C) 2008 Red Hat, Inc. All rights reserved. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA . ./test-utils.sh aux prepare_pvs 4 # vgcfgbackup handles similar VG names (bz458941) vg1=${PREFIX}vg00 vg2=${PREFIX}vg01 vgcreate $vg1 $dev1 vgcreate $vg2 $dev2 vgcfgbackup -f /tmp/bak-%s >out grep "Volume group \"$vg1\" successfully backed up." out grep "Volume group \"$vg2\" successfully backed up." out vgremove -ff $vg1 vgremove -ff $vg2 # vgcfgbackup correctly stores metadata with missing PVs # and vgcfgrestore able to restore them when device reappears pv1_uuid=$(pvs --noheadings -o pv_uuid $dev1) pv2_uuid=$(pvs --noheadings -o pv_uuid $dev2) vgcreate $vg $devs lvcreate -l1 -n $lv1 $vg $dev1 lvcreate -l1 -n $lv2 $vg $dev2 lvcreate -l1 -n $lv3 $vg $dev3 vgchange -a n $vg pvcreate -ff -y $dev1 pvcreate -ff -y $dev2 vgcfgbackup -f "$(pwd)/backup.$$" $vg sed 's/flags = \[\"MISSING\"\]/flags = \[\]/' "$(pwd)/backup.$$" > "$(pwd)/backup.$$1" pvcreate -ff -y -u $pv1_uuid $dev1 pvcreate -ff -y -u $pv2_uuid $dev2 vgcfgrestore -f "$(pwd)/backup.$$1" $vg
require "bloc_works/version" require "bloc_works/controller" require "bloc_works/dependencies" require "bloc_works/router" require "bloc_works/utility" module BlocWorks class Application def call(env) # [status code, {header}, [body]] # if the request is for a favicon # return the 404 format (see fav_icon) # otherwise # assume /controller/action and use controller_and_action to parse PATH_INFO # then, execute the action and return the result if env['PATH_INFO'] == '/favicon.ico' return [404, {'Content-Type' => 'text/html'}, []] else my_action = controller_and_action(env) unless my_action[0].nil? controller = my_action[0].new(env) puts "controller is '#{controller}' and action is #{my_action[1]}" puts "does controller respond to action? #{controller.respond_to?(my_action[1])}" if controller && controller.respond_to?(my_action[1]) body = controller.send(my_action[1]) return [200, {'Content-Type' => 'text/html'}, [body]] end end end return [404, {'Content-Type' => 'text/html'}, ["Check your controller and action in the URL"]] end end end
package sake.command.builtin import org.specs._ import scala.util.matching.Regex import sake.util._ import sake.environment._ import java.io.{PrintStream, ByteArrayOutputStream} object JVMCommandSpec extends Specification { val savedDryRun = Environment.environment.dryRun val savedLog = Log.log var byteStream = new ByteArrayOutputStream() var newStream = new PrintStream(byteStream) val delim = Environment.environment.pathSeparator def checkString(regex: Regex, actual: String) = { (regex findFirstIn actual) match { case Some(s) => case None => fail("expected (regex): "+regex+", actual: "+actual) } } doBeforeSpec { Environment.environment.dryRun = true Log.log = new Log(Level.Info, newStream) } doAfterSpec { Environment.environment.dryRun = savedDryRun Log.log = savedLog } "Running a JVMCommand with standard options" should { doBefore { byteStream = new ByteArrayOutputStream() newStream = new PrintStream(byteStream) Log.log.out = newStream } "maps 'classpath -> List(a,b,c) to -classpath a:b:c'" in { val cmd = new JVMCommand("java", Map('classpath -> List("bar1", "bar2", "bar3"))) cmd() byteStream.toString() must be matching("""java\s+-classpath bar1[:;]bar2[:;]bar3[:;].*""") } "maps 'cp -> List(a,b,c) to -classpath a:b:c'" in { val cmd = new JVMCommand("java", Map('classpath -> List("bar1", "bar2", "bar3"))) cmd() byteStream.toString() must be matching("""java\s+-classpath bar1[:;]bar2[:;]bar3[:;].*""") } "maps 'class -> name to 'name'" in { val cmd = new JVMCommand("java", Map('class -> "foo.bar.Bar")) cmd() byteStream.toString() must be matching("""java\s+foo.bar.Bar""") } } }
# Quickstart Here is a template that will help you quickstart your project: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello, world!</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/samsunginternet/OneUI-Web/oui-css/oui.css"> </head> <body> <main class="container"> <div class="oui-viewing"> <!-- Viewing area --> </div> <div class="oui-interaction"> <!-- Interaction area --> </div> </main> </body> </html> ``` ## From the Source ### 1st step - Download the release from OneUI Web REPO This is the easiest step. Here is is the link from where the releases are available: https://github.com/SamsungInternet/OneUI-Web/releases/latest Download it and place it in your projects folder ### 2nd step - Include it Include it on your page by adding the css stylesheet to your page: ``` <link rel="stylesheet" href="OneUI/oui.css"> ``` Here is what your page should look like. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello, world!</title> <link rel="stylesheet" href="OneUI/oui.css"> </head> <body> <main class="container"> <div class="oui-viewing"> <!-- Viewing area --> </div> <div class="oui-interaction"> <!-- Interaction area --> </div> </main> </body> </html> ``` ## Enjoy Now that One UI is added to your project you can have fun with it. Don't miss the rest of the documentation, here are three components to get you started: - [Bubble](components/bubble) - [Tab / Item](components/tab) - [All kinds of inputs](components/inputs)
package sqs import ( "fmt" "github.com/pjmyburg/virago/config" ) // SQS represents an instance of the SQS mock type SQS struct { queues map[string]queue } type queue struct { url string in chan message inFlight chan message } type message struct { body string } // New creates a new SQS instance and creates queues using the supplied config on startup func New(conf *config.Config) *SQS { queues := make(map[string]queue) for _, confQ := range conf.Queues { queues[confQ.Name] = queue{ url: fmt.Sprintf("https://%s.queue.amazonaws.com/%s/%s", config.Region, config.AccountID, confQ.Name), in: nil, inFlight: nil, } } return &SQS{ queues: queues, } }
const getScriptReadyState = () => { return 'return document.readyState' } const getScriptClickCheckbox = (el) => { return `document.getElementById('${el}').click(); return;` } const getScriptSelectDifficulty = (difficulty) => { return ` let diffList = document.getElementById('difSelect').options; for (let item of diffList) { if (item.innerHTML.toLowerCase().includes('${difficulty}')) { document.getElementById('difSelect').value = item.value } } return; ` } const getScriptScrollCenter = () => { return "arguments[0].scrollIntoView({block: 'center'})" } const getScriptScrollStart = () => { return "arguments[0].scrollIntoView({block: 'start'})" } module.exports = { getScriptReadyState, getScriptClickCheckbox, getScriptSelectDifficulty, getScriptScrollCenter, getScriptScrollStart };
//! Response codes use super::{Error, ErrorKind}; use crate::command; use anomaly::{fail, format_err}; use serde::{de, ser, Deserialize, Serialize}; /// Codes associated with HSM responses #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Code { /// Successful response for the given command type Success(command::Code), /// HSM memory error (or generic error) MemoryError, /// Initialization error InitError, /// Network error ConnectionError, /// Couldn't find connector ConnectorNotFound, /// Invalid parameters InvalidParameters, /// Wrong length WrongLength, /// Buffer is too small BufferTooSmall, /// Cryptogram mismatches CryptogramMismatch, /// Session auth error SessionAuthenticationFailed, /// MAC mismatch MacMismatch, /// OK (HSM) DeviceOK, /// Invalid command (HSM) DeviceInvalidCommand, /// Invalid data (HSM) DeviceInvalidData, /// Invalid session (HSM) DeviceInvalidSession, /// Authentication failure (HSM) DeviceAuthenticationFailed, /// Sessions full (HSM) DeviceSessionsFull, /// Session failed (HSM) DeviceSessionFailed, /// Storage failed (HSM) DeviceStorageFailed, /// Wrong length (HSM) DeviceWrongLength, /// Invalid permissions (HSM) DeviceInsufficientPermissions, /// Audit log full (HSM) DeviceLogFull, /// Object not found (HSM) DeviceObjectNotFound, /// Invalid ID (HSM) DeviceInvalidId, /// Invalid OTP (HSM) DeviceInvalidOtp, /// Demo mode (HSM) DeviceDemoMode, /// Command unexecuted DeviceCommandUnexecuted, /// Generic error GenericError, /// Object already exists DeviceObjectExists, /// Connector error ConnectorError, /// Constraint on CA violated DeviceSshCaConstraintViolation, } impl Code { /// Convert an unsigned byte into a Code (if valid) pub fn from_u8(byte: u8) -> Result<Self, Error> { let code = i16::from(byte).checked_sub(0x80).unwrap() as i8; Ok(match code { 0..=0x7F => Code::Success( command::Code::from_u8(code as u8) .map_err(|e| format_err!(ErrorKind::CodeInvalid, "{}", e.kind()))?, ), -1 => Code::MemoryError, -2 => Code::InitError, -3 => Code::ConnectionError, -4 => Code::ConnectorNotFound, -5 => Code::InvalidParameters, -6 => Code::WrongLength, -7 => Code::BufferTooSmall, -8 => Code::CryptogramMismatch, -9 => Code::SessionAuthenticationFailed, -10 => Code::MacMismatch, -11 => Code::DeviceOK, -12 => Code::DeviceInvalidCommand, -13 => Code::DeviceInvalidData, -14 => Code::DeviceInvalidSession, -15 => Code::DeviceAuthenticationFailed, -16 => Code::DeviceSessionsFull, -17 => Code::DeviceSessionFailed, -18 => Code::DeviceStorageFailed, -19 => Code::DeviceWrongLength, -20 => Code::DeviceInsufficientPermissions, -21 => Code::DeviceLogFull, -22 => Code::DeviceObjectNotFound, -23 => Code::DeviceInvalidId, -24 => Code::DeviceInvalidOtp, -25 => Code::DeviceDemoMode, -26 => Code::DeviceCommandUnexecuted, -27 => Code::GenericError, -28 => Code::DeviceObjectExists, -29 => Code::ConnectorError, -30 => Code::DeviceSshCaConstraintViolation, _ => fail!(ErrorKind::CodeInvalid, "invalid response code: {}", code), }) } /// Convert a Code back into its original byte form pub fn to_u8(self) -> u8 { let code: i8 = match self { Code::Success(cmd_type) => cmd_type as i8, Code::MemoryError => -1, Code::InitError => -2, Code::ConnectionError => -3, Code::ConnectorNotFound => -4, Code::InvalidParameters => -5, Code::WrongLength => -6, Code::BufferTooSmall => -7, Code::CryptogramMismatch => -8, Code::SessionAuthenticationFailed => -9, Code::MacMismatch => -10, Code::DeviceOK => -11, Code::DeviceInvalidCommand => -12, Code::DeviceInvalidData => -13, Code::DeviceInvalidSession => -14, Code::DeviceAuthenticationFailed => -15, Code::DeviceSessionsFull => -16, Code::DeviceSessionFailed => -17, Code::DeviceStorageFailed => -18, Code::DeviceWrongLength => -19, Code::DeviceInsufficientPermissions => -20, Code::DeviceLogFull => -21, Code::DeviceObjectNotFound => -22, Code::DeviceInvalidId => -23, Code::DeviceInvalidOtp => -24, Code::DeviceDemoMode => -25, Code::DeviceCommandUnexecuted => -26, Code::GenericError => -27, Code::DeviceObjectExists => -28, Code::ConnectorError => -29, Code::DeviceSshCaConstraintViolation => -30, }; (i16::from(code) + 0x80) as u8 } /// Is this a successful response? pub fn is_success(self) -> bool { match self { Code::Success(_) => true, _ => false, } } /// Is this an error response? pub fn is_err(self) -> bool { !self.is_success() } } impl Serialize for Code { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { serializer.serialize_u8(self.to_u8()) } } impl<'de> Deserialize<'de> for Code { fn deserialize<D>(deserializer: D) -> Result<Code, D::Error> where D: de::Deserializer<'de>, { let value = u8::deserialize(deserializer)?; use de::Error; Code::from_u8(value) .or_else(|_| Code::from_u8(Code::DeviceOK.to_u8() - value)) .map_err(D::Error::custom) } }
require "rspec/expectations" RSpec::Matchers.define :be_a_file do match do |path| File.exists?(path) end end RSpec::Matchers.define :be_a_directory do match do |path| Dir.exists?(path) end end RSpec::Matchers.define :be_a_symlink do match do |path| File.symlink?(File.expand_path(path)) end end RSpec::Matchers.define :be_a_symlink_of do |expected| match do |path| File.symlink?(File.expand_path(path)) && File.realpath(path).eql?(expected) end end RSpec::Matchers.define :exist do |expected| match do |path| File.exists?(File.expand_path(path)) end end
course_review_page = Proc.new do menu parent: "Models" permit_params :overall_rating, :challenge_rating, :inclusivity_rating, :comments, :course_id, :work_per_week end ActiveAdmin.register CourseReview, :namespace => :admin, &course_review_page
class CommentsController < ApplicationController def create recipe = Recipe.find(params[:recipe_id]) if current_user != nil @comment = recipe.comments.create(comment: params[:comment]) respond_to do |format| format.json { render json: @comment } end else redirect_to recipe, flash: { alert: "login to leave your review!" } end end def destroy Comment.find(params[:id]).destroy end def render_comment(comment) ApplicationController.render( partial: 'comments/comment', locals: { comment: comment } ) end end
// ----------------------------------------------------------------------- // <copyright file="ISenderContext.cs" company="Asynkron HB"> // Copyright (C) 2015-2018 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; namespace Proto { public interface ISenderContext : IInfoContext { /// <summary> /// MessageHeaders of the Context /// </summary> MessageHeader Headers { get; } //TODO: should the current message of the actor be exposed to sender middleware? object? Message { get; } /// <summary> /// Send a message to a given PID target /// </summary> /// <param name="target">The target PID</param> /// <param name="message">The message to send</param> void Send(PID target, object message); /// <summary> /// Sends a message together with a Sender PID, this allows the target to respond async to the Sender /// </summary> /// <param name="target">The target PID</param> /// <param name="message">The message to send</param> void Request(PID target, object message); /// <summary> /// Sends a message together with a Sender PID, this allows the target to respond async to the Sender /// </summary> /// <param name="target">The target PID</param> /// <param name="message">The message to send</param> /// <param name="sender">Message sender</param> void Request(PID target, object message, PID? sender); /// <summary> /// Sends a message together with a Sender PID, this allows the target to respond async to the Sender. /// This operation can be awaited. /// </summary> /// <param name="target">The target PID</param> /// <param name="message">The message to send</param> /// <param name="timeout">Timeout for the request</param> /// <typeparam name="T">Expected return message type</typeparam> /// <returns>A Task that completes once the Target Responds back to the Sender</returns> Task<T> RequestAsync<T>(PID target, object message, TimeSpan timeout); /// <summary> /// Sends a message together with a Sender PID, this allows the target to respond async to the Sender. /// This operation can be awaited. /// </summary> /// <param name="target">The target PID</param> /// <param name="message">The message to send</param> /// <param name="cancellationToken">Cancellation token for the request</param> /// <typeparam name="T">Expected return message type</typeparam> /// <returns>A Task that completes once the Target Responds back to the Sender</returns> Task<T> RequestAsync<T>(PID target, object message, CancellationToken cancellationToken); /// <summary> /// Sends a message together with a Sender PID, this allows the target to respond async to the Sender. /// This operation can be awaited. /// </summary> /// <param name="target">The target PID</param> /// <param name="message">The message to send</param> /// <typeparam name="T">Expected return message type</typeparam> /// <returns>A Task that completes once the Target Responds back to the Sender</returns> Task<T> RequestAsync<T>(PID target, object message); } }
export { middlewareBuilder } from './middleware'; export { simplifyBuilder } from './builder'; export { httpMethod, ReduxServerAction } from './types';
#ifndef SIMPLE_SOURCE_INCLUDE_SIMPLE_SOURCE_H #define SIMPLE_SOURCE_INCLUDE_SIMPLE_SOURCE_H #include <cstdint> int MyHeaderFunction(); inline int MyHeaderFunction() { return 5; } std::uint8_t Function(); int Foo(); inline int Foo() { std::uint8_t const a = 0U; return a; } #endif // SIMPLE_SOURCE_INCLUDE_SIMPLE_SOURCE_H
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Dapper.SimpleSave.Impl { public static class MemberInfoExtensions { public static IDictionary<Type, Attribute> GetAttributesDict(this MemberInfo member) { var target = new Dictionary<Type, Attribute>(); foreach (var attr in member.GetCustomAttributes(true).OfType<Attribute>()) { target[attr.GetType()] = attr; } return target; } } }
import React from 'react'; import { Map } from 'reaviz'; import { feature } from 'topojson-client'; import geojson from 'world-atlas/countries-110m.json'; const worldData = feature(geojson, geojson.objects.countries); export default () => ( <div style={{ margin: '55px', textAlign: 'center' }}> <Map data={worldData} height={350} width={500} markers={[ <MapMarker coordinates={[-122.490402, 37.786453]} />, <MapMarker coordinates={[-58.3816, -34.6037]} />, <MapMarker coordinates={[-97.7437, 30.2711]} tooltip="Austin, TX" /> ]} /> </div> );
# frozen_string_literal: true require 'rails_helper' RSpec.describe NintendoPricesClient, type: :clients do describe 'Configurations' do it 'has default base_uri' do expect(described_class.base_uri).to eq 'https://ec.nintendo.com/api' end end describe '#fetch' do subject(:result) { described_class.new.fetch(country: country, lang: lang, nsuids: nsuids) } let(:country) { 'XX' } let(:lang) { 'YY' } let(:nsuids) { %w[123 456 789] } let(:querystring) { 'ns_uids=123&ns_uids=456&ns_uids=789' } let(:response) { Faker::Types.rb_hash(number: 4).stringify_keys } before do stub_request(:get, "#{described_class.base_uri}/#{country}/#{lang}/guest_prices?#{querystring}") .to_return(body: response.to_json, headers: { 'Content-Type' => 'application/json' }) end it 'requests given nsuids prices from nintendo servers' do expect(result).to eq response end context 'when given nsuids count is greater than 99' do let(:nsuids) { (1..100).to_a } it 'raises error' do expect { result }.to raise_error('NSUIDS are limited to 99 per request') end end end end
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::transaction::Script; use std::fmt; #[test] fn test_code_fmt() { let expect_output = r#"Script { code: "6d6f7665", args: [], }"#; let script = Script::new(b"move".to_vec(), vec![], vec![]); let mut output = String::new(); fmt::write(&mut output, format_args!("{:#?}", script)) .expect("Error occurred while trying to format Script."); assert_eq!(output, expect_output); println!("{:#?}", script); }
import pytest import gen.internals from gen.exceptions import ValidationError from gen.internals import Scope, Source, Target def sample_fn_small(): pass def sample_fn_normal(foo): pass def sample_fn_big(foo, bar, baz, ping=None, pong="magic"): pass def test_get_function_parameters(): get_function_parameters = gen.internals.get_function_parameters assert get_function_parameters(sample_fn_small) == set() assert get_function_parameters(sample_fn_normal) == {'foo'} assert get_function_parameters(sample_fn_big) == {'foo', 'bar', 'baz', 'ping', 'pong'} assert get_function_parameters(lambda x: x) == {'x'} assert get_function_parameters(lambda x, y, a, b: sample_fn_normal(x)) == {'x', 'y', 'a', 'b'} def test_validate_arguments_strings(): validate_arguments_strings = gen.internals.validate_arguments_strings validate_arguments_strings(dict()) validate_arguments_strings({'a': 'b'}) validate_arguments_strings({'a': 'b', 'c': 'd', 'e': 'f'}) # TODO(cmaloney): Validate the error message contains all error keys. with pytest.raises(ValidationError): validate_arguments_strings({'a': {'b': 'c'}}) with pytest.raises(ValidationError): validate_arguments_strings({'a': 1}) with pytest.raises(ValidationError): validate_arguments_strings({1: 'a'}) with pytest.raises(ValidationError): validate_arguments_strings({'a': 'b', 'c': 1}) with pytest.raises(ValidationError): validate_arguments_strings({'a': None}) def validate_a(a): assert a == 'a_str' def test_resolve_simple(): test_source = Source({ 'validate': [validate_a], 'default': { 'a': 'a_str', 'd': 'd_1', }, 'must': { 'b': 'b_str' }, 'conditional': { 'd': { 'd_1': { 'must': { 'd_1_b': 'd_1_b_str' } }, 'd_2': { 'must': { 'd_2_b': 'd_2_b_str' } } } } }) test_target = Target( {'a', 'b', 'c'}, {'d': Scope( 'd', { 'd_1': Target({'d_1_a', 'd_1_b'}), 'd_2': Target({'d_2_a', 'd_2_b'}) })}) resolver = gen.internals.resolve_configuration([test_source], [test_target], {'c': 'c_str', 'd_1_a': 'd_1_a_str'}) print(resolver) assert resolver.status_dict == {'status': 'ok'}
import PanelSlider from '../../src/index' const slider = PanelSlider({ element: document.querySelector('.panel-set') as HTMLElement, numPanels: 3 }) // Display live results from callbacks function $e (id: string) { return document.getElementById(id) as HTMLElement } const elId = $e('panelId') const elPos = $e('panelPos') slider.on('panelchange', panelId => { elId.textContent = String(panelId) }) slider.on('animate', panelPos => { elPos.textContent = panelPos.toFixed(2) })
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.parse_thicket.matching; import java.util.ArrayList; import java.util.List; import opennlp.tools.parse_thicket.IGeneralizer; public class PartOfSpeechGeneralizer implements IGeneralizer<String>{ @Override public List<String> generalize(Object o1, Object o2){ String pos1 = (String)o1, pos2 = (String) o2; List<String> results = new ArrayList<String>(); String res = computeSimilarity(pos1, pos2); if (res!=null) results.add(res); return results; } private String computeSimilarity(String pos1, String pos2){ if ((pos1.startsWith("NN") && pos2.equals("NP") || pos2.startsWith("NN") && pos1.equals("NP"))) { return "NN"; } if ((pos1.startsWith("NN") && pos2.equals("VBG") || pos2.startsWith("VBG") && pos1.equals("NN"))) { return "NN"; } if ((pos1.startsWith("NN") && pos2.equals("ADJP") || pos2.startsWith("NN") && pos1.equals("ADJP"))) { return "NN"; } if ((pos1.equals("IN") && pos2.equals("TO") || pos1.equals("TO") && pos2.equals("IN"))) { return "IN"; } // VBx vs VBx = VB (does not matter which form for verb) if (pos1.startsWith("VB") && pos2.startsWith("VB")) { return "VB"; } // ABx vs ABy always gives AB if (pos1.equalsIgnoreCase(pos2)) { return pos1; } if (pos1.length() > 2) { pos1 = pos1.substring(0, 2); } if (pos2.length() > 2) { pos2 = pos2.substring(0, 2); } if (pos1.equalsIgnoreCase(pos2)) { return pos1 + "*"; } return null; } }
from unittest import TestCase import os import consul import uuid import time from consul_lock import defaults from consul_lock import EphemeralLock def get_consul_client(): host = os.environ.get('CONSUL_LOCK_CONSUL_HOST') port = os.environ.get('CONSUL_LOCK_CONSUL_PORT') assert host, 'CONSUL_LOCK_CONSUL_HOST environment variable is required for integration testing' assert port, 'CONSUL_LOCK_CONSUL_PORT environment variable is required for integration testing' client = consul.Consul(host=host, port=int(port)) return client def generate_key(key): # always prefix key with uuid so tests can always be re-run immediately without # clashing on stale locks from a previous run (which will eventually timeout) return '%s/%s' % (uuid.uuid4(), key) class IntegrationTests(TestCase): """ These test require connecting to an actual Consul cluster and will write actual data to the key/value store, run carefully. """ @classmethod def setUpClass(cls): super(IntegrationTests, cls).setUpClass() cls.consul_client = get_consul_client() defaults.consul_client = cls.consul_client print cls.consul_client def setUp(self): super(IntegrationTests, self).setUp() defaults.lock_key_pattern = 'consul_lock/test/%s' def test_unable_to_acquire_held_lock(self): key1 = generate_key('key1') lock1_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) lock2_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) lock1_on_key1.acquire() was_acquired = lock2_on_key1.acquire(fail_hard=False) self.assertFalse(was_acquired) lock1_on_key1.release() lock3_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) was_acquired = lock3_on_key1.acquire(fail_hard=False) self.assertTrue(was_acquired) def test_unrelated_locks_can_be_acquired_concurrently(self): key1 = generate_key('key1') lock1_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) key2 = generate_key('key2') lock2_on_key2 = EphemeralLock(key2, acquire_timeout_ms=0, lock_timeout_seconds=10) lock1_on_key1.acquire() lock2_on_key2.acquire() def test_able_to_acquire_after_timeout_lock(self): key1 = generate_key('key1') lock1_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) lock1_on_key1.acquire() time.sleep(20) lock2_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) was_acquired = lock2_on_key1.acquire(fail_hard=False) self.assertTrue(was_acquired) def test_acquire_timeout_will_wait_and_acquire(self): key1 = generate_key('key1') lock1_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) lock1_on_key1.acquire() lock2_on_key1 = EphemeralLock(key1, acquire_timeout_ms=20 * 1000, lock_timeout_seconds=10) was_acquired = lock2_on_key1.acquire(fail_hard=False) self.assertTrue(was_acquired) def test_acquire_timeout_blocks_for_reasonable_time(self): key1 = generate_key('key1') lock1_on_key1 = EphemeralLock(key1, acquire_timeout_ms=0, lock_timeout_seconds=10) lock1_on_key1.acquire() lock2_on_key1 = EphemeralLock(key1, acquire_timeout_ms=500, lock_timeout_seconds=10) start_time = time.time() was_acquired = lock2_on_key1.acquire(fail_hard=False) elapsed_time_ms = int(round(1000 * (time.time() - start_time))) self.assertFalse(was_acquired) self.assertGreater(elapsed_time_ms, 500) self.assertLess(elapsed_time_ms, 600)
program Calc32; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} uses {$IFnDEF FPC} {$ELSE} Interfaces, {$ENDIF} Forms, SysUtils, Frm_CALC in '..\source\CALC32\Frm_CALC.PAS' {CalcForm}, Frm_CalcABOUT in '..\source\CALC32\Frm_CalcABOUT.PAS' {AboutForm}; {$IFNDEF FPC} {$E EXE} {$ENDIF} {$R *.res} function AppVendorName: String; begin Result := 'JC-Soft' end; function AppApplicationName: String; begin Result := 'Calc32'; end; begin Application.Scaled:=True; Application.Initialize; Application.Title := 'Demo: Calc32'; OnGetVendorName:=AppVendorName; OnGetApplicationName:=AppApplicationName; Application.CreateForm(TfrmCalcMain, frmCalcMain); Application.CreateForm(TfrmCalcAbout, frmCalcAbout); Application.Run; end.
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const util_base64_node_1 = require("@aws-sdk/util-base64-node"); const util_hex_encoding_1 = require("@aws-sdk/util-hex-encoding"); const _1 = require("./"); const hashVectors = require("hash-test-vectors"); describe("Md5", () => { let idx = 0; for (const { input, ...results } of hashVectors) { const expected = results["md5"]; it(`should calculate a MD5 hash of ${expected} for test vector ${++idx}`, async () => { const hash = new _1.Md5(); hash.update(util_base64_node_1.fromBase64(input)); expect(util_hex_encoding_1.toHex(await hash.digest())).toBe(expected); }); } });
import 'dart:ui'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/foundation.dart'; import 'package:intl/intl.dart'; import 'package:flutter_keep_notes/services.dart' show NoteQuery; /// Data model of a note. class Note extends ChangeNotifier { final String id; String title; String content; Color color; NoteState state; final DateTime createdAt; DateTime modifiedAt; /// Instantiates a [Note]. Note({ this.id, this.title, this.content, this.color, this.state, DateTime createdAt, DateTime modifiedAt, }) : this.createdAt = createdAt ?? DateTime.now(), this.modifiedAt = modifiedAt ?? DateTime.now(); /// Transforms the Firestore query [snapshot] into a list of [Note] instances. static List<Note> fromQuery(QuerySnapshot snapshot) => snapshot != null ? snapshot.toNotes() : []; /// Whether this note is pinned bool get pinned => state == NoteState.pinned; /// Returns an numeric form of the state int get stateValue => (state ?? NoteState.unspecified).index; bool get isNotEmpty => title?.isNotEmpty == true || content?.isNotEmpty == true; /// Formatted last modified time String get strLastModified => DateFormat.MMMd().format(modifiedAt); /// Update this note with another one. /// /// If [updateTimestamp] is `true`, which is the default, /// `modifiedAt` will be updated to `DateTime.now()`, otherwise, the value of `modifiedAt` /// will also be copied from [other]. void update(Note other, {bool updateTimestamp = true}) { title = other.title; content = other.content; color = other.color; state = other.state; if (updateTimestamp || other.modifiedAt == null) { modifiedAt = DateTime.now(); } else { modifiedAt = other.modifiedAt; } notifyListeners(); } /// Update this note with specified properties. /// /// If [updateTimestamp] is `true`, which is the default, /// `modifiedAt` will be updated to `DateTime.now()`. Note updateWith({ String title, String content, Color color, NoteState state, bool updateTimestamp = true, }) { if (title != null) this.title = title; if (content != null) this.content = content; if (color != null) this.color = color; if (state != null) this.state = state; if (updateTimestamp) modifiedAt = DateTime.now(); notifyListeners(); return this; } /// Serializes this note into a JSON object. Map<String, dynamic> toJson() => { 'title': title, 'content': content, 'color': color?.value, 'state': stateValue, 'createdAt': (createdAt ?? DateTime.now()).millisecondsSinceEpoch, 'modifiedAt': (modifiedAt ?? DateTime.now()).millisecondsSinceEpoch, }; /// Make a copy of this note. /// /// If [updateTimestamp] is `true`, the defaults is `false`, /// timestamps both of `createdAt` & `modifiedAt` will be updated to `DateTime.now()`, /// or otherwise be identical with this note. Note copy({bool updateTimestamp = false}) => Note( id: id, createdAt: (updateTimestamp || createdAt == null) ? DateTime.now() : createdAt, )..update(this, updateTimestamp: updateTimestamp); @override bool operator ==(other) => other is Note && (other.id ?? '') == (id ?? '') && (other.title ?? '') == (title ?? '') && (other.content ?? '') == (content ?? '') && other.stateValue == stateValue && (other.color ?? 0) == (color ?? 0); @override int get hashCode => id?.hashCode ?? super.hashCode; } /// State enum for a note. enum NoteState { unspecified, pinned, archived, deleted, } /// Add properties/methods to [NoteState] extension NoteStateX on NoteState { /// Checks if it's allowed to create a new note in this state. bool get canCreate => this <= NoteState.pinned; /// Checks if a note in this state can edit (modify / copy). bool get canEdit => this < NoteState.deleted; bool operator <(NoteState other) => (this?.index ?? 0) < (other?.index ?? 0); bool operator <=(NoteState other) => (this?.index ?? 0) <= (other?.index ?? 0); /// Message describes the state transition. String get message { switch (this) { case NoteState.archived: return 'Note archived'; case NoteState.deleted: return 'Note moved to trash'; default: return ''; } } /// Label of the result-set filtered via this state. String get filterName { switch (this) { case NoteState.archived: return 'Archive'; case NoteState.deleted: return 'Trash'; default: return ''; } } /// Short message explains an empty result-set filtered via this state. String get emptyResultMessage { switch (this) { case NoteState.archived: return 'Archived notes appear here'; case NoteState.deleted: return 'Notes in trash appear here'; default: return 'Notes you add appear here'; } } }
var _ = require('lodash'); function titleIsCool(isCool, title) { if (isCool) { var words = _.compact(title.split(/\W/)); return words.every(isCool); } else { return true; } } module.exports = titleIsCool;
<?php /** * @author Tharanga Kothalawala <tharanga.kothalawala@tsk-webdevelopment.com> * @date 15-02-2021 */ namespace TSK\SSO\ThirdParty\Stripe; use TSK\SSO\ThirdParty\VendorConnection; use TSK\SSO\ThirdParty\VendorConnectionFactory; /** * @package TSK\SSO\ThirdParty\Spotify */ class StripeConnectionFactory implements VendorConnectionFactory { /** * Returns a Stripe Connection instance using given credentials. Visit the following links for credentials. * @see https://dashboard.stripe.com/apikeys * @see https://dashboard.stripe.com/settings/applications * * @param string $clientId the client id which can be generated at the Stripe portal * @param string $clientSecret this can be found similar to the clientId * @param string $callbackUrl the url to callback after a third party auth attempt * * @return VendorConnection */ public function get($clientId, $clientSecret, $callbackUrl) { return new StripeConnection( new StripeConfiguration( $clientId, $clientSecret, $callbackUrl ) ); } }
$ModulePath = Split-Path -Parent $MyInvocation.MyCommand.Path; $ModulePath = Resolve-Path "$ModulePath\..\DeployCube\DeployCube.psd1"; import-Module -Name $ModulePath; Describe "Find-AnalysisServicesDeploymentExeLocations" { It "Finds some version" { ( Find-AnalysisServicesDeploymentExeLocations ) | Should -Not -Be $null } } Remove-Module -Name DeployCube
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:little_tree_stronger_flutter/widgets/community/CommunityRoute.dart'; import 'package:little_tree_stronger_flutter/widgets/diet/DietRoute.dart'; import 'package:little_tree_stronger_flutter/widgets/exercise/ExerciseRoute.dart'; import 'package:little_tree_stronger_flutter/widgets/myself/MyselfRoute.dart'; class PageViewWidget extends StatefulWidget{ PageViewWidget(this._pageController); final PageController _pageController; @override State<StatefulWidget> createState() => PageViewWidgetState(_pageController); } class PageViewWidgetState extends State<PageViewWidget>{ PageViewWidgetState(this._pageController); final PageController _pageController; var _currentPageIndex; @override Widget build(BuildContext context) { return PageView.builder( onPageChanged: _pageChange, controller: _pageController, itemBuilder: (BuildContext context,int index) { switch (index){ case 0: return DietRouteWidget();break; case 1: return ExerciseRouteWidget();break; case 2: return CommunityRouteWidget();break; case 3: return MyselfRouteWidget();break; default: return DietRouteWidget();break; } }, itemCount: 4, ); } void _pageChange(int index) { Scaffold.of(context).setState((){ if (_currentPageIndex != index) { _currentPageIndex = index; } }); } }
module Rubydora class Datastream def entity_size(response) if content_length = response["content-length"] content_length.to_i else response.body.length end end end end
package com.github.lany192.arch.fragment import android.content.res.Configuration import android.os.Bundle import androidx.annotation.CallSuper import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import com.elvishew.xlog.Logger import com.elvishew.xlog.XLog import com.github.lany192.arch.R import com.github.lany192.dialog.LoadingDialog import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode abstract class BaseFragment : Fragment() { protected var log: Logger.Builder = XLog.tag(javaClass.name) private var loadingDialog: LoadingDialog? = null @CallSuper override fun onCreate(state: Bundle?) { super.onCreate(state) if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this) } } @CallSuper override fun onResume() { super.onResume() if (immersionBarEnabled()) { initImmersionBar() } } @CallSuper override fun onDestroy() { super.onDestroy() if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this) } } @Subscribe(threadMode = ThreadMode.MAIN) open fun onEvent(event: Void) { } @JvmOverloads fun showLoadingDialog(message: CharSequence? = getString(R.string.loading)) { if (loadingDialog == null) { loadingDialog = LoadingDialog() } loadingDialog!!.setMessage(message) loadingDialog!!.show(this) } fun cancelLoadingDialog() { if (loadingDialog != null) { loadingDialog!!.cancel() loadingDialog = null } } @CallSuper override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (immersionBarEnabled()) { initImmersionBar() } } /** * 是否可以实现沉浸式,当为true的时候才可以执行initImmersionBar方法 * Immersion bar enabled boolean. * * @return the boolean */ fun immersionBarEnabled(): Boolean { return true } open fun initImmersionBar() {} fun <T : ViewModel> getViewModel(modelClass: Class<T>): T { val viewModel = ViewModelProvider(this)[modelClass] if (viewModel is LifecycleObserver) { lifecycle.addObserver((viewModel as LifecycleObserver)) } return viewModel } fun <T : ViewModel> getActivityViewModel(modelClass: Class<T>): T { val viewModel = ViewModelProvider(requireActivity())[modelClass] if (viewModel is LifecycleObserver) { lifecycle.addObserver((viewModel as LifecycleObserver)) } return viewModel } fun <T : ViewModel> getAndroidViewModel(modelClass: Class<T>): T { return ViewModelProvider((requireActivity().applicationContext as ViewModelStoreOwner))[modelClass] } }
// TARGET_BACKEND: JVM // FIR_IDENTICAL // FILE: Some.java public class Some { public static final String HELLO = "HELLO"; } // FILE: AnnotationInAnnotation.kt annotation class Storage(val value: String) annotation class State(val name: String, val storages: Array<Storage>) @State( name = "1", storages = [Storage(value = Some.HELLO)] ) class Test
import { promises as fs } from 'fs'; import { resolve } from 'path'; import execa from 'execa'; import { build } from '../src/cmds/build'; import { SnapsCliGlobals } from '../src/types/package'; // mock the snaps global declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace NodeJS { // eslint-disable-next-line @typescript-eslint/no-empty-interface interface Global extends SnapsCliGlobals {} } } global.snaps = { verboseErrors: false, suppressWarnings: false, isWatching: false, }; const EXAMPLES_PATH = 'examples'; buildExamples(); async function buildExamples() { const examplesDir = await fs.readdir(EXAMPLES_PATH); examplesDir.forEach(async (exampleFile) => { const exampleFilePath = resolve(EXAMPLES_PATH, exampleFile); const exampleFileStat = await fs.stat(exampleFilePath); if (exampleFileStat.isDirectory()) { const srcPath = resolve(exampleFilePath, 'index.js'); const pkgPath = resolve(exampleFilePath, 'package.json'); const pkgStat = await fs.stat(pkgPath); const srcStat = await fs.stat(srcPath); if (pkgStat.isFile() && srcStat.isFile()) { try { // install dependencies await execa('yarn', [], { cwd: exampleFilePath, }); } catch (depsInstallError) { console.log( `Unexpected error when installing dependences in "${exampleFilePath}.`, ); throw depsInstallError; } try { await build({ src: srcPath, dist: resolve(exampleFilePath, 'dist'), sourceMaps: true, stripComments: true, port: 8000, }); } catch (bundleError) { console.log( `Unexpected error while creating bundle in "${exampleFilePath}.`, ); throw bundleError; } } else { throw new Error( `Invalid example directory "${exampleFile}". Ensure it has valid 'package.json' and 'index.js' files.`, ); } } }); }
require_relative 'helpers/title' title("Classes") # What if we could teach a little robot to do this # whenever we turned it on and pressed a button? # A class is like a factory that builds little robots # that are called "instances" class FizzBuzz # when you turn it on, it needs input... def initialize(number) @range = (1..number) end # Then you tell it to do the work! # Here's the button to press to make it go: def output @range.each do |number| if even_split?(number, 3) puts "fizz" elsif even_split?(number, 5) puts "buzz" else puts number end end end private # This is now one of the gears inside the robot def even_split?(num, by) num % by == 0 end end # BIG IDEA: 'private' separates the public interface # from the private details that can change. This # let's our code change over time without users # having to worry about it breaking when they use it. # This is called encapsulation. # Let's turn it on! buzzy = FizzBuzz.new(10) # Now let's press the button to make it go! puts "buzzy the FizzBuzz robot's (instance) output:" buzzy.output pause_here # We can keep stamping them out with different input and # hitting their output buttons, too. puts "dizzy the FizzBuzz robot's (instance) output:" dizzy = FizzBuzz.new(12) dizzy.output pause_here # We don't even need to name them if we just want the output puts "\nUnnamed Robot: Why do I exist?" puts "Programmer: To print 'FizzBuzz" puts "Unnamed Robot: ...oh my god..." FizzBuzz.new(13).output puts "(garbage collector fires up and sweeps him away)" # Extra credit: The next factory is broken. Fix it up then # uncomment the last line from the file. # Counts up to a number, puts "Pling" if even, "Plong" if odd class PlingPlang # when you turn it on, it needs input... def initialize(number) @range = (1..number) end # Then you tell it to do the work! # Here's the button to press to make it go: def output @range.each do |number| if puts "Pling" else puts "Plang" end end end end # PlingPlang.new(12).output
import { HomeComponent } from './../home.component'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { Component, OnInit, Inject } from '@angular/core'; declare let Swiper: any; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { constructor( public dialogRef: MatDialogRef<HomeComponent>, @Inject(MAT_DIALOG_DATA) public data: any) {} ngOnInit() { this.invokeSwiper(); } public invokeSwiper(): void { Swiper('.swiper-container', { "pagination": '.swiper-pagination', "effect": 'coverflow', "grabCursor": true, "centeredSlides": true, "slidesPerView": 'auto', "coverflow": { "rotate": 50, "stretch": 0, "depth": 100, 'modifier': 1, 'slideShadows': true }, "loop": true }); } }
################################################################################ # (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # # 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. ################################################################################ require 'spec_helper' type_class = Puppet::Type.type(:oneview_enclosure_group) enclosure_group_config = { name: 'Enclosure Group', ensure: 'present', data: { 'name' => 'Enclosure Group', 'interconnectBayMappingCount' => '8', 'stackingMode' => 'Enclosure', 'type' => 'EnclosureGroupV200', 'interconnectBayMappings' => [ { 'interconnectBay' => '1', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '2', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '3', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '4', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '5', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '6', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '7', 'logicalInterconnectGroupUri' => nil }, { 'interconnectBay' => '8', 'logicalInterconnectGroupUri' => nil } ] } } describe type_class, integration: true do let(:params) { %i[name data provider] } let(:special_ensurables) { %i[found get_script set_script] } it 'should have expected parameters' do params.each do |param| expect(type_class.parameters).to include(param) end end it 'should accept special ensurables' do special_ensurables.each do |value| expect do described_class.new(name: 'Test', ensure: value, data: {}) end.to_not raise_error end end it 'should require a name' do expect do type_class.new({}) end.to raise_error('Title or name must be provided') end it 'should require a data hash' do modified_config = enclosure_group_config modified_config[:data] = '' expect do type_class.new(modified_config) end.to raise_error(Puppet::ResourceError, 'Parameter data failed on Oneview_enclosure_group[Enclosure Group]: '\ 'Validate method failed for class data: Inserted value for data is not valid') end end
@model EventFinder.Models.Entity.User <div class="partial-profile"> <section class="create-form"> <h3>Редактировать профиль</h3> <form asp-controller="Profile" asp-action="EditProfile" method="post"> <div class="form-main"> <input type="hidden" asp-for="Id" required> <p> <input type="email" asp-for="Email" placeholder="Введите Email" required> <span asp-validation-for="Email" class="error-valid"></span> </p> <p> <input type="text" asp-for="Name" placeholder="Введите Имя"> <span asp-validation-for="Name" class="error-valid"></span> </p> <p> <input type="text" asp-for="SurName" placeholder="Введите Фамилию"> <span asp-validation-for="SurName" class="error-valid"></span> </p> <p> <textarea asp-for="AboutMe" placeholder="Обо мне..."></textarea> <span asp-validation-for="AboutMe" class="error-valid"></span> </p> </div> <button type="submit">Сохранить</button> </form> </section> </div>
/** * GIBS Web Examples * * Copyright 2013 - 2018 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ window.onload = function () { var mapOptions = { center: new google.maps.LatLng(21, 78), zoom: 5, maxZoom: 6 }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); var getTileUrl = function (tile, zoom) { return '//gibs.earthdata.nasa.gov/wmts/epsg3857/best/' + 'MODIS_Terra_Aerosol/default/2013-12-02/' + 'GoogleMapsCompatible_Level6/' + zoom + '/' + tile.y + '/' + tile.x + '.png'; }; var layerOptions = { alt: 'MODIS_Terra_Aerosol', getTileUrl: getTileUrl, maxZoom: 6, minZoom: 1, name: 'MODIS_Terra_Aerosol', tileSize: new google.maps.Size(256, 256), opacity: 0.5 }; var imageMapType = new google.maps.ImageMapType(layerOptions); map.overlayMapTypes.insertAt(0, imageMapType); };
#!/usr/bin/env bash set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" cd $DIR/.. # Bundle Kafka Lag Exporter Helm Chart into a tarball artifact. The `helm package` command will output the artifact # in the CWD it is executed from. echo Package helm chart rm -f ./kafka-lag-exporter-*.tgz helm package ./charts/kafka-lag-exporter
use crate::records; use chrono::prelude::*; use std::collections::HashMap; pub struct Person { pub firstname: String, pub lastname: String, pub birthday: String, } #[allow(dead_code)] pub fn get_month_date(md: &String) -> (u32, u32) { let month_str = md[0..2].to_string(); let date_str = md[2..].to_string(); ( month_str.parse::<u32>().unwrap(), date_str.parse::<u32>().unwrap(), ) } pub fn happy_birthday( map_dates: &HashMap<String, Date<Local>>, birthdays: &Vec<records::Row>, ) -> Vec<Person> { let mut people: Vec<Person> = Vec::new(); for birthday in birthdays { if map_dates.contains_key(&birthday.birthday) { people.push(Person { firstname: birthday.firstname.clone(), lastname: birthday.lastname.clone(), birthday: birthday.birthday.clone(), }) } } people }
# require 'resque_web' Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'about#about' get '/search/:id', to: 'search#search', as: :search get '/suggest/:id', to: 'suggest#suggest', as: :suggest get '/about', to: 'about#about', as: :about post '/api/ocr_resource' mount ResqueWeb::Engine => "/jobs" end
import '@polymer/polymer/polymer-legacy.js'; import 'd2l-localize-behavior/d2l-localize-behavior.js'; import './namespace.js'; import './lang/all.js'; /* @polymerBehavior */ D2L.PolymerBehaviors.AnalyticsDashboards.LocalizeBehaviorImpl = { properties: { resources: { value: function() { return window.D2L.PolymerBehaviors.AnalyticsDashboards.LangTerms; } } } }; /* @polymerBehavior */ D2L.PolymerBehaviors.AnalyticsDashboards.LocalizeBehavior = [ D2L.PolymerBehaviors.LocalizeBehavior, D2L.PolymerBehaviors.AnalyticsDashboards.LocalizeBehaviorImpl ];
from PySide2.QtCore import * from PySide2.QtWidgets import * from PySide2.QtGui import * from ..BindFilter import * class ColorGrid(QFrame): sigPicked = Signal(object) def __init__(self, _gridX, _gridY, _gridSize): QFrame.__init__(self) self.setWindowFlags(Qt.Popup) cLayout = QGridLayout(self) cLayout.setSpacing(0) cLayout.setContentsMargins(0,0,0,0) # todo 210 (fix, widgets) -1: popup ignores Alt+F4 self.tmpFilter = BindFilter({ QEvent.Type.KeyPress: lambda _e: self.close() }) self.installEventFilter(self.tmpFilter) def makeSample(_color): #inline to scope signal lambda cSample = QPushButton() cSample.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) cColor = QColor(_color) cSample.setStyleSheet(f"border:0; background:{cColor.name()}") cSample.clicked.connect(lambda: self.sigPicked.emit(cColor)) return cSample for iX in range(1,_gridX+1): for iY in range(1,_gridY+1): cSample = makeSample( QColor.fromHslF(1.*(iX-1)/_gridX,1,1.*iY/(_gridY+1)) ) cLayout.addWidget(cSample, iY, iX) _gridX += 1 for iY in range(1,_gridY+1): cSample = makeSample( QColor.fromHslF(0,0,1.*iY/(_gridY+1)) ) cLayout.addWidget(cSample, iY, _gridX+1) self.resize(_gridX*_gridSize, _gridY*_gridSize) class ColorPicker(QPushButton): sigChangedColor = Signal(str) color = None def __init__(self, _color): QPushButton.__init__(self) self.setColor(QColor(_color)) self.clicked.connect(self.palettePop) self.lPalette = ColorGrid(12, 6, 15) self.lPalette.sigPicked.connect(self.picked) def picked(self, _color): self.lPalette.hide() if _color.name() == self.color.name(): return self.setColor(_color) self.sigChangedColor.emit(_color.name()) def palettePop(self): # -todo 209 (fix, widgets) +0: bound color picker by screen borders pos = self.mapToGlobal(QPoint(self.width()+2,0)) self.lPalette.move(pos) self.lPalette.setFocus() self.lPalette.show() def setColor(self, _color): self.color = _color self.setStyleSheet( "background-color: " + self.color.name() ) def getColor(self): return self.color
// Copyright 2019 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package k8sutil import ( "bytes" "fmt" "io/ioutil" "path" "path/filepath" "regexp" "github.com/operator-framework/operator-registry/pkg/registry" log "github.com/sirupsen/logrus" apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/version" "sigs.k8s.io/yaml" ) // GetCustomResourceDefinitions returns all CRD manifests of both v1 and v1beta1 // versions in the directory crdsDir. If a duplicate object with different API // versions is found, and error is returned. func GetCustomResourceDefinitions(crdsDir string) ( v1crds []apiextv1.CustomResourceDefinition, v1beta1crds []apiextv1beta1.CustomResourceDefinition, err error) { infos, err := ioutil.ReadDir(crdsDir) if err != nil { return nil, nil, err } // The set of all custom resource GVKs in found CRDs. crGVKSet := map[schema.GroupVersionKind]struct{}{} for _, info := range infos { path := filepath.Join(crdsDir, info.Name()) if info.IsDir() { log.Debugf("Skipping dir: %s", path) continue } b, err := ioutil.ReadFile(path) if err != nil { return nil, nil, fmt.Errorf("error reading manifest %s: %w", path, err) } scanner := NewYAMLScanner(bytes.NewBuffer(b)) for scanner.Scan() { manifest := scanner.Bytes() typeMeta, err := GetTypeMetaFromBytes(manifest) if err != nil { log.Debugf("Skipping manifest in %s: %v", path, err) continue } if typeMeta.Kind != "CustomResourceDefinition" { continue } // Unmarshal based on CRD version. var crGVKs []schema.GroupVersionKind switch gvk := typeMeta.GroupVersionKind(); gvk.Version { case apiextv1.SchemeGroupVersion.Version: crd := apiextv1.CustomResourceDefinition{} if err = yaml.Unmarshal(manifest, &crd); err != nil { return nil, nil, err } v1crds = append(v1crds, crd) crGVKs = append(crGVKs, GVKsForV1CustomResourceDefinitions(crd)...) case apiextv1beta1.SchemeGroupVersion.Version: crd := apiextv1beta1.CustomResourceDefinition{} if err := yaml.Unmarshal(manifest, &crd); err != nil { return nil, nil, err } v1beta1crds = append(v1beta1crds, crd) crGVKs = append(crGVKs, GVKsForV1beta1CustomResourceDefinitions(crd)...) default: return nil, nil, fmt.Errorf("unrecognized CustomResourceDefinition version %q", gvk.Version) } // Check if any GVK in crd is a duplicate. for _, gvk := range crGVKs { if _, hasGVK := crGVKSet[gvk]; hasGVK { return nil, nil, fmt.Errorf("duplicate custom resource GVK %s in %s", gvk, path) } crGVKSet[gvk] = struct{}{} } } if err = scanner.Err(); err != nil { return nil, nil, fmt.Errorf("error scanning %s: %w", path, err) } } return v1crds, v1beta1crds, nil } // DefinitionsForV1CustomResourceDefinitions returns definition keys for all // custom resource versions in each crd in crds. //nolint:lll func DefinitionsForV1CustomResourceDefinitions(crds ...apiextv1.CustomResourceDefinition) (keys []registry.DefinitionKey) { for _, crd := range crds { for _, ver := range crd.Spec.Versions { keys = append(keys, registry.DefinitionKey{ Name: crd.GetName(), Group: crd.Spec.Group, Version: ver.Name, Kind: crd.Spec.Names.Kind, }) } } return keys } // DefinitionsForV1beta1CustomResourceDefinitions returns definition keys for all // custom resource versions in each crd in crds. //nolint:lll func DefinitionsForV1beta1CustomResourceDefinitions(crds ...apiextv1beta1.CustomResourceDefinition) (keys []registry.DefinitionKey) { for _, crd := range crds { if len(crd.Spec.Versions) == 0 { keys = append(keys, registry.DefinitionKey{ Name: crd.GetName(), Group: crd.Spec.Group, Version: crd.Spec.Version, Kind: crd.Spec.Names.Kind, }) } for _, ver := range crd.Spec.Versions { keys = append(keys, registry.DefinitionKey{ Name: crd.GetName(), Group: crd.Spec.Group, Version: ver.Name, Kind: crd.Spec.Names.Kind, }) } } return keys } // GVKsForV1CustomResourceDefinitions returns GroupVersionKind's for all // custom resource versions in each crd in crds. func GVKsForV1CustomResourceDefinitions(crds ...apiextv1.CustomResourceDefinition) (gvks []schema.GroupVersionKind) { for _, key := range DefinitionsForV1CustomResourceDefinitions(crds...) { gvks = append(gvks, schema.GroupVersionKind{ Group: key.Group, Version: key.Version, Kind: key.Kind, }) } return gvks } // GVKsForV1beta1CustomResourceDefinitions returns GroupVersionKind's for all // custom resource versions in each crd in crds. //nolint:lll func GVKsForV1beta1CustomResourceDefinitions(crds ...apiextv1beta1.CustomResourceDefinition) (gvks []schema.GroupVersionKind) { for _, key := range DefinitionsForV1beta1CustomResourceDefinitions(crds...) { gvks = append(gvks, schema.GroupVersionKind{ Group: key.Group, Version: key.Version, Kind: key.Kind, }) } return gvks } // ParseGroupSubpackages parses the apisDir directory tree and returns a map of // all found API groups to subpackages. func ParseGroupSubpackages(apisDir string) (map[string][]string, error) { return parseGroupSubdirs(apisDir, false) } // ParseGroupVersions parses the apisDir directory tree and returns a map of // all found API groups to versions. func ParseGroupVersions(apisDir string) (map[string][]string, error) { return parseGroupSubdirs(apisDir, true) } // versionRegexp defines a kube-like version: // https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-versioning var versionRegexp = regexp.MustCompile("^v[1-9][0-9]*((alpha|beta)[1-9][0-9]*)?$") // parseGroupSubdirs searches apisDir for all groups and potential version // subdirs directly beneath each group dir, and returns a map of each group // dir name to all children version dir names. If strictVersionMatch is true, // all potential version dir names must strictly match versionRegexp. If // false, all subdir names are considered valid. func parseGroupSubdirs(apisDir string, strictVersionMatch bool) (map[string][]string, error) { gvs := make(map[string][]string) groups, err := ioutil.ReadDir(apisDir) if err != nil { return nil, fmt.Errorf("error reading directory %q to find API groups: %v", apisDir, err) } for _, g := range groups { if g.IsDir() { groupDir := filepath.Join(apisDir, g.Name()) versions, err := ioutil.ReadDir(groupDir) if err != nil { return nil, fmt.Errorf("error reading directory %q to find API versions: %v", groupDir, err) } gvs[g.Name()] = make([]string, 0) for _, v := range versions { if v.IsDir() { // Ignore directories that do not contain any files, so generators // do not get empty directories as arguments. verDir := filepath.Join(groupDir, v.Name()) files, err := ioutil.ReadDir(verDir) if err != nil { return nil, fmt.Errorf("error reading directory %q to find API source files: %v", verDir, err) } for _, f := range files { if !f.IsDir() && filepath.Ext(f.Name()) == ".go" { // If strictVersionMatch is true, strictly check if v.Name() // is a Kubernetes API version. if !strictVersionMatch || versionRegexp.MatchString(v.Name()) { gvs[g.Name()] = append(gvs[g.Name()], v.Name()) } break } } } } } } if len(gvs) == 0 { return nil, fmt.Errorf("no groups or versions found in %s", apisDir) } return gvs, nil } // CreateFQAPIs return a slice of all fully qualified pkg + groups + versions // of pkg and gvs in the format "pkg/groupA/v1". func CreateFQAPIs(pkg string, gvs map[string][]string) (apis []string) { for g, vs := range gvs { for _, v := range vs { apis = append(apis, path.Join(pkg, g, v)) } } return apis } type CRDVersions []apiextv1beta1.CustomResourceDefinitionVersion func (vs CRDVersions) Len() int { return len(vs) } func (vs CRDVersions) Less(i, j int) bool { return version.CompareKubeAwareVersionStrings(vs[i].Name, vs[j].Name) > 0 } func (vs CRDVersions) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] } //nolint:lll func Convertv1beta1Tov1CustomResourceDefinition(in *apiextv1beta1.CustomResourceDefinition) (*apiextv1.CustomResourceDefinition, error) { var unversioned apiext.CustomResourceDefinition //nolint:lll if err := apiextv1beta1.Convert_v1beta1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(in, &unversioned, nil); err != nil { return nil, err } var out apiextv1.CustomResourceDefinition out.TypeMeta.APIVersion = apiextv1.SchemeGroupVersion.String() out.TypeMeta.Kind = "CustomResourceDefinition" //nolint:lll if err := apiextv1.Convert_apiextensions_CustomResourceDefinition_To_v1_CustomResourceDefinition(&unversioned, &out, nil); err != nil { return nil, err } return &out, nil }
import { Dispatcher } from '../dispatcher/Dispatcher' import { ActionTypes } from './ActionTypes' import { AbstractActionCreator } from './AbstractActionCreator' import { Keyword } from 'pluto-rd'; class ActionCreator extends AbstractActionCreator { public clickKeyword(handle:string): void { this.dispatch({ actionType: ActionTypes.KEYWORD_CLICK, payload: handle }); } public initKeywords( data: { keywords: Keyword[], entryCount: number }) { this.dispatch({ actionType: ActionTypes.KEYWORD_DRIVER_CONNECT, payload: data }); } } //singleton export const WordCloudActionCreator: ActionCreator = new ActionCreator();
package com.example.demo.dao; import com.example.demo.Entity.relation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Map; public interface relationRepository extends JpaRepository<relation, Integer>, JpaSpecificationExecutor<relation> { @Query(value="select p.name from movie q join relation r on q.movieID = r.movieID " + "join person p on p.personID = r.personID " + "where q.title=?1 AND r.isDirector=?2 ORDER BY p.name ASC ",nativeQuery = true) List<String> getAssociateDirector(String title,Character identify); @Query(value="select p.name,q.title from movie q join relation r on q.movieID = r.movieID " + "join person p on p.personID = r.personID " + "where q.title like concat(?1,'%') AND r.isDirector=?2 ORDER BY p.name ASC", nativeQuery = true) List<Map<String,String>> getAssociateDirectorLike(String title, Character identify); @Query(value="select p.name from movie q join relation r on q.movieID = r.movieID " + "join person p on p.personID = r.personID " + "where q.title=?1 AND r.isActor=?2 ORDER BY p.name ASC",nativeQuery = true) List<String> getAssociateActor(String title,Character identify); @Query(value="select p.name,q.title from movie q join relation r on q.movieID = r.movieID " + "join person p on p.personID = r.personID " + "where q.title like concat(?1,'%') AND r.isActor=?2 ORDER BY p.name ASC", nativeQuery = true) List<Map<String,String>> getAssociateActorLike(String title, Character identify); }
const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const morgan = require("morgan"); const { sequelize } = require("./models"); const config = require("./config/config"); const app = express(); require("dotenv").config(); // Used for logging app.use(morgan("combined")); // Body parser middleware app.use(bodyParser.json()); // TODO chnage before production app.use(cors()); // Passport config require("./passport"); require("./routes")(app); sequelize.sync().then(() => { app.listen(process.env.PORT); console.log(`Server started on port ${process.env.PORT}`); });
subroutine sq_snom !! ~ ~ ~ PURPOSE ~ ~ ~ !! this subroutine predicts daily snom melt when the average air !! temperature exceeds 0 degrees Celcius !! ~ ~ ~ INCOMING VARIABLES ~ ~ ~ !! name |units |definition !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! ihru |none |HRU number !! snocov1 |none |1st shape parameter for snow cover equation !! |This parameter is determined by solving the !! |equation for 50% snow cover !! snocov2 |none |2nd shape parameter for snow cover equation !! |This parameter is determined by solving the !! |equation for 95% snow cover !! snotmp(:) |deg C |temperature of snow pack in HRU !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! ~ ~ ~ OUTGOING VARIABLES ~ ~ ~ !! name |units |definition !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! wst(:)%weat%ts(:) |mm H2O |precipitation for the time step during day !! snofall |mm H2O |amount of precipitation falling as freezing !! |rain/snow on day in HRU !! snomlt |mm H2O |amount of water in snow melt for the day in !! |HRU !! snotmp(:) |deg C |temperature of snow pack in HRU !! ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ !! ~ ~ ~ SUBROUTINES/FUNCTIONS CALLED ~ ~ ~ !! Intrinsic: Real, Sin, Exp !! ~ ~ ~ ~ ~ ~ END SPECIFICATIONS ~ ~ ~ ~ ~ ~ use time_module use hydrograph_module use hru_module, only : hru, snotmp, tmpav, tmx, ihru, precip_eff, snocov1, snocov2, & snofall, snomlt use hydrology_data_module use climate_module, only: wst implicit none integer :: ib !none |counter integer :: j !none |HRU number real :: sum !mm H2O |snow water content in HRU on current day real :: smp !mm H2O |precipitation on current day for HRU real :: smfac ! | real :: smleb !mm H2O |amount of snow melt in elevation band on ! |current day real :: xx !none |ratio of amount of current day"s snow water ! |content to the minimum amount needed to ! |cover ground completely real :: snocov !none |fraction of HRU area covered with snow integer :: isno !none |counter integer :: ii !none |counter j = ihru sum = 0. smp = 0. isno = hru(j)%dbs%snow !! estimate snow pack temperature snotmp(j)=snotmp(j) * (1. - snodb(isno)%timp) + tmpav(j) * snodb(isno)%timp if (tmpav(j) <= snodb(isno)%falltmp) then !! calculate snow fall hru(j)%sno_mm = hru(j)%sno_mm + precip_eff snofall = precip_eff precip_eff = 0. if (time%step > 0) wst(iwst)%weat%ts = 0. endif if (tmx(j) > snodb(isno)%melttmp .and. hru(j)%sno_mm > 0.) then !! adjust melt factor for time of year smfac = (snodb(isno)%meltmx + snodb(isno)%meltmn) / 2. + & Sin((time%day - 81) / 58.09) * & (snodb(isno)%meltmx - snodb(isno)%meltmn) / 2. !! 365/2pi = 58.09 snomlt = smfac * (((snotmp(j)+tmx(j))/2.)-snodb(isno)%melttmp) !! adjust for areal extent of snow cover if (hru(j)%sno_mm < snodb(isno)%covmx) then xx = hru(j)%sno_mm / snodb(isno)%covmx snocov = xx / (xx + Exp(snocov1 - snocov2 * xx)) else snocov = 1. endif snomlt = snomlt * snocov if (snomlt < 0.) snomlt = 0. if (snomlt > hru(j)%sno_mm) snomlt = hru(j)%sno_mm hru(j)%sno_mm = hru(j)%sno_mm - snomlt precip_eff = precip_eff + snomlt if (time%step > 0) then do ii = 1, time%step wst(iwst)%weat%ts(ii+1) = wst(iwst)%weat%ts(ii+1) + snomlt / time%step end do end if if (precip_eff < 0.) precip_eff = 0. else snomlt = 0. end if return end subroutine sq_snom
CREATE SCHEMA test AUTHORIZATION test; CREATE TABLE IF NOT EXISTS test.user ( id integer NOT NULL, count_pong NUMERIC, PRIMARY KEY (id) ) WITH ( OIDS = FALSE ); ALTER TABLE test.user OWNER to test; -- CREATE OR REPLACE FUNCTION test.insrease_count(id_ INT) RETURNS VOID AS -- $$ -- BEGIN -- LOOP -- UPDATE test.user SET count_pong = count_pong + 1 WHERE id = id_; -- IF found THEN -- RETURN; -- END IF; -- BEGIN -- INSERT INTO test.user(id, count_pong) VALUES (id_, 1); -- RETURN; -- EXCEPTION WHEN unique_violation THEN -- END; -- END LOOP; -- END; -- $$ -- LANGUAGE plpgsql; -- -- SELECT test.insrease_count(2); -- UPDATE test.user SET count_pong = count_pong + 1 WHERE id = 2;
-- database: presto; groups: ml_functions --! SELECT classify(features(1, 2 + random(1)), model) FROM ( SELECT learn_classifier(labels, features) AS model FROM (VALUES (1, features(1, 2))) t (labels, features) ) t2 --!
using DragonSpark.Sources.Parameterized; using System; namespace DragonSpark.Sources { public sealed class CachedFactoryBuilder<T> : AlterationBase<Func<T>> { public static IParameterizedSource<Func<T>, Func<T>> Default { get; } = new CachedFactoryBuilder<T>(); CachedFactoryBuilder() {} public override Func<T> Get( Func<T> parameter ) => new SuppliedDeferredSource<T>( parameter ).Get; } }
# create-express-backend Generator to scaffold Express backend projects using `npm init express-backend` ![node][node] [![npm version][npm-badge]][npm] [![dependencies Status][dependencies-badge]][dependencies] [![devDependencies Status][dev-dependencies-badge]][dev-dependencies] [![PRs Welcome][prs-badge]][prs] [![GitHub][license-badge]][license] ## Usage * Creating a new project ``` npm init express-backend ``` > Run this command inside an empty folder * Running a generator ``` npm init express-backend login:local ``` > Run this command inside a folder with a previous generated project * List available generators ``` npm init express-backend --list ``` ## Folder structure #### `src/index.js` * Entry point #### `src/init` * Main generator to init a new project * Dispatched using: ``` npm init express-backend <folder> ``` #### `src/generators` * Folder with all generators * All generators must be registed in `src/generators/index.js`: ```javascript // src/generators/index.js const login = require('./login') module.exports = { login, } ``` * Example generator dispatched with: ``` npm init express-backend <generator-name> ``` #### `src/generator/<generator>/<sub-generator>` * A generator can have sub-generators * The generator folder must have an `index.js` file with all sub-generators registered: ```javascript // src/generator/login/index.js const local = require('./local') const oauth = require('./oauth') module.exports = { local, oauth, } ``` * The sub-generator can be dispatched with: ``` npm init express-backend <generator>:<sub-generator> ``` [node]: https://img.shields.io/node/v/create-express-backend.svg [npm-badge]: https://badge.fury.io/js/create-express-backend.svg [npm]: https://badge.fury.io/js/create-express-backend [dependencies-badge]: https://david-dm.org/joaogsleite/create-express-backend/status.svg [dependencies]: https://david-dm.org/joaogsleite/create-express-backend [dev-dependencies-badge]: https://david-dm.org/joaogsleite/create-express-backend/dev-status.svg [dev-dependencies]: https://david-dm.org/joaogsleite/create-express-backend?type=dev [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg [prs]: http://makeapullrequest.com [license-badge]: https://img.shields.io/github/license/joaogsleite/create-express-backend.svg [license]: https://github.com/joaogsleite/create-express-backend/blob/master/LICENSE
docker rm -f ch_sts_testserver &>/dev/null && echo 'Removed old container' docker run --rm -d \ --name ch_sts_testserver \ --network=host \ --volume=$(pwd)/conf.d:/etc/clickhouse-server/conf.d \ --volume=$(pwd)/users.d:/etc/clickhouse-server/users.d \ --volume=$(pwd)/ssl/server.crt:/etc/clickhouse-server/server.crt \ --volume=$(pwd)/ssl/server.key:/etc/clickhouse-server/server.key \ --volume=$(pwd)/ssl/dhparam.pem:/etc/clickhouse-server/dhparam.pem \ --volume=$(pwd)/dictionaries.d:/etc/clickhouse-server/dictionaries.d \ --volume=$(pwd)/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d \ --ulimit nofile=262144:262144 \ yandex/clickhouse-server source ../helpers/wait_for_clickhouse_server_start.sh CHSTS_CLICKHOUSE_HTTP_BASE='https://127.0.0.1:8443/' CHSTS_CLICKHOUSE_HOST='127.0.0.1' CHSTS_CLICKHOUSE_PORT=9440 CHSTS_CLICKHOUSE_USER='default' CHSTS_CLICKHOUSE_SECURE=1
require 'singleton' require 'yaml' require 'tree' require 'redcarpet' require 'pygments' require 'rugged' require_relative 'i-write-docs/diff_to_html' require_relative 'i-write-docs/docs_tree' require_relative 'i-write-docs/markdown_render' require_relative 'i-write-docs/generator' require_relative 'i-write-docs/doc_filter' require_relative 'i-write-docs/git_adapter' module IWriteDocs class IWriteDocsError < StandardError; end def self.config Config.instance end def self.repo GitAdapter.instance end def self.docs_tree DocsTree.instance end class Config include Singleton attr_accessor :subproject def initialize @default_subproject = ENV['DEFAULT_SUBPROJECT'] || 'gear' end def documentation_path ENV['DOCUMENTATION_PATH'] || raise(IWriteDocsError.new("DOCUMENTATION_PATH is not provided in ENV")) end def build_folder ENV['BUILD_FOLDER'] || 'build' end def source_folder ENV["SOURCE_FOLDER"] || 'source' end def subproject @subproject || @default_subproject end end # def self.setup # yield self.config # end end
package fortos.configurations import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.kotlin.registerKotlinModule class ObjectMapperConfiguration { fun loadObjectMapper(): ObjectMapper = ObjectMapper(YAMLFactory()).registerKotlinModule() }
use crate::{publish::Publisher, ValidatedMessage}; use futures_util::stream::Stream; use std::{pin::Pin, task}; /// A blackhole publisher that doesn't publish messages anywhere. /// /// Great for conditionally disabling publishing. /// /// # Examples /// /// ``` /// use hedwig::publish::NullPublisher; /// let publisher = NullPublisher::default(); /// ``` #[derive(Debug, Default, Clone, Copy)] pub struct NullPublisher; impl Publisher for NullPublisher { type MessageId = (); type MessageError = std::convert::Infallible; type PublishStream = NullPublishStream; fn publish<'a, I>(&self, _: crate::Topic, messages: I) -> Self::PublishStream where I: Iterator<Item = &'a ValidatedMessage> + ExactSizeIterator, { NullPublishStream(0..messages.len()) } } /// Stream for `NullPublisher::publish`. pub struct NullPublishStream(std::ops::Range<usize>); impl Stream for NullPublishStream { type Item = Result<(), std::convert::Infallible>; fn poll_next( mut self: Pin<&mut Self>, _: &mut task::Context<'_>, ) -> task::Poll<Option<Self::Item>> { task::Poll::Ready(self.0.next().map(|_| Ok(()))) } }
import 'package:formz/formz.dart'; enum PasswordValidationError { invalid } class Password extends FormzInput<String, PasswordValidationError> { const Password.pure() : super.pure(''); const Password.dirty([String value = '']) : super.dirty(value); @override PasswordValidationError validator(String value) { return value.isNotEmpty ? null : PasswordValidationError.invalid; } }
--- sidebar_position: 4 --- # Frontmatter Module _TODO:ShowHowToUseIndenpendantlyOfTemplating_
--- layout: posts_by_category categories: raspberry-pi title: Raspberry-Pi permalink: /category/raspberry-pi ---
unit rtf2html; (* -------------------------------------------------------------------------------- Revision history: Nb. Date: Author What was done. 004 01-Oct-1999 CMS MAJOR work done-- --Inserted end tags where necessary --Fixed bug that would not modify the color of a font when the rest of the font was unchanged --cleaned up the code and commented 003 ? ? ? 002 21-aug-1997 TSE Minor (very minor) cleanup before release 001 20-aug-1997 TSE Unit created - RtfToHTML function designed and written. Author list: TSE Troels Skovmand Eriksen TSEriksen@cyberdude.com TSErikse@post8.tele.dk ? ? ? CMS Christopher Matthew Sansone ChrisSansone@rocketmail.com Supported features: rev. 001 Indents, Bullets, Left-, Centered & Rightjustified text, Text styles (bold, italics and underline), Fonts (face, size, color). rev. 002 - do - rev. 3 ? -------------------------------------------------------------------------------- This unit and all procedures and functions herein is released as freeware. Any components or units created using this unit or portions hereoff must be released as freeware (This does not cover applications - they may be shareware/commercial as needed). Part of the function RtfToHTML may be covered by some obscure Microsoft copyright since it reads the RTF format - check it out yourself, if you do something worthwhile. Please let this preface stay if you publish a changed/updated version of this unit and write all changes the "Revision history" section above. Who-Dun-it information should be inserted in the "Author list" and the "Supported features" section should be updated. This makes it easier to pass the blame :-) I'm finished with this unit for now - but please email a copy of any changes you make to me - Troels S Eriksen. -------------------------------------------------------------------------------- The following should be fixed - if anybody want to do it? * Should be rewritten into a conversion class - could be tricky, since it seems like a stream only contains 4 Kb at a time ... * Code should be cleaned up - this below is not that fast ... * The indents (\li###) should be translated to <BLOCKQUOTE> or just a <UL> with no <LI> elements. * The hanging paragraphs should be translated to definitionlists ( the <DL COMPACT> <DT> term <DD> definition </DL> structure ) * Tabs (\tab) should be fixed somehow ( heck, I DO want a <TAB> code ! ) * Embedded objects / pictures should be converted to .gif'S - I know it'S possible * Some nice way to handle links ( the way .RTF-sources for helpfiles do ? ) * A even more nice way of handling tables - could fix the indent / tab-problems as well -------------------------------------------------------------------------------- The idea and logic behind this weirdo function : Well, the idea was to write a pascal RTF-2-HTML converter which doesn't just do some "search and replace" - but actually converts the dammed stuff. Since there'S a difference between HTML and RTF in the code-sequencing, I decided to try storing all paragraph and textformatting information in two records (RTFParagraphFormat and RTFTextFormat) and only write the contents of these to the output "stream" when needed. This first attempt is successfull - not highly, but it'll convert the contents of a TRichEdit control and most other .RTF documents to HTML and keep the general layout. Enjoy it Troels S Eriksen, Denmark -------------------------------------------------------------------------------- *) {$LONGSTRINGS ON} interface uses hwsfunctions, ComCtrls; //To use RtfToHtml, just pass the RTF-encoded string, and it will return //the HTML-encoded string. To use RichEditHTML, simply pass the TRichEdit, //and it will return the HTML. function hws_RtfToHtml(const RTF: String): String; function hws_RichEditHTML(ARichEdit: TRichEdit): String; implementation uses Classes, SysUtils, Forms; function hws_RtfToHtml(const RTF: String): String; type THTMLTagState = (htsNotActivated, htsMustActivate, htsActivated, htsMustDeactivate); THTMLTagType = (hftNone, hftBold, hftUnderline, hftItalics, hftFont, hftParagraph); THTMLTagTypes = set of THTMLTagType; THTMLBulletType = (hbtNone, hbtListOpen, hbtListItemOpen, hbtListItemClose, hbtListClose, hbtBreak); TRTFFontState = record FontTable: Boolean; ColorTable: Boolean; FontList, ColorList: TStringList; end; TRTFParagraphFormat = record Alignment: TAlignment; Bullets: THTMLBulletType; Written: Boolean; end; TRTFTextFormat = record WriteFont: Boolean; DefaultFont: Integer; Font: Integer; FontSize: Integer; Color: Integer; Bold: THTMLTagState; Italics: THTMLTagState; Underline: THTMLTagState; Written: Boolean; end; var Index : Integer; // index of the current character RTFParagraphFormat : TRTFParagraphFormat; //paragraph formatting record RTFTextFormat : TRTFTextFormat; //text formatting record RTFFontState : TRTFFontState; //font state record HTMLTagOrder: array[0..4] of THTMLTagType; //ordered array of tags Keyword, FullKeyword: String; //current and full RTF tag ActiveTags: THTMLTagTypes; //active formatting tags Group: Integer; //current number of groups the code is nested in FColor: String[10]; //RTF color information FFont: String[63]; //RTF font information procedure AddTagType(AHTMLTagType: THTMLTagType); {adds the current tag type to the tag array} var i: Integer; begin For i := 0 to High(HTMLTagOrder) do //loop through the array If HTMLTagOrder[i] = AHTMLTagType then //the tag type is already in Exit; //since the tag type is already there, do not add again //the most recent tags are in the front of the array For i := High(HTMLTagOrder) downto 0 do //loop from last to first If HTMLTagOrder[i] = hftNone then begin //empty space in array HTMLTagOrder[i] := AHTMLTagType; //set the empty entry to the tag type Exit; //finished, so exit end; end; procedure InsertTag(AHTMLTagType: THTMLTagType; var S: String); {Inserts the necessary tag into S -- If UpdateArray is True, the array will be updated to include this entry} begin Case AHTMLTagType of hftBold: //add a bold tag begin S := S + '<B>'; RTFTextFormat.Bold := htsActivated; //update the text format record end; hftItalics: //add an italics tag begin S := S + '<I>'; RTFTextFormat.Italics := htsActivated; //update text format record end; hftUnderline: //add an underline tag begin S := S + '<U>'; RTFTextFormat.Underline := htsActivated; //update text format record end; hftFont: //add a font tag begin With RTFTextFormat do //create font tag with current font info S := S + '<FONT FACE="' + RTFFontState.FontList[Font] + '" COLOR="' + RTFFontState.ColorList[Color] + '" SIZE="' + IntToStr(FontSize) + '">'; end; hftParagraph: //add a paragraph tag begin case RTFParagraphFormat.Alignment of //create aligned paragraph tag taLeftJustify : S := S + #13#10'<P>'; taRightJustify: S := S + #13#10'<P ALIGN=RIGHT>'; taCenter : S := S + #13#10'<P ALIGN=CENTER>'; end; end; end; AddTagType(AHTMLTagType); //update the array end; procedure WriteEndTag(AHTMLTagType: THTMLTagType; var S: String); {Writes the end tag of the tag type into S and updates the record-- ***Methods should call WriteEndTags instead, because this method does not update the array of tags.} begin Case AHTMLTagType of hftBold: //write bold end tag begin S := S + '</B>'; RTFTextFormat.Bold := htsNotActivated; //update format record end; hftItalics: //write italics end tag begin S := S + '</I>'; RTFTextFormat.Italics := htsNotActivated; //update format record end; hftUnderline: //write underline end tag begin S := S + '</U>'; RTFTextFormat.Underline := htsNotActivated; //update format record end; hftFont: //write font end tag begin S := S + '</FONT>'; end; hftParagraph: //write paragraph end tag begin S := S + '</P>'#13#10#13#10; end; end; end; procedure WriteEndTags(var S: String; AExcludeTags: THTMLTagTypes); {Writes the end tags for all items in the array except for those excluded} var i: Integer; begin For i := 0 to High(HTMLTagOrder) do //loop through the array If not (HTMLTagOrder[i] in AExcludeTags) then begin //not excluded WriteEndTag(HTMLTagOrder[i], S); //write the end tag into S HTMLTagOrder[i] := hftNone; //reset the entry in the array end; end; procedure WriteChar(C: Char); {Processes the character to HTML and writes the character to the result-- This method also checks to see if text and paragraph tags must be inserted} var S : string; //temporary string begin Application.ProcessMessages; //allow the application to process S := ''; //initialize the return string If (not RTFParagraphFormat.Written) or (not RTFTextFormat.Written) then //either the paragraph format or text format will be changed-- //must keep track of the current format tags in order to deactivate, //add other tags, and reactivate With RTFTextFormat do begin ActiveTags := []; //initialize If Bold = htsActivated then //Bold is staying activated ActiveTags := ActiveTags + [hftBold]; //add Bold to set If Italics = htsActivated then //Italics is staying activated ActiveTags := ActiveTags + [hftItalics]; //add Italics to set If Underline = htsActivated then //Underline is staying activated ActiveTags := ActiveTags + [hftUnderline]; //add Underline to set end; With RTFParagraphFormat do //write the necessary paragraph tags If not Written then begin //changes must be made WriteEndTags(S, []); //close all open tags //write the proper paragraph tags case Bullets of hbtNone: //a new paragraph must be created begin InsertTag(hftParagraph, S); //insert new paragraph tag RTFTextFormat.WriteFont := True; //will add the new font tag RTFTextFormat.Written := False; //must write text format tags end; hbtListOpen: //start a list begin S := S + #13#10'<UL>'; //write the tag RTFTextFormat.WriteFont := True; //will add the new font tag RTFTextFormat.Written := False; //must write text format tags end; hbtListItemOpen: //add a new list item begin S := S + #13#10#9'<LI>'; //write the tag RTFTextFormat.WriteFont := True; //will add the new font tag RTFTextFormat.Written := False; //must write text format tags end; hbtListItemClose: //close a list item begin S := S + '</LI>'; //write the close list item tag end; hbtListClose: //close a list begin S := S + #13#10'</UL>'#13#10; //write the close list tag Bullets := hbtNone; //set paragraph formatting to standard (<P>) end; hbtBreak: //break -- not currently used begin S := S + '<BR>'#13#10#160#32#160#32#160; //insert a break Bullets := hbtNone; //set paragraph formatting to standard (<P>) end; end; Written := True; //flag -- the paragraph tags have been written end; { RTFParagraphFormat } With RTFTextFormat do //now write any necessary text format tags If (not Written) and //changes must be made (RTFParagraphFormat.Bullets <> hbtListOpen) then begin WriteEndTags(S, [hftFont, hftParagraph]); //write format end tags If WriteFont then begin //the font has changed--must write font WriteEndTags(S, [hftParagraph]); //close the font tag if necessary InsertTag(hftFont, S); //insert the new font tag WriteFont := False; //flag -- font has been written end; If (hftBold in ActiveTags) or (Bold = htsMustActivate) then //Bold is either currently active or must be activated InsertTag(hftBold, S); //insert the Bold tag If (hftItalics in ActiveTags) or (Italics = htsMustActivate) then //Italics is either currently active or must be activated InsertTag(hftItalics, S); //insert the Italics tag If (hftUnderline in ActiveTags) or (Underline = htsMustActivate) then //Underline is either currently active or must be activated InsertTag(hftUnderline, S); //insert the Underline tag Written := True; //flag -- text formatting tags have been handled end; //Now write the characters and tags case C of #0 : Result := Result + S; // Writes pending codes only #9 : Result := Result + S + #9; // Writes tab char '>' : Result := Result + S + '&gt'; // Writes "greater than" '<' : Result := Result + S + '&lt'; // Writes "less than" else Result := Result + S + C; // Writes the passed character end; end; { WriteChar } function Resolve(C: Char): Integer; {Converts the character to its integer value -- used to decode \'## to an ansi-Value } begin case Byte(C) of 48..57 : Result := Byte(C) - 48; 65..70 : Result := Byte(C) - 55; else Result := 0; end; end; { resolve } function GetFullKeyword(ARTF: String; StartPos: Integer): String; {Returns the entire keyword for a particular key--keys are separated by ' '} begin Delete(ARTF, 1, StartPos - 1); //remove all text before the key Result := Copy(ARTF, 1, Pos(' ', ARTF) - 1); //return all text before ' ' end; function TagInKeyword(ARTFTag: String): Boolean; {Returns true if a particular tag is in the current keyword (e.g. '\b')} begin Result := Pos(ARTFTag, FullKeyword) > 0; //return true if substring found end; function CollectCode(I: Integer): Integer; {Parses and handles the RTF code beginning at position I to convert to HTML} var Value: String; A: Integer; begin Keyword := ''; //initialize the keyword // First - check if Keyword is any "special" Keyword or is a normal one ... case RTF[i + 1] of //look at the current character '*' : begin // Ignore all code until the end of the Group a := Group; //get the current embedded Group count repeat //loop through each character case RTF[i] of '{' : Inc(Group); //another Group is opened -- increment count '}' : Dec(Group); //a Group is closed -- decrement embedded count end; Inc(i); //go to the next character until (Group + 1) = a; //until the start of another Group is found Result := i - 1; //return the position of the Group start end; #39 : begin // Decode hex Value WriteChar(Char(Resolve(UpCase(RTF[i + 2])) * 16 + Resolve(UpCase(RTF[i + 3])))); Inc(i, 3); //go three spaces ahead Result := i; //return the next position end; '\','{','}' : begin // Return special character WriteChar(RTF[i + 1]); //write the character Inc(i); //go to the next character Result := i; //return the next character end; else begin //must be a keyword repeat //get the keyword Keyword := Keyword + RTF[i]; //add the next character to the keyword Inc(i); //go to the next character until (RTF[i] in ['{','\','}',' ',';','-','0'..'9']); //end of keyword // Second - get any Value following ... Value := ''; //initialize the value While (RTF[i] in ['a'..'z','-','0'..'9']) do begin //value exists Value := Value + RTF[i]; //add the character to value Inc(i); //go to the next character end; while (RTF[i] in ['{', '}', ';', ' ']) do //character can be ignored Inc(i); //ignore the current character Result := i - 1; //return position of previous character // Check which Keyword it is and perform the necessary functionality-- // Tested--Using IF THEN ELSE is 10% more efficient than calling EXIT if Keyword = '\par' then //New paragraph or bullet item with RTFParagraphFormat do begin Written := False; //update the HTML tags if Bullets = hbtListItemOpen then begin //list item currently open Bullets := hbtListItemClose; //must close the list item WriteChar(#0); //write the change end end else if Keyword='\f' then //font change case RTFFontState.FontTable of True: //must add the current font to the font list begin FFont:=''; //initialize current font While RTF[i]<>' ' do // Ignore font family info, etc. Inc(i); Inc(i); //go to next character While RTF[i]<>';' do begin //Read font name until ';' FFont := FFont + RTF[i]; //add character to font name Inc(i); //go to the next character end; Dec(Group); //finished a Group, so close it Result := i + 1; //Move one beyond Group end RTFFontState.FontList.Add(FFont); //Add font name to font list end; False: With RTFTextFormat do begin //Use name already in font list a := StrToIntDef(Value, 0); //get index of font in font list if Font <> a then begin //Font has changed--must make HTML tag WriteFont := True; //must write the new font Written := False; //have not written new text formatting yet Font := a; //set the index of the current font end; end; end else if Keyword = '\plain' then //original text format with RTFTextFormat do begin //must reset all text attributes FullKeyword := GetFullKeyword(RTF, i); //get full keyword If (Color <> 0) and (not TagInKeyword('\cf')) then begin //the current color is not the default color, and the color will //not be updated in this keyword--must reset color and write font Color := 0; //reset the color WriteFont := True; //must write the new font Written := False; //have not written the new text formatting yet WriteChar(#0); //write the new tags end else begin //the color does not need to be updated If (bold = htsActivated) {and (not TagInKeyword('\b'))} then //Bold is no longer active, so it must be deactivated Bold := htsMustDeactivate; //deactivate Bold If (Italics = htsActivated) {and (not TagInKeyword('\i'))} then //Italics is no longer active, so it must be deactivated Italics := htsMustDeactivate; //deactivate Italics If (Underline = htsActivated) {and (not TagInKeyword('\ul'))} then //Underline is no longer active, so it must be deactivated Underline := htsMustDeactivate; //deactivate Underline if (Bold = htsMustDeactivate) or (Italics = htsMustDeactivate) or (Underline = htsMustDeactivate) then begin //one or more attributes have changed--must write the new tags Written := False; //have not written new text formatting yet WriteChar(#0); //write the new tags end else //no attributes have changed -- no need to write anything WriteFont := False; //do not update the font end; end else if Keyword = '\fs' then //modify the font size with RTFTextFormat do begin case StrToIntDef(Value, 11) div 2 of 1.. 5 : a := 1; //set an appropriate font size 6.. 9 : a := 2; 10..11 : a := 3; 12..13 : a := 4; 14..15 : a := 5; else a := 6; end; if a <> FontSize then begin //the font size has changed FontSize := a; //set the new font size Written := False; //have not written the new font size yet WriteFont := True; //write the new font end; end else if Keyword = '\tab' then //tab character WriteChar(#9) //send a tab character--displayed as a space in HTML else if Keyword = '\ul' then begin //Underline is activated with RTFTextFormat do if Underline = htsNotActivated then begin //must activate Underline Underline := htsMustActivate; //activate Underline Written := False; //have not written new attribute yet end; end else if Keyword = '\b' then begin //Bold is activated with RTFTextFormat do if Bold = htsNotActivated then begin //must activate Bold Bold := htsMustActivate; //activate Bold Written := False; //have not written new attribute yet end; end else if Keyword = '\i' then begin //Italics is activated with RTFTextFormat do if Italics = htsNotActivated then begin //must activate Italics Italics := htsMustActivate; //activate Italics Written := False; //have not written new attribute yet end; end else if Keyword = '\cf' then //font color has been changed with RTFTextFormat do begin a := StrToIntDef(Value, 0); //get index of color in the color list If Color <> a then begin //the color has changed Color := a; //set the new color Written := False; //have not written the new color yet WriteFont := True; //write the new font end; end else if Keyword = '\qc' then begin //paragraph must be centered With RTFParagraphFormat do If Bullets = hbtNone then begin Alignment := taCenter; //align the paragraph to center Written := False; //alignment has not been written yet end; end else if Keyword = '\qr' then begin //paragraph must be right-aligned With RTFParagraphFormat do If Bullets = hbtNone then begin Alignment := taRightJustify; //align the paragraph to right Written := False; //alignment has not been written yet end; end else if Keyword = '\pntext' then //Start bullet list item with RTFParagraphFormat do begin Written := False; //have not written the bullet tag yet Bullets := hbtListItemOpen; //the current item is a new list item a := Group; //get current embedded group count repeat //go through the RTF until a group is closed case RTF[i] of '{': Inc(Group); //new group to open--increment Group '}': Dec(Group); //group is closed--decrement Group end; Inc(i); //go to the next character until (Group + 1) = a; //until the end of a group has been reached Result := i - 1; //go to the end of the group end else if Keyword = '\fi' then //a bullet list must be started with RTFParagraphFormat do begin Written := False; //bullet tag has not been written Bullets := hbtListOpen; //the current bullet type is an open list WriteChar(#0); //write the open list tag end else if Keyword = '\pard' then //end of paragraph / bullet list with RTFParagraphFormat do begin Alignment := taLeftJustify; //reset the paragraph alignment to left Written := False; //have not written the paragraph change yet If Bullets <> hbtNone then begin //currently in an open bullet list Bullets := hbtListClose; //close the bullet list WriteChar(#0); //write the close list tag end; end else if Keyword = '\red' then //setting red color FColor := '#' + IntToHex(StrToIntDef(Value, 255), 2) //Get red color else if Keyword = '\green' then //setting green color FColor := FColor + IntToHex(StrToIntDef(Value, 255), 2) //Get color else if Keyword = '\blue' then begin //setting blue color--finished FColor := FColor + IntToHex(StrToIntDef(Value, 255), 2); //Get color RTFFontState.ColorList.Add(FColor); //Add RGB to the color list end else if Keyword = '\deff' then //default font index with RTFTextFormat do DefaultFont := StrToIntDef(Value, 0) //set the default font index else if Keyword = '\fonttbl' then //must create an entry in font list RTFFontState.FontTable := True //initialize creation of font list else if Keyword = '\colortbl' then //must create a color list RTFFontState.ColorTable := True //must create an entry in color list else if Keyword = '\deflang' then begin //Update is finished RTFFontState.FontTable := False; //finished creating font list entry With RTFParagraphFormat do begin // reset paragraph format Alignment := taLeftJustify; //reset paragraph alignment to left Written := False; //have not written new paragraph tags yet Bullets := hbtNone; //reset bullets to standard paragraphs end; With RTFTextFormat do begin //reset font format Font := DefaultFont; //set the font index to the default index FontSize := 3; //reset the font size to default Color := 0; //reset the color index to the default index Bold := htsNotActivated; //initialize bold Italics := htsNotActivated; //initialize italics Underline := htsNotActivated; //initialize underline Written := False; //have not written the new font settings yet end; RTFFontState.ColorTable := True; //must start creating color entry end; end; end; end; function CleanUp(S: String): String; {Occurs when the HTML code has been completed-- Closes any remaining open tags and returns the updated code} begin WriteEndTags(S, []); Result := S; end; var i: Integer; begin try For i := 0 to High(HTMLTagOrder) do //loop through entire array HTMLTagOrder[i] := hftNone; //initialize the entire array to hftNone RTFFontState.FontList := TStringList.Create; //Create font list RTFFontState.ColorList := TStringList.Create; //Create color list RTFParagraphFormat.Written := True; //initialize RTFTextFormat.Written := True; //initialize--will be false on first format Index := 0; //initialize the index Result := ''; //initialize the result repeat Inc(Index); //go to the next character case RTF[Index] of #0..#31 : ; //ASCII control characters -- ignore '{': Inc(Group); //new group -- increment embedded group count '}': Dec(Group); //closed group -- decrement embedded group count '\': Index := CollectCode(Index); //RTF keyword--update HTML tags else begin //a standard character -- just write it to the result WriteChar(RTF[Index]); //Write char and any pending HTML codes Inc(Index); //Speed-write normal characters until next special one while (Index < Length(RTF)) and not (RTF[Index] in ['{','}','\','<','>',#00..#31]) do begin //have not reached end of RTF yet and current character is standard Result := Result + RTF[Index]; //add current character to result Inc(Index); //go to next result end; Dec(Index); //go back one character (incremented one too many times) end; end; until Index = Length(RTF); //until all code has been processed finally Result := CleanUp(Result); //Return the completed HTML document With RTFFontState do begin FontList.Free; //destroy the font list ColorList.Free; //destroy the color list end; end; end; function hws_RichEditHTML(ARichEdit: TRXRichEdit): String; var MS: TMemoryStream; RichText: String; begin RichText := ''; MS:= TMemoryStream.Create; //create a memory stream try ARichEdit.Lines.SaveToStream(MS); //save the RTF text to stream RichText := PChar(MS.Memory); //get the resulting text stream Result := hws_RtfToHtml(RichText); finally MS.Free; //destroy the memory stream end; end; end.
import { Component, OnInit } from '@angular/core'; import { EventService } from 'app/services/enterprise-services/event.service'; import { Participation } from 'app/services/enterprise-services/models/participation'; import { User } from 'app/services/user-services/models/user'; import { Event } from 'app/services/enterprise-services/models/event'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-listevent-page', templateUrl: './listevent-page.component.html', styleUrls: ['./listevent-page.component.scss'] }) export class ListeventPageComponent implements OnInit { data : Date = new Date(); events:Event[]=[]; participations:Participation[]=[]; idSelected; searchText; collection = { count: null, events: [] }; config:any; hidden1=true; constructor(private eventService:EventService, private toastr: ToastrService) { } ngOnInit() { var body = document.getElementsByTagName('body')[0]; body.classList.add('blog-posts'); var navbar = document.getElementsByTagName('nav')[0]; navbar.classList.remove('navbar-transparent'); navbar.classList.add('bg-danger'); var body = document.getElementsByTagName('body')[0]; body.classList.add('search-page'); var navbar = document.getElementsByTagName('nav')[0]; navbar.classList.add('bg-danger'); this.eventService.GetAllEvent().subscribe(e => { this.collection.events = e; for(let i=0;i<e.length;i++){ this.eventService.GetUniquePart(e[i]['eeid'],localStorage.getItem('id')).subscribe(p => { if (p['status']==='ok'){ this.hidden1=false;} else{this.hidden1=true;} console.log(p); this.participations =p; }) console.log(e); } }); this.config = { itemsPerPage: 4, currentPage: 1, totalItems: this.collection.count }; } ngOnDestroy(){ var body = document.getElementsByTagName('body')[0]; body.classList.remove('blog-posts'); var navbar = document.getElementsByTagName('nav')[0]; navbar.classList.remove('bg-danger'); navbar.classList.add('navbar-transparent'); } Participate(id){ this.idSelected=id; this.eventService.AddParticipation(id,localStorage.getItem('id')).subscribe(p => { this.toastr.success('check your email for ridaction code!', 'Success!', {timeOut: 2000});; this.load(id); console.log(p); this.participations =p; }) } load(id){ this.eventService.GetAllEvent().subscribe(e => { this.collection.events = e; this.eventService.GetUniquePart(id,localStorage.getItem('id')).subscribe(p => { if (p['status']=='ok'){ this.hidden1=false;} else{this.hidden1=true;} console.log(p); this.participations =p; }) console.log(e); }); } pageChanged(event){ this.config.currentPage = event; } showSuccess() { this.toastr.success('Hello world!', 'Toastr fun!', {timeOut: 2000});; } showError() { this.toastr.error('everything is broken', 'Major Error', { timeOut: 3000 }); } }
<?php if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); class CustomCurrentUserMobileApi extends CurrentUserMobileApi { /** * Register api endpoints * @return array */ public function registerApiRest() { //in case we want to add additional endpoints return parent::registerApiRest(); } /** * Retrieves the current user info * * @param $api * @param $args * @return array */ public function retrieveCurrentUser($api, $args) { $data = parent::retrieveCurrentUser($api, $args); $current_user = $this->getUserBean(); \BeanFactory::newBean('IRM_IPRestrictionManager')->validateAPI($api, $current_user->user_name, $api->platform); return $data; } }
import styled from '@emotion/styled' export const Container = styled.section` padding: 1rem 0; ` export const Grid = styled.div` display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; `
Spree::Core::Engine.add_routes do # Add your extension routes here post '/webpay/webpay_final_url', :to => 'webpay#webpay_final_url', :as => :webpay_result post '/webpay/webpay_return_url', :to => 'webpay#webpay_return_url', :as => :webpay_return_url get 'webpay/success', :to => 'webpay#webpay_success', :as => :webpay_success get 'webpay/error', :to => 'webpay#webpay_error', :as => :webpay_error get 'webpay/nullify', :to => 'webpay#webpay_nullify', :as => :webpay_nullify end
namespace Store.Messages.Events { using NServiceBus; public class HaveOrderAccepted : IEvent, IHaveCustomerInfo, IHaveOrderNumber { public int OrderNumber { get; set; } public string[] ProductIds { get; set; } public string ClientId { get; set; } } }
package main import ( "flag" "fmt" "os" "strings" "golang.org/x/net/html" ) func main() { fileFlag := flag.String("file", "example.html", "The HTML file to be parsed.") flag.Parse() file, err := os.Open(*fileFlag) checkError(err) tree, err := html.Parse(file) checkError(err) links := make([]link, 0) addLink := func(href string, text string) { links = append(links, link{href: href, text: text}) } visit(tree, makeVisitor(addLink)) fmt.Println(links) } func checkError(err error) { if err != nil { panic(err) } } type link struct { href string text string } func visit(tree *html.Node, visitor func(*html.Node)) { visitor(tree) for child := tree.FirstChild; child != nil; child = child.NextSibling { visit(child, visitor) } } func makeVisitor(addLink func(string, string)) func(*html.Node) { visitor := func(node *html.Node) { if node.Type == html.ElementNode && node.Data == "a" { href := getHref(node) text := "" getText(node, &text) addLink(href, text) } } return visitor } func getHref(node *html.Node) string { attributes := node.Attr for _, attribute := range attributes { if attribute.Key == "href" { return attribute.Val } } return "" } func getText(node *html.Node, text *string) { if node.Type == html.TextNode { s := strings.TrimSpace(node.Data) if len(*text) > 0 { *text += " " } *text += s } for child := node.FirstChild; child != nil; child = child.NextSibling { getText(child, text) } }
import React, { FC, useState, useEffect, ChangeEvent, KeyboardEvent } from 'react' import { Grid, Button, Table, TableContainer, TableHead, TableRow, TableCell, TableBody, TextField, Paper } from '@mui/material' import Axios from 'axios' import capitalize from 'capitalize' import './editor.scss' import { server as serverConfig } from '@/config' //TODO pass down to child using cloneElement //TODO implement country const EditorPage = () => ( <Grid container id='editor-page'> <Wrapper label='attributes' name='attribute'> <WrapperItem label='attribute' /> </Wrapper> <Wrapper label='categories' name='category'> <WrapperItem label='category' /> </Wrapper> <Wrapper label='locations' name='location'> <WrapperItem label='location' /> </Wrapper> <Wrapper label='countries' name='country'> <WrapperItemCountries label='country' /> </Wrapper> </Grid> ) const Wrapper: FC<{ label: string; name: string }> = ({ label, name, children }) => { const [input, setInput] = useState('') const handleChange = (e: ChangeEvent<HTMLInputElement>) => setInput(e.currentTarget.value) const handleSubmit = () => { if (input.length) { if (input.toLowerCase() === input) return false Axios.post(`${serverConfig.api}/${name}`, { name: input }).then(() => { window.location.reload() //TODO use stateObj instead }) } } const handleKeyPress = (e: KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault() handleSubmit() } } return ( <Grid item xs={3} style={{ paddingLeft: 5, paddingRight: 5, marginTop: 5 }}> <Grid container justifyContent='center' style={{ marginBottom: 10 }}> <Grid item component='h2'> {capitalize(label)} </Grid> <Grid item> <TextField variant='standard' onChange={handleChange} onKeyPress={handleKeyPress} style={{ marginLeft: 5, marginRight: 5 }} /> <Button variant='contained' color='primary' size='small' onClick={handleSubmit} style={{ marginTop: 2 }} > Add {capitalize(name)} </Button> </Grid> </Grid> {children} </Grid> ) } const WrapperItem = ({ label }: { label: string }) => { const [data, setData] = useState([]) const updateItem = (ref: any, value: any) => { Axios.put(`${serverConfig.api}/${label}/${ref.id}`, { value }).then(() => { setData( [...data].filter((item: any) => { if (ref.id === item.id) item.name = value return item }) ) }) } useEffect(() => { Axios.get(`${serverConfig.api}/${label}`).then(({ data }) => { setData(data.sort((a: { id: number; name: string }, b: { id: number; name: string }) => a.id - b.id)) }) }, []) return ( <TableContainer component={Paper}> <Table size='small' className='table-striped'> <TableHead> <TableRow> <TableCell>ID</TableCell> <TableCell>{capitalize(label)}</TableCell> </TableRow> </TableHead> <TableBody> {data.map((item: any) => ( <Item key={item.id} data={item} update={updateItem} /> ))} </TableBody> </Table> </TableContainer> ) } const WrapperItemCountries = ({ label }: { label: string }) => { const [data, setData] = useState([]) const updateItem = (ref: { id: number }, value: string, label: string) => { Axios.put(`${serverConfig.api}/country/${ref.id}`, { label, value }).then(({ data: countryData }) => { setData( [...data].filter((country: any) => { if (ref.id === country.id) { country.name = countryData.name country.code = countryData.code } return country }) ) }) } useEffect(() => { Axios.get(`${serverConfig.api}/${label}`).then(({ data }) => { setData(data.sort((a: any, b: any) => a.id - b.id)) }) }, []) return ( <TableContainer component={Paper}> <Table size='small' className='table-striped'> <TableHead> <TableRow> <TableCell>ID</TableCell> <TableCell>Country</TableCell> <TableCell>Code</TableCell> <TableCell>Flag</TableCell> </TableRow> </TableHead> <TableBody> {data.map((item: any) => ( <ItemCountry key={item.id} data={item} updateCountry={(ref: any, value: any) => updateItem(ref, value, 'country')} updateCode={(ref: any, value: any) => updateItem(ref, value, 'code')} /> ))} </TableBody> </Table> </TableContainer> ) } const Item = ({ update, data }: any) => { const [edit, setEdit] = useState(false) const [value, setValue] = useState('') const save = () => { setEdit(false) if (value.length) update(data, value) } return ( <TableRow> <TableCell>{data.id}</TableCell> <TableCell> {edit ? ( <TextField variant='standard' defaultValue={data.name} autoFocus onBlur={save} onKeyPress={(e) => { if (e.key === 'Enter') { save() } }} onChange={(e) => setValue(e.currentTarget.value)} /> ) : ( <span onClick={() => setEdit(true)}>{data.name}</span> )} </TableCell> </TableRow> ) } const ItemCountry = ({ updateCountry, updateCode, data }: any) => { const [country, setCountry] = useState<{ edit: boolean; value: null | string }>({ edit: false, value: null }) const [code, setCode] = useState<{ edit: boolean; value: null | string }>({ edit: false, value: null }) const saveCountry = () => { setCountry({ ...country, edit: false }) if (country.value) updateCountry(data, country.value) } const saveCode = () => { setCode({ ...code, edit: false }) if (code.value) updateCode(data, code.value) } return ( <TableRow> <TableCell>{data.id}</TableCell> <TableCell onClick={() => setCountry({ ...country, edit: true })}> {country.edit ? ( <TextField variant='standard' defaultValue={data.name} autoFocus onBlur={saveCountry} onChange={(e) => setCountry({ ...country, value: e.target.value })} onKeyPress={(e: React.KeyboardEvent) => { if (e.key === 'Enter') saveCountry() }} /> ) : ( <span>{data.name}</span> )} </TableCell> <TableCell onClick={() => setCode({ ...code, edit: true })}> {code.edit ? ( <TextField variant='standard' defaultValue={data.code} autoFocus onBlur={saveCode} onChange={(e) => setCode({ ...code, value: e.target.value })} inputProps={{ maxLength: 2 }} onKeyPress={(e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Enter') saveCode() }} /> ) : ( <span>{data.code}</span> )} </TableCell> <TableCell className='pb-0'> <i className={`flag flag-${data.code}`} /> </TableCell> </TableRow> ) } export default EditorPage
module Takeaway.Data.Acid.ID ( module Takeaway.Data.Acid.ID_v0 ) where import Takeaway.Data.Acid.ID_v0
% Keeps a map of url prefix -> module/handler % so plugins can register to handle certain web requests. -module(playdar_http_registry). -behaviour(gen_server). %% API -export([start_link/0, get_handler/1, register_handler/2, register_handler/3, register_handler/4, get_all/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {db}). %% API start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). get_handler(Url) -> gen_server:call(?MODULE, {get_handler, Url}). register_handler(Urlprefix, Fun) -> register_handler(Urlprefix, Fun, "", ""). register_handler(Urlprefix, Fun, MenuText) -> register_handler(Urlprefix, Fun, MenuText, ""). register_handler(Urlprefix, Fun, MenuText, MenuUrl) -> gen_server:cast(?MODULE, {register, Urlprefix, Fun, MenuUrl, MenuText}). get_all() -> gen_server:call(?MODULE, all). %% gen_server callbacks init([]) -> P = ets:new(db, []), % hardcoded handlers that ship by default: register_handler("api", fun playdar_http_api:http_req/2, "Handles core Playdar API"), register_handler("ws:api", fun playdar_websocket_api:req/2, "Websocket Playdar API"), register_handler("logger", fun playdar_logger:http_req/2, "View log output in realtime", "/logger"), {ok, #state{db=P}}. handle_call(all, _From, State) -> R = [ [{prefix, P},{menu_url, Murl},{menu_text,Mtxt}] || {P,_,Murl, Mtxt} <- ets:tab2list(State#state.db) ], {reply, R, State}; handle_call({get_handler, Url}, _From, State) -> case ets:lookup(State#state.db, prefix(Url)) of [{_,Fun,_,_}] when is_function(Fun) -> {reply, Fun, State}; _ -> {reply, undefined, State} end. handle_cast({register, Urlprefix, Fun, MenuUrl, MenuText}, State) -> ets:insert(State#state.db, {Urlprefix, Fun, MenuUrl, MenuText}), {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%% Internal functions % Eg: /api/?method=foo -> api prefix(Url) -> hd(string:tokens(Url,"/")).
{-# LANGUAGE BangPatterns #-} module ZIO.Interpreter where import ZIO.Prelude import Control.Exception (throwIO) import qualified Data.Map as Map import qualified ZIO.Language as L import qualified ZIO.Runtime as R import qualified ZIO.Types as T import qualified ZIO.Effects.Effect.Interpreter as R interpretZIOF :: R.ZIORuntime -> L.ZIOF a -> IO a interpretZIOF rt (L.EvalAsyncEffect eff next) = do asyncVar <- R.runAsyncEffect rt eff next <$> R.awaitAsyncVar asyncVar -- interpretZIOF rt (L.EvalSynchronously eff next) = do -- asyncVar <- R.runAsyncEffectSynchronously rt eff -- next <$> R.awaitAsyncVar asyncVar interpretZIOF rt (L.EvalEffect eff next) = next <$> R.runEffect rt eff interpretZIOF rt (L.EvalSafely act next) = next <$> (try $ runZIO rt act) runZIO :: R.ZIORuntime -> L.ZIO a -> IO a runZIO rt = foldFree (interpretZIOF rt)
CREATE TABLE hr.instructor ( idinstructor INT NOT NULL, iNombre VARCHAR(45) NOT NULL, iPaterno VARCHAR(45) NULL, iMaterno VARCHAR(45) NULL, Carrera VARCHAR(45) NULL, Especialidad VARCHAR(45) NULL, iEmail VARCHAR(45) NULL, iTelefono VARCHAR(45) NULL, iDireccion VARCHAR(45) NULL, PRIMARY KEY (idinstructor) ); -- ----------------------------------------------------- -- Table hr.cursos -- ----------------------------------------------------- CREATE TABLE hr.cursos ( idcursos INT NOT NULL, nombre VARCHAR(45) NOT NULL, horario VARCHAR(45) NULL, fechaInicio VARCHAR(45) NULL, fechaFin VARCHAR(45) NULL, tipo VARCHAR(45) NOT NULL, i_idinstructor INT NOT NULL, PRIMARY KEY (idcursos), CONSTRAINT fk_cursos_instructor1 FOREIGN KEY (i_idinstructor) REFERENCES hr.instructor (idinstructor) ); -- ----------------------------------------------------- -- Table hr.evaluaciones -- ----------------------------------------------------- CREATE TABLE hr.evaluaciones ( idevaluacion INT NOT NULL, c_idcursos INT NOT NULL, nombre VARCHAR(45) NOT NULL, idAlumno INT NOT NULL, fechaInicio DATE NOT NULL, fechaFin DATE NOT NULL, tiempo VARCHAR(30) NOT NULL, PRIMARY KEY (idevaluacion), CONSTRAINT fk_evaluaciones_cursos1 FOREIGN KEY (c_idcursos) REFERENCES hr.cursos (idcursos) ); -- ----------------------------------------------------- -- Table hr.preguntas -- ----------------------------------------------------- CREATE TABLE hr.preguntas ( idpregunta INT NOT NULL, e_idevaluacion INT NOT NULL, idEvaluacion INT NOT NULL, Pregunta VARCHAR(45) NOT NULL, PRIMARY KEY (idpregunta), CONSTRAINT fk_preguntas_evaluaciones1 FOREIGN KEY (e_idevaluacion) REFERENCES hr.evaluaciones (idevaluacion) ); -- ----------------------------------------------------- -- Table hr.Respuestas -- ----------------------------------------------------- CREATE TABLE hr.Respuestas ( idRespuesta INT NOT NULL, p_idpregunta INT NOT NULL, Respuesta VARCHAR(45) NOT NULL, Solucion VARCHAR(45) NOT NULL, Puntaje VARCHAR(45) NOT NULL, PRIMARY KEY (idRespuesta), CONSTRAINT fk_Respuestas_preguntas1 FOREIGN KEY (p_idpregunta) REFERENCES hr.preguntas (idpregunta) ); -- ----------------------------------------------------- -- Table hr.templetes -- ----------------------------------------------------- CREATE TABLE hr.templetes ( idtempletes INT NOT NULL, descripcion VARCHAR(150) NULL, imagen VARCHAR(45) NULL, PRIMARY KEY (idtempletes) ); -- ----------------------------------------------------- -- Table hr.pais -- ----------------------------------------------------- CREATE TABLE hr.pais ( idPais INT NOT NULL, nombre VARCHAR(45) NOT NULL, region VARCHAR(45) NULL, PRIMARY KEY (idPais) ); -- ----------------------------------------------------- -- Table hr.ciudad -- ----------------------------------------------------- CREATE TABLE hr.ciudad ( idCiudad INT NOT NULL, nombre VARCHAR(45) NULL, p_idPais INT NOT NULL, PRIMARY KEY (idCiudad), CONSTRAINT fk_ciudad_pais1 FOREIGN KEY (p_idPais) REFERENCES hr.pais (idPais) ); -- ----------------------------------------------------- -- Table hr.promociones -- ----------------------------------------------------- CREATE TABLE hr.promociones ( idpromociones INT NOT NULL, tipo VARCHAR(45) NULL, PRIMARY KEY (idpromociones) ); -- ----------------------------------------------------- -- Table hr.eventos -- ----------------------------------------------------- CREATE TABLE hr.eventos ( idevento INT NOT NULL, nombre VARCHAR(45) NOT NULL, fechaInicio DATE NULL, descripcion VARCHAR(45) NULL, programa VARCHAR(45) NULL, i_idinstructor INT NOT NULL, lugar VARCHAR(45) NULL, c_idCiudad INT NOT NULL, capacidad VARCHAR(45) NOT NULL, tipo VARCHAR(45) NULL, estatus VARCHAR(45) NULL, costo VARCHAR(45) NULL, t_idtempletes INT NOT NULL, p_idpromociones INT NOT NULL, PRIMARY KEY (idevento), CONSTRAINT fk_eventos_instructor1 FOREIGN KEY (i_idinstructor) REFERENCES hr.instructor (idinstructor), CONSTRAINT fk_eventos_templetes1 FOREIGN KEY (t_idtempletes) REFERENCES hr.templetes (idtempletes), CONSTRAINT fk_eventos_ciudad1 FOREIGN KEY (c_idCiudad) REFERENCES hr.ciudad (idCiudad), CONSTRAINT fk_eventos_promociones1 FOREIGN KEY (p_idpromociones) REFERENCES hr.promociones (idpromociones) ); -- ----------------------------------------------------- -- Table hr.empresa -- ----------------------------------------------------- CREATE TABLE hr.empresa ( idEmpresa INT NOT NULL, nombre VARCHAR(45) NULL, email VARCHAR(45) NULL, telefono VARCHAR(45) NULL, direccion VARCHAR(45) NULL, PRIMARY KEY (idEmpresa) ); -- ----------------------------------------------------- -- Table hr.alumno -- ----------------------------------------------------- CREATE TABLE hr.alumno ( idalumno INT NOT NULL, aNombre VARCHAR(45) NOT NULL, aPaterno VARCHAR(45) NOT NULL, aMaterno VARCHAR(45) NOT NULL, telefono VARCHAR(45) NULL, email VARCHAR(45) NULL, e_idEmpresa INT NOT NULL, carrera VARCHAR(45) NULL, notebook VARCHAR(45) NOT NULL, status VARCHAR(45) NOT NULL, PRIMARY KEY (idalumno), CONSTRAINT fk_alumno_empresa1 FOREIGN KEY (e_idEmpresa) REFERENCES hr.empresa (idEmpresa) ); -- ----------------------------------------------------- -- Table hr.materiales -- ----------------------------------------------------- CREATE TABLE hr.materiales ( idmaterial INT NOT NULL, mNombre VARCHAR(45) NOT NULL, mDescripcion VARCHAR(45) NULL, mRuta VARCHAR(45) NULL, c_idcursos INT NOT NULL, PRIMARY KEY (idmaterial), CONSTRAINT fk_materiales_cursos1 FOREIGN KEY (c_idcursos) REFERENCES hr.cursos (idcursos) ); -- ----------------------------------------------------- -- Table hr.factura -- ----------------------------------------------------- CREATE TABLE hr.factura ( idfactura INT NOT NULL, valor VARCHAR(30) NOT NULL, descripcion VARCHAR(100) NULL, RCFexpide VARCHAR(45) NOT NULL, selloDigital VARCHAR(45) NOT NULL, lugar VARCHAR(45) NULL, fecha DATE NOT NULL, RFCrecibe VARCHAR(45) NOT NULL, valorLetra VARCHAR(100) NULL, certificadoDigital VARCHAR(45) NOT NULL, PRIMARY KEY (idfactura) ); -- ----------------------------------------------------- -- Table hr.pagos -- ----------------------------------------------------- CREATE TABLE hr.pagos ( idpagos INT NOT NULL, f_idfactura INT NOT NULL, tipo VARCHAR(20) NOT NULL, status INT NULL, PRIMARY KEY (idpagos), CONSTRAINT fk_pagos_factura1 FOREIGN KEY (f_idfactura) REFERENCES hr.factura (idfactura) ); -- ----------------------------------------------------- -- Table hr.alumno_has_eventos -- ----------------------------------------------------- CREATE TABLE hr.alumno_has_eventos ( a_idalumno INT NOT NULL, e_idevento INT NOT NULL, PRIMARY KEY (a_idalumno, e_idevento), CONSTRAINT fk_alumno_has_eventos_alumno1 FOREIGN KEY (a_idalumno) REFERENCES hr.alumno (idalumno), CONSTRAINT fk_alumno_has_eventos_eventos1 FOREIGN KEY (e_idevento) REFERENCES hr.eventos (idevento) ); -- ----------------------------------------------------- -- Table hr.alumno_has_cursos -- ----------------------------------------------------- CREATE TABLE hr.alumno_has_cursos ( a_idalumno INT NOT NULL, c_idcursos INT NOT NULL, PRIMARY KEY (a_idalumno, c_idcursos), CONSTRAINT fk_alumno_has_cursos_alumno1 FOREIGN KEY (a_idalumno) REFERENCES hr.alumno (idalumno), CONSTRAINT fk_alumno_has_cursos_cursos1 FOREIGN KEY (c_idcursos) REFERENCES hr.cursos (idcursos) ); -- ----------------------------------------------------- -- Table hr.cursos_has_pagos -- ----------------------------------------------------- CREATE TABLE hr.cursos_has_pagos ( c_idcursos INT NOT NULL, p_idpagos INT NOT NULL, promocion VARCHAR(30) NOT NULL, PRIMARY KEY (c_idcursos, p_idpagos), CONSTRAINT fk_cursos_has_pagos_cursos1 FOREIGN KEY (c_idcursos) REFERENCES hr.cursos (idcursos), CONSTRAINT fk_cursos_has_pagos_pagos1 FOREIGN KEY (p_idpagos) REFERENCES hr.pagos (idpagos) ); -- ----------------------------------------------------- -- Table hr.eventos_has_pagos -- ----------------------------------------------------- CREATE TABLE hr.eventos_has_pagos ( e_idevento INT NOT NULL, p_idpagos INT NOT NULL, PRIMARY KEY (e_idevento, p_idpagos), CONSTRAINT fk_eventos_has_pagos_eventos1 FOREIGN KEY (e_idevento) REFERENCES hr.eventos (idevento), CONSTRAINT fk_eventos_has_pagos_pagos1 FOREIGN KEY (p_idpagos) REFERENCES hr.pagos (idpagos) ); -- ----------------------------------------------------- -- Table hr.diploma -- ----------------------------------------------------- CREATE TABLE hr.diploma ( iddiploma INT NOT NULL, nombre VARCHAR(45) NOT NULL, curso VARCHAR(45) NOT NULL, fecha VARCHAR(45) NOT NULL, PRIMARY KEY (iddiploma) ); -- ----------------------------------------------------- -- Table hr.pre-inscripcion -- ----------------------------------------------------- CREATE TABLE hr.preInscripcion ( idpreInscripcion INT NOT NULL, nombre VARCHAR(45) NOT NULL, apellido VARCHAR(45) NOT NULL, telefono VARCHAR(45) NOT NULL, email VARCHAR(45) NOT NULL, e_idEmpresa INT NOT NULL, carrera VARCHAR(45) NULL, confirmar VARCHAR(45) NULL, PRIMARY KEY (idpreInscripcion), CONSTRAINT fk_preInscripcion_empresa1 FOREIGN KEY (e_idEmpresa) REFERENCES hr.empresa (idEmpresa) ); -- ----------------------------------------------------- -- Table hr.alumno_has_diploma -- ----------------------------------------------------- CREATE TABLE hr.alumno_has_diploma ( a_idalumno INT NOT NULL, d_iddiploma INT NOT NULL, PRIMARY KEY (a_idalumno, d_iddiploma), CONSTRAINT fk_alumno_has_diploma_alumno1 FOREIGN KEY (a_idalumno) REFERENCES hr.alumno (idalumno), CONSTRAINT fk_alumno_has_diploma_diploma1 FOREIGN KEY (d_iddiploma) REFERENCES hr.diploma (iddiploma) ); -- ----------------------------------------------------- -- Table hr.pre-inscripcion_has_pagos -- ----------------------------------------------------- CREATE TABLE hr.preInscripcion_has_pagos ( p_idpreInscripcion INT NOT NULL, p_idpagos INT NOT NULL, PRIMARY KEY (p_idpreInscripcion, p_idpagos), CONSTRAINT fk_has_preInscripcion1 FOREIGN KEY (p_idpreInscripcion) REFERENCES hr.preInscripcion (idpreInscripcion), CONSTRAINT fk_has_pagos FOREIGN KEY (p_idpagos) REFERENCES hr.pagos (idpagos) ); -- ----------------------------------------------------- -- Table hr.perfil -- ----------------------------------------------------- CREATE TABLE hr.perfil ( idPerfil INT NOT NULL, perfil VARCHAR(45) NOT NULL, PRIMARY KEY (idPerfil) ); -- ----------------------------------------------------- -- Table hr.usuarios -- ----------------------------------------------------- CREATE TABLE hr.usuarios ( idusuarios INT NOT NULL, idPerfil INT NOT NULL, userName VARCHAR(45) NOT NULL, userPass VARCHAR(45) NOT NULL, PRIMARY KEY (idusuarios), CONSTRAINT fk_usuarios_perfil1 FOREIGN KEY (idPerfil) REFERENCES hr.perfil (idPerfil) );
package org.bitcoins.crypto import org.bitcoin.Secp256k1Context sealed trait CryptoContext object CryptoContext { case object LibSecp256k1 extends CryptoContext case object BouncyCastle extends CryptoContext def default: CryptoContext = { val secpDisabled = System.getenv("DISABLE_SECP256K1") if ( secpDisabled != null && (secpDisabled.toLowerCase == "true" || secpDisabled == "1") ) { BouncyCastle } else { if (Secp256k1Context.isEnabled) { LibSecp256k1 } else { BouncyCastle } } } }
package example object SquareShaderSource extends ShaderSource { val vertexShader: String = """ attribute vec4 aVertexPosition; attribute vec4 aVertexColour; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; varying lowp vec4 vColour; void main() { gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition; vColour = aVertexColour; } """ val fragmentShader: String = """ varying lowp vec4 vColour; void main(void) { gl_FragColor = vColour; } """ }
package com.easykotlin.learn.study1 /** * 常量 */ object SdkConst { const val ERROR_CODE_1 = 10086 const val ERROR_CODE_2 = 10087 const val ERROR_CODE_3 = 10088 const val ERROR_CODE_4 = -1000 }
import qualified Data.Set as S import Control.Applicative ((<$>), Applicative(..), Alternative((<|>))) import Data.Char (isDigit) import Data.Functor (($>)) import Text.ParserCombinators.ReadP data State = On | Off deriving (Show, Eq) data Instruction = Instruction State (Int, Int) (Int, Int) (Int, Int) deriving (Show, Eq) parseInstruction = (string "on" $> On) <|> (string "off" $> Off) parseInt :: ReadP Int parseInt = do sign <- option '0' (char '-') digits <- many (satisfy isDigit) return $ read $ sign : digits parseRange = do start <- parseInt string ".." end <- parseInt return (start, end) parseLine = do onOff <- parseInstruction string " x=" xrange <- parseRange string ",y=" yrange <- parseRange string ",z=" zrange <- parseRange return $ Instruction onOff xrange yrange zrange runParser p = fst . head . filter (null . snd) . readP_to_S p evaluateInstruction active (Instruction st (xl, xh) (yl, yh) (zl, zh)) = case st of On -> S.union active fs Off -> S.difference active fs where cap n | n > 50 = 51 | n < -50 = -51 | otherwise = n inRange n = n <= 50 && n >= -50 fs = S.fromList [ (x, y, z) | x <- [ cap xl .. cap xh ] , y <- [ cap yl .. cap yh ] , z <- [ cap zl .. cap zh ] , all inRange [x,y,z] ] main :: IO () main = do instructions <- fmap (map (runParser parseLine) . lines) getContents print $ S.size $ foldl evaluateInstruction S.empty instructions
package com.github.datalking.common.convert.editor; import java.beans.PropertyEditorSupport; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Map; import java.util.Properties; /** */ public class PropertiesEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { Properties props = new Properties(); if (text != null) { try { // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. props.load(new ByteArrayInputStream(text.getBytes("ISO-8859-1"))); } catch (IOException ex) { // Should never happen. throw new IllegalArgumentException( "Failed to parse [" + text + "] into Properties", ex); } } setValue(props); } @Override public void setValue(Object value) { if (!(value instanceof Properties) && value instanceof Map) { Properties props = new Properties(); props.putAll((Map) value); super.setValue(props); } else { super.setValue(value); } } }