text stringlengths 1 1.05M |
|---|
'use strict';
var orm = require('../index'),
should = require('should');
describe('orm', function () {
it('exports an object', function () {
should.exist(orm);
});
describe('errors', function () {
it('empty collections and connections', function () {
var options = {};
options.adapters = options.connections = options.collections = {};
orm(options, function (err, models) {
models.collections.should.be.empty;
models.connections.should.be.empty;
});
});
});
describe('models', function () {
it('get collections and connections', function () {
var options = {
adapters: {
'sails-disk': require('sails-disk')
},
connections: {
localDiskDb: {
adapter: 'sails-disk'
},
},
collections: {
Help: {
migrate: 'safe',
connection: 'localDiskDb',
attributes: {
provider: {
type: 'alphanumericdashed'
},
identifier: {
type: 'string'
}
}
}
}
};
orm(options, function (err, models) {
models.collections.should.not.be.empty;
models.connections.should.not.be.empty;
});
});
});
});
|
<filename>src/views/Overview/Container.js
import { connect } from 'react-redux';
import Component from './Component';
const mapStateToProps = (state) => ({
assets: state.assets,
});
export default connect(
mapStateToProps,
)(Component);
|
<filename>finalProject/src/main/java/co/finalproject/farm/app/myPage/controller/OrderController.java
package co.finalproject.farm.app.myPage.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import co.finalproject.farm.app.shop.service.OrderVO;
import co.finalproject.farm.common.Paging;
import oracle.jdbc.proxy.annotation.Post;
import co.finalproject.farm.app.myPage.service.impl.OrderMapper;
@Controller
public class OrderController {
@Autowired OrderMapper orderMapper;
Logger logger = LoggerFactory.getLogger(OrderController.class);
//구매내역 뷰페이시 이동
@RequestMapping("/getOrderList")
public String getOrderList(OrderVO vo){
return "mypageTiles/mypage/getOrderList";
}
//리스트 조회
@RequestMapping("/ajaxgetOrderList")
@ResponseBody
public List<OrderVO> getOrderlist(OrderVO vo){
return orderMapper.getOrderList(vo);
}
//상세내역 뷰페이지 이동
@RequestMapping("/getOrder")
public String getOrder(Model model, @RequestParam String order_no ) {
model.addAttribute("order_no", order_no);
return "notiles/mypage/getOrder";
}
// 주문상세내역 조회
@RequestMapping("/ajaxgetOrder")
@ResponseBody
public List<OrderVO> getOrder(OrderVO vo){
return orderMapper.getOrder(vo);
}
//판매내역 뷰페이지 이동
@RequestMapping("/getSaleList")
public String getSaleList() {
return "mypageTiles/mypage/getSaleList";
}
//판매내역조회
@RequestMapping("/ajaxgetSaleList")
@ResponseBody
public List<OrderVO> getSaleList(OrderVO vo){
return orderMapper.getSaleList(vo);
}
//수정 - 송장번호, 주문상태
//수정폼
@RequestMapping("/updateOrder")
public String updateOrder(OrderVO vo) {
return "notiles/mypage/updateOrder";
}
@PostMapping("/updateOrder")
public String updateOrderProc(OrderVO vo) {
orderMapper.updateOrder(vo);
return "redirect:getSaleList";
}
}
|
from typing import Dict, Union
from datetime import datetime
def process_data(data: Dict[str, Union[datetime, str]]) -> Dict[str, Union[datetime, str]]:
processed_data = {}
for key, value in data.items():
if isinstance(value, str):
try:
processed_data[key] = datetime.strptime(value, "%Y-%m-%d")
except ValueError:
processed_data[key] = value # If the string is not a valid date, keep it as is
else:
processed_data[key] = value # If the value is already a datetime object, keep it as is
return processed_data |
import {
TextComponent,
} from "./text-component";
/**
* Signature/interface for an `Illustrator` object
* @see https://developer.apple.com/documentation/apple_news/illustrator
* @extends {TextComponent}
*/
export interface Illustrator extends TextComponent {
role: "illustrator";
}
|
#!/usr/bin/env bash
# import, install only if not existed
source bash-base 2>/dev/null || npm i -g @renault-digital/bash-base && source bash-base
# customize the short description of default help usage
SHORT_DESC='an example shell script to show how to use bash-base '
print_header "collect information"
args_parse $# "$@" firstName lastName age sex country
args_valid_or_read firstName '^[A-Za-z ]{2,}$' "Your first name (only letters)"
args_valid_or_read lastName '^[A-Za-z ]{2,}$' "Your last name (only letters)"
args_valid_or_read age '^[0-9]{1,2}$' "Your age (maxim 2 digits))"
args_valid_or_select_pipe sex 'man|woman' "Your sex"
response=$(curl -sS 'https://restcountries.eu/rest/v2/regionalbloc/eu' --compressed)
string_pick_to_array '{"name":"' '","topLevelDomain' countryNames "$response"
args_valid_or_select country countryNames "Which country"
confirm_to_continue firstName lastName age sex country
print_header "say hello"
cat <<-EOF
Hello $(string_upper_first "$firstName") $(string_upper "$lastName"),
nice to meet you.
EOF
# you can run this script with -h to get the help usage
# ./example-npm.sh -h
|
#!/usr/bin/env bash
# Guide:
# This script supports distributed inference on multi-gpu workers (as well as single-worker inference).
# Please set the options below according to the comments.
# For multi-gpu workers inference, these options should be manually set for each worker.
# After setting the options, please run the script on each worker.
# Number of GPUs per GPU worker
GPUS_PER_NODE=8
# Number of GPU workers, for single-worker inference, please set to 1
WORKER_CNT=4
# The ip address of the rank-0 worker, for single-worker inference, please set to localhost
export MASTER_ADDR=XX.XX.XX.XX
# The port for communication
export MASTER_PORT=8316
# The rank of this worker, should be in {0, ..., WORKER_CNT-1}, for single-worker inference, please set to 0
export RANK=0
user_dir=../../ofa_module
bpe_dir=../../utils/BPE
# val or test
split=$1
data=../../dataset/vqa_data/vqa_${split}.tsv
ans2label_file=../../dataset/vqa_data/trainval_ans2label.pkl
path=../../checkpoints/vqa_base_best.pt
result_path=../../results/vqa_${split}_allcand
selected_cols=0,5,2,3,4
python3 -m torch.distributed.launch --nproc_per_node=${GPUS_PER_NODE} --nnodes=${WORKER_CNT} --node_rank=${RANK} --master_addr=${MASTER_ADDR} --master_port=${MASTER_PORT} ../../evaluate.py \
${data} \
--path=${path} \
--user-dir=${user_dir} \
--task=vqa_gen \
--batch-size=4 \
--valid-batch-size=20 \
--log-format=simple --log-interval=10 \
--seed=7 \
--gen-subset=${split} \
--results-path=${result_path} \
--fp16 \
--ema-eval \
--num-workers=0 \
--model-overrides="{\"data\":\"${data}\",\"bpe_dir\":\"${bpe_dir}\",\"selected_cols\":\"${selected_cols}\",\"ans2label_file\":\"${ans2label_file}\"}" |
<reponame>grsantos13/orange-talents-01-template-proposta
package br.com.zup.propostas.proposta;
import br.com.zup.propostas.compartilhado.validacao.CPFouCNPJ.CPFouCNPJ;
import br.com.zup.propostas.proposta.endereco.Endereco;
import br.com.zup.propostas.proposta.endereco.EnderecoRequest;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.math.BigDecimal;
public class NovaPropostaRequest {
@NotBlank
private String nome;
@Email
@NotBlank
private String email;
@CPFouCNPJ
@NotBlank
private String documento;
@NotNull
private EnderecoRequest endereco;
@NotNull
@Positive
private BigDecimal salario;
public NovaPropostaRequest(@NotBlank String nome,
@Email @NotBlank String email,
@NotBlank String documento,
@NotNull EnderecoRequest endereco,
@NotNull @Positive BigDecimal salario) {
this.nome = nome;
this.email = email;
this.documento = documento;
this.endereco = endereco;
this.salario = salario;
}
public String getNome() {
return nome;
}
public String getEmail() {
return email;
}
public String getDocumento() {
return documento;
}
public EnderecoRequest getEndereco() {
return endereco;
}
public BigDecimal getSalario() {
return salario;
}
public String documentoOfuscado(){
return this.documento.substring(this.documento.length() - 5);
}
public Proposta toModel() {
return new Proposta(nome, email, documento, new Endereco(this.endereco), salario);
}
}
|
/**
* 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 kafka.log
import java.io.{File, IOException}
import java.nio.file.{Files, NoSuchFileException}
import kafka.common.LogSegmentOffsetOverflowException
import kafka.log.UnifiedLog.{CleanedFileSuffix, DeletedFileSuffix, SwapFileSuffix, isIndexFile, isLogFile, offsetFromFile}
import kafka.server.{LogDirFailureChannel, LogOffsetMetadata}
import kafka.server.epoch.LeaderEpochFileCache
import kafka.utils.{CoreUtils, Logging, Scheduler}
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.errors.InvalidOffsetException
import org.apache.kafka.common.utils.Time
import scala.collection.{Set, mutable}
case class LoadedLogOffsets(logStartOffset: Long,
recoveryPoint: Long,
nextOffsetMetadata: LogOffsetMetadata)
/**
* @param dir The directory from which log segments need to be loaded
* @param topicPartition The topic partition associated with the log being loaded
* @param config The configuration settings for the log being loaded
* @param scheduler The thread pool scheduler used for background actions
* @param time The time instance used for checking the clock
* @param logDirFailureChannel The LogDirFailureChannel instance to asynchronously handle log
* directory failure
* @param hadCleanShutdown Boolean flag to indicate whether the associated log previously had a
* clean shutdown
* @param segments The LogSegments instance into which segments recovered from disk will be
* populated
* @param logStartOffsetCheckpoint The checkpoint of the log start offset
* @param recoveryPointCheckpoint The checkpoint of the offset at which to begin the recovery
* @param maxProducerIdExpirationMs The maximum amount of time to wait before a producer id is
* considered expired
* @param leaderEpochCache An optional LeaderEpochFileCache instance to be updated during recovery
* @param producerStateManager The ProducerStateManager instance to be updated during recovery
*/
case class LoadLogParams(dir: File,
topicPartition: TopicPartition,
config: LogConfig,
scheduler: Scheduler,
time: Time,
logDirFailureChannel: LogDirFailureChannel,
hadCleanShutdown: Boolean,
segments: LogSegments,
logStartOffsetCheckpoint: Long,
recoveryPointCheckpoint: Long,
maxProducerIdExpirationMs: Int,
leaderEpochCache: Option[LeaderEpochFileCache],
producerStateManager: ProducerStateManager) {
val logIdentifier: String = s"[LogLoader partition=$topicPartition, dir=${dir.getParent}] "
}
/**
* This object is responsible for all activities related with recovery of log segments from disk.
*/
object LogLoader extends Logging {
/**
* Clean shutdown file that indicates the broker was cleanly shutdown in 0.8 and higher.
* This is used to avoid unnecessary recovery after a clean shutdown. In theory this could be
* avoided by passing in the recovery point, however finding the correct position to do this
* requires accessing the offset index which may not be safe in an unclean shutdown.
* For more information see the discussion in PR#2104
*/
val CleanShutdownFile = ".kafka_cleanshutdown"
/**
* Load the log segments from the log files on disk, and returns the components of the loaded log.
* Additionally, it also suitably updates the provided LeaderEpochFileCache and ProducerStateManager
* to reflect the contents of the loaded log.
*
* In the context of the calling thread, this function does not need to convert IOException to
* KafkaStorageException because it is only called before all logs are loaded.
*
* @param params The parameters for the log being loaded from disk
*
* @return the offsets of the Log successfully loaded from disk
*
* @throws LogSegmentOffsetOverflowException if we encounter a .swap file with messages that
* overflow index offset
*/
def load(params: LoadLogParams): LoadedLogOffsets = {
// First pass: through the files in the log directory and remove any temporary files
// and find any interrupted swap operations
val swapFiles = removeTempFilesAndCollectSwapFiles(params)
// The remaining valid swap files must come from compaction or segment split operation. We can
// simply rename them to regular segment files. But, before renaming, we should figure out which
// segments are compacted/split and delete these segment files: this is done by calculating
// min/maxSwapFileOffset.
// We store segments that require renaming in this code block, and do the actual renaming later.
var minSwapFileOffset = Long.MaxValue
var maxSwapFileOffset = Long.MinValue
swapFiles.filter(f => UnifiedLog.isLogFile(new File(CoreUtils.replaceSuffix(f.getPath, SwapFileSuffix, "")))).foreach { f =>
val baseOffset = offsetFromFile(f)
val segment = LogSegment.open(f.getParentFile,
baseOffset = baseOffset,
params.config,
time = params.time,
fileSuffix = UnifiedLog.SwapFileSuffix)
info(s"${params.logIdentifier}Found log file ${f.getPath} from interrupted swap operation, which is recoverable from ${UnifiedLog.SwapFileSuffix} files by renaming.")
minSwapFileOffset = Math.min(segment.baseOffset, minSwapFileOffset)
maxSwapFileOffset = Math.max(segment.readNextOffset, maxSwapFileOffset)
}
// Second pass: delete segments that are between minSwapFileOffset and maxSwapFileOffset. As
// discussed above, these segments were compacted or split but haven't been renamed to .delete
// before shutting down the broker.
for (file <- params.dir.listFiles if file.isFile) {
try {
if (!file.getName.endsWith(SwapFileSuffix)) {
val offset = offsetFromFile(file)
if (offset >= minSwapFileOffset && offset < maxSwapFileOffset) {
info(s"${params.logIdentifier}Deleting segment files ${file.getName} that is compacted but has not been deleted yet.")
file.delete()
}
}
} catch {
// offsetFromFile with files that do not include an offset in the file name
case _: StringIndexOutOfBoundsException =>
case _: NumberFormatException =>
}
}
// Third pass: rename all swap files.
for (file <- params.dir.listFiles if file.isFile) {
if (file.getName.endsWith(SwapFileSuffix)) {
info(s"${params.logIdentifier}Recovering file ${file.getName} by renaming from ${UnifiedLog.SwapFileSuffix} files.")
file.renameTo(new File(CoreUtils.replaceSuffix(file.getPath, UnifiedLog.SwapFileSuffix, "")))
}
}
// Fourth pass: load all the log and index files.
// We might encounter legacy log segments with offset overflow (KAFKA-6264). We need to split such segments. When
// this happens, restart loading segment files from scratch.
retryOnOffsetOverflow(params, {
// In case we encounter a segment with offset overflow, the retry logic will split it after which we need to retry
// loading of segments. In that case, we also need to close all segments that could have been left open in previous
// call to loadSegmentFiles().
params.segments.close()
params.segments.clear()
loadSegmentFiles(params)
})
val (newRecoveryPoint: Long, nextOffset: Long) = {
if (!params.dir.getAbsolutePath.endsWith(UnifiedLog.DeleteDirSuffix)) {
val (newRecoveryPoint, nextOffset) = retryOnOffsetOverflow(params, {
recoverLog(params)
})
// reset the index size of the currently active log segment to allow more entries
params.segments.lastSegment.get.resizeIndexes(params.config.maxIndexSize)
(newRecoveryPoint, nextOffset)
} else {
if (params.segments.isEmpty) {
params.segments.add(
LogSegment.open(
dir = params.dir,
baseOffset = 0,
params.config,
time = params.time,
initFileSize = params.config.initFileSize))
}
(0L, 0L)
}
}
params.leaderEpochCache.foreach(_.truncateFromEnd(nextOffset))
val newLogStartOffset = math.max(params.logStartOffsetCheckpoint, params.segments.firstSegment.get.baseOffset)
// The earliest leader epoch may not be flushed during a hard failure. Recover it here.
params.leaderEpochCache.foreach(_.truncateFromStart(params.logStartOffsetCheckpoint))
// Any segment loading or recovery code must not use producerStateManager, so that we can build the full state here
// from scratch.
if (!params.producerStateManager.isEmpty)
throw new IllegalStateException("Producer state must be empty during log initialization")
// Reload all snapshots into the ProducerStateManager cache, the intermediate ProducerStateManager used
// during log recovery may have deleted some files without the LogLoader.producerStateManager instance witnessing the
// deletion.
params.producerStateManager.removeStraySnapshots(params.segments.baseOffsets.toSeq)
UnifiedLog.rebuildProducerState(
params.producerStateManager,
params.segments,
newLogStartOffset,
nextOffset,
params.config.recordVersion,
params.time,
reloadFromCleanShutdown = params.hadCleanShutdown,
params.logIdentifier)
val activeSegment = params.segments.lastSegment.get
LoadedLogOffsets(
newLogStartOffset,
newRecoveryPoint,
LogOffsetMetadata(nextOffset, activeSegment.baseOffset, activeSegment.size))
}
/**
* Removes any temporary files found in log directory, and creates a list of all .swap files which could be swapped
* in place of existing segment(s). For log splitting, we know that any .swap file whose base offset is higher than
* the smallest offset .clean file could be part of an incomplete split operation. Such .swap files are also deleted
* by this method.
*
* @param params The parameters for the log being loaded from disk
* @return Set of .swap files that are valid to be swapped in as segment files and index files
*/
private def removeTempFilesAndCollectSwapFiles(params: LoadLogParams): Set[File] = {
val swapFiles = mutable.Set[File]()
val cleanedFiles = mutable.Set[File]()
var minCleanedFileOffset = Long.MaxValue
for (file <- params.dir.listFiles if file.isFile) {
if (!file.canRead)
throw new IOException(s"Could not read file $file")
val filename = file.getName
if (filename.endsWith(DeletedFileSuffix)) {
debug(s"${params.logIdentifier}Deleting stray temporary file ${file.getAbsolutePath}")
Files.deleteIfExists(file.toPath)
} else if (filename.endsWith(CleanedFileSuffix)) {
minCleanedFileOffset = Math.min(offsetFromFile(file), minCleanedFileOffset)
cleanedFiles += file
} else if (filename.endsWith(SwapFileSuffix)) {
swapFiles += file
}
}
// KAFKA-6264: Delete all .swap files whose base offset is greater than the minimum .cleaned segment offset. Such .swap
// files could be part of an incomplete split operation that could not complete. See Log#splitOverflowedSegment
// for more details about the split operation.
val (invalidSwapFiles, validSwapFiles) = swapFiles.partition(file => offsetFromFile(file) >= minCleanedFileOffset)
invalidSwapFiles.foreach { file =>
debug(s"${params.logIdentifier}Deleting invalid swap file ${file.getAbsoluteFile} minCleanedFileOffset: $minCleanedFileOffset")
Files.deleteIfExists(file.toPath)
}
// Now that we have deleted all .swap files that constitute an incomplete split operation, let's delete all .clean files
cleanedFiles.foreach { file =>
debug(s"${params.logIdentifier}Deleting stray .clean file ${file.getAbsolutePath}")
Files.deleteIfExists(file.toPath)
}
validSwapFiles
}
/**
* Retries the provided function only whenever an LogSegmentOffsetOverflowException is raised by
* it during execution. Before every retry, the overflowed segment is split into one or more segments
* such that there is no offset overflow in any of them.
*
* @param params The parameters for the log being loaded from disk
* @param fn The function to be executed
* @return The value returned by the function, if successful
* @throws Exception whenever the executed function throws any exception other than
* LogSegmentOffsetOverflowException, the same exception is raised to the caller
*/
private def retryOnOffsetOverflow[T](params: LoadLogParams, fn: => T): T = {
while (true) {
try {
return fn
} catch {
case e: LogSegmentOffsetOverflowException =>
info(s"${params.logIdentifier}Caught segment overflow error: ${e.getMessage}. Split segment and retry.")
val result = UnifiedLog.splitOverflowedSegment(
e.segment,
params.segments,
params.dir,
params.topicPartition,
params.config,
params.scheduler,
params.logDirFailureChannel,
params.logIdentifier)
deleteProducerSnapshotsAsync(result.deletedSegments, params)
}
}
throw new IllegalStateException()
}
/**
* Loads segments from disk into the provided params.segments.
*
* This method does not need to convert IOException to KafkaStorageException because it is only called before all logs are loaded.
* It is possible that we encounter a segment with index offset overflow in which case the LogSegmentOffsetOverflowException
* will be thrown. Note that any segments that were opened before we encountered the exception will remain open and the
* caller is responsible for closing them appropriately, if needed.
*
* @param params The parameters for the log being loaded from disk
* @throws LogSegmentOffsetOverflowException if the log directory contains a segment with messages that overflow the index offset
*/
private def loadSegmentFiles(params: LoadLogParams): Unit = {
// load segments in ascending order because transactional data from one segment may depend on the
// segments that come before it
for (file <- params.dir.listFiles.sortBy(_.getName) if file.isFile) {
if (isIndexFile(file)) {
// if it is an index file, make sure it has a corresponding .log file
val offset = offsetFromFile(file)
val logFile = UnifiedLog.logFile(params.dir, offset)
if (!logFile.exists) {
warn(s"${params.logIdentifier}Found an orphaned index file ${file.getAbsolutePath}, with no corresponding log file.")
Files.deleteIfExists(file.toPath)
}
} else if (isLogFile(file)) {
// if it's a log file, load the corresponding log segment
val baseOffset = offsetFromFile(file)
val timeIndexFileNewlyCreated = !UnifiedLog.timeIndexFile(params.dir, baseOffset).exists()
val segment = LogSegment.open(
dir = params.dir,
baseOffset = baseOffset,
params.config,
time = params.time,
fileAlreadyExists = true)
try segment.sanityCheck(timeIndexFileNewlyCreated)
catch {
case _: NoSuchFileException =>
error(s"${params.logIdentifier}Could not find offset index file corresponding to log file" +
s" ${segment.log.file.getAbsolutePath}, recovering segment and rebuilding index files...")
recoverSegment(segment, params)
case e: CorruptIndexException =>
warn(s"${params.logIdentifier}Found a corrupted index file corresponding to log file" +
s" ${segment.log.file.getAbsolutePath} due to ${e.getMessage}}, recovering segment and" +
" rebuilding index files...")
recoverSegment(segment, params)
}
params.segments.add(segment)
}
}
}
/**
* Just recovers the given segment, without adding it to the provided params.segments.
*
* @param segment Segment to recover
* @param params The parameters for the log being loaded from disk
*
* @return The number of bytes truncated from the segment
*
* @throws LogSegmentOffsetOverflowException if the segment contains messages that cause index offset overflow
*/
private def recoverSegment(segment: LogSegment, params: LoadLogParams): Int = {
val producerStateManager = new ProducerStateManager(
params.topicPartition,
params.dir,
params.maxProducerIdExpirationMs,
params.time)
UnifiedLog.rebuildProducerState(
producerStateManager,
params.segments,
params.logStartOffsetCheckpoint,
segment.baseOffset,
params.config.recordVersion,
params.time,
reloadFromCleanShutdown = false,
params.logIdentifier)
val bytesTruncated = segment.recover(producerStateManager, params.leaderEpochCache)
// once we have recovered the segment's data, take a snapshot to ensure that we won't
// need to reload the same segment again while recovering another segment.
producerStateManager.takeSnapshot()
bytesTruncated
}
/**
* Recover the log segments (if there was an unclean shutdown). Ensures there is at least one
* active segment, and returns the updated recovery point and next offset after recovery. Along
* the way, the method suitably updates the LeaderEpochFileCache or ProducerStateManager inside
* the provided LogComponents.
*
* This method does not need to convert IOException to KafkaStorageException because it is only
* called before all logs are loaded.
*
* @param params The parameters for the log being loaded from disk
*
* @return a tuple containing (newRecoveryPoint, nextOffset).
*
* @throws LogSegmentOffsetOverflowException if we encountered a legacy segment with offset overflow
*/
private[log] def recoverLog(params: LoadLogParams): (Long, Long) = {
/** return the log end offset if valid */
def deleteSegmentsIfLogStartGreaterThanLogEnd(): Option[Long] = {
if (params.segments.nonEmpty) {
val logEndOffset = params.segments.lastSegment.get.readNextOffset
if (logEndOffset >= params.logStartOffsetCheckpoint)
Some(logEndOffset)
else {
warn(s"${params.logIdentifier}Deleting all segments because logEndOffset ($logEndOffset) " +
s"is smaller than logStartOffset ${params.logStartOffsetCheckpoint}. " +
"This could happen if segment files were deleted from the file system.")
removeAndDeleteSegmentsAsync(params.segments.values, params)
params.leaderEpochCache.foreach(_.clearAndFlush())
params.producerStateManager.truncateFullyAndStartAt(params.logStartOffsetCheckpoint)
None
}
} else None
}
// If we have the clean shutdown marker, skip recovery.
if (!params.hadCleanShutdown) {
val unflushed = params.segments.values(params.recoveryPointCheckpoint, Long.MaxValue).iterator
var truncated = false
while (unflushed.hasNext && !truncated) {
val segment = unflushed.next()
info(s"${params.logIdentifier}Recovering unflushed segment ${segment.baseOffset}")
val truncatedBytes =
try {
recoverSegment(segment, params)
} catch {
case _: InvalidOffsetException =>
val startOffset = segment.baseOffset
warn(s"${params.logIdentifier}Found invalid offset during recovery. Deleting the" +
s" corrupt segment and creating an empty one with starting offset $startOffset")
segment.truncateTo(startOffset)
}
if (truncatedBytes > 0) {
// we had an invalid message, delete all remaining log
warn(s"${params.logIdentifier}Corruption found in segment ${segment.baseOffset}," +
s" truncating to offset ${segment.readNextOffset}")
removeAndDeleteSegmentsAsync(unflushed.toList, params)
truncated = true
}
}
}
val logEndOffsetOption = deleteSegmentsIfLogStartGreaterThanLogEnd()
if (params.segments.isEmpty) {
// no existing segments, create a new mutable segment beginning at logStartOffset
params.segments.add(
LogSegment.open(
dir = params.dir,
baseOffset = params.logStartOffsetCheckpoint,
params.config,
time = params.time,
initFileSize = params.config.initFileSize,
preallocate = params.config.preallocate))
}
// Update the recovery point if there was a clean shutdown and did not perform any changes to
// the segment. Otherwise, we just ensure that the recovery point is not ahead of the log end
// offset. To ensure correctness and to make it easier to reason about, it's best to only advance
// the recovery point when the log is flushed. If we advanced the recovery point here, we could
// skip recovery for unflushed segments if the broker crashed after we checkpoint the recovery
// point and before we flush the segment.
(params.hadCleanShutdown, logEndOffsetOption) match {
case (true, Some(logEndOffset)) =>
(logEndOffset, logEndOffset)
case _ =>
val logEndOffset = logEndOffsetOption.getOrElse(params.segments.lastSegment.get.readNextOffset)
(Math.min(params.recoveryPointCheckpoint, logEndOffset), logEndOffset)
}
}
/**
* This method deletes the given log segments and the associated producer snapshots, by doing the
* following for each of them:
* - It removes the segment from the segment map so that it will no longer be used for reads.
* - It schedules asynchronous deletion of the segments that allows reads to happen concurrently without
* synchronization and without the possibility of physically deleting a file while it is being
* read.
*
* This method does not need to convert IOException to KafkaStorageException because it is either
* called before all logs are loaded or the immediate caller will catch and handle IOException
*
* @param segmentsToDelete The log segments to schedule for deletion
* @param params The parameters for the log being loaded from disk
*/
private def removeAndDeleteSegmentsAsync(segmentsToDelete: Iterable[LogSegment],
params: LoadLogParams): Unit = {
if (segmentsToDelete.nonEmpty) {
// Most callers hold an iterator into the `params.segments` collection and
// `removeAndDeleteSegmentAsync` mutates it by removing the deleted segment. Therefore,
// we should force materialization of the iterator here, so that results of the iteration
// remain valid and deterministic. We should also pass only the materialized view of the
// iterator to the logic that deletes the segments.
val toDelete = segmentsToDelete.toList
info(s"${params.logIdentifier}Deleting segments as part of log recovery: ${toDelete.mkString(",")}")
toDelete.foreach { segment =>
params.segments.remove(segment.baseOffset)
}
UnifiedLog.deleteSegmentFiles(
toDelete,
asyncDelete = true,
params.dir,
params.topicPartition,
params.config,
params.scheduler,
params.logDirFailureChannel,
params.logIdentifier)
deleteProducerSnapshotsAsync(segmentsToDelete, params)
}
}
private def deleteProducerSnapshotsAsync(segments: Iterable[LogSegment],
params: LoadLogParams): Unit = {
UnifiedLog.deleteProducerSnapshots(segments,
params.producerStateManager,
asyncDelete = true,
params.scheduler,
params.config,
params.logDirFailureChannel,
params.dir.getParent,
params.topicPartition)
}
}
|
#!/bin/bash
for i in `seq 1 500000`
do
echo "fn func$i of x is x + x - x * x / x; end"
echo "func$i($i);"
done
|
<reponame>hafizalfaza/rrssrbp
import { CHECK_AUTH } from '../actions/constants';
const authInitialState = {
isLoggedIn: false
}
export default (state=authInitialState, action) => {
switch(action.type){
case CHECK_AUTH:
return {
...state,
isLoggedIn: action.payload
}
default:
return state
}
} |
#!/usr/bin/env bash
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
cd $SCRIPTPATH
cd ../../../
. config.profile
# check the enviroment info
nvidia-smi
export PYTHONPATH="$PWD":$PYTHONPATH
DATA_DIR="${DATA_ROOT}/cityscapes"
SAVE_DIR="${DATA_ROOT}/seg_result/cityscapes/"
BACKBONE="hrnet48"
CONFIGS="configs/cityscapes/H_48_D_4.json"
CONFIGS_TEST="configs/cityscapes/H_48_D_4_TEST.json"
MODEL_NAME="hrnet_w48_ocr"
LOSS_TYPE="fs_auxohemce_loss"
CHECKPOINTS_NAME="${MODEL_NAME}_paddle_ohem_lr2x_$(date +%F_%H-%M-%S)"
LOG_FILE="./log/cityscapes/${CHECKPOINTS_NAME}.log"
echo "Logging to $LOG_FILE"
mkdir -p `dirname $LOG_FILE`
PRETRAINED_MODEL="./pretrained_model/HRNet_W48_C_ssld_pretrained.pth"
MAX_ITERS=40000
BASE_LR=0.02
if [ "$1"x == "train"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} \
--drop_last y \
--phase train \
--gathered n \
--loss_balance y \
--log_to_file n \
--backbone ${BACKBONE} \
--model_name ${MODEL_NAME} \
--gpu 0 1 2 3 4 5 6 7 \
--data_dir ${DATA_DIR} \
--loss_type ${LOSS_TYPE} \
--max_iters ${MAX_ITERS} \
--checkpoints_name ${CHECKPOINTS_NAME} \
--pretrained ${PRETRAINED_MODEL} \
--distributed \
--base_lr ${BASE_LR} \
2>&1 | tee ${LOG_FILE}
elif [ "$1"x == "resume"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} \
--drop_last y \
--phase train \
--gathered n \
--loss_balance y \
--log_to_file n \
--backbone ${BACKBONE} \
--model_name ${MODEL_NAME} \
--max_iters ${MAX_ITERS} \
--data_dir ${DATA_DIR} \
--loss_type ${LOSS_TYPE} \
--gpu 0 1 2 3 \
--resume_continue y \
--resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--checkpoints_name ${CHECKPOINTS_NAME} \
2>&1 | tee -a ${LOG_FILE}
elif [ "$1"x == "val"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} --drop_last y \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --checkpoints_name ${CHECKPOINTS_NAME} \
--phase test --gpu 0 1 2 3 --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--loss_type ${LOSS_TYPE} --test_dir ${DATA_DIR}/val/image \
--out_dir ${SAVE_DIR}${CHECKPOINTS_NAME}_val
cd lib/metrics
${PYTHON} -u cityscapes_evaluator.py --pred_dir ${SAVE_DIR}${CHECKPOINTS_NAME}_val/label \
--gt_dir ${DATA_DIR}/val/label
elif [ "$1"x == "segfix"x ]; then
if [ "$3"x == "test"x ]; then
DIR=${SAVE_DIR}${CHECKPOINTS_NAME}_test_ss/label
echo "Applying SegFix for $DIR"
${PYTHON} scripts/cityscapes/segfix.py \
--input $DIR \
--split test \
--offset ${DATA_ROOT}/cityscapes/test_offset/semantic/offset_hrnext/
elif [ "$3"x == "val"x ]; then
DIR=${SAVE_DIR}${CHECKPOINTS_NAME}_val/label
echo "Applying SegFix for $DIR"
${PYTHON} scripts/cityscapes/segfix.py \
--input $DIR \
--split val \
--offset ${DATA_ROOT}/cityscapes/val/offset_pred/semantic/offset_hrnext/
fi
elif [ "$1"x == "test"x ]; then
if [ "$3"x == "ss"x ]; then
echo "[single scale] test"
${PYTHON} -u main.py --configs ${CONFIGS} --drop_last y \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --checkpoints_name ${CHECKPOINTS_NAME} \
--phase test --gpu 0 1 2 3 --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--test_dir ${DATA_DIR}/test --log_to_file n \
--out_dir ${SAVE_DIR}${CHECKPOINTS_NAME}_test_ss
else
echo "[multiple scale + flip] test"
${PYTHON} -u main.py --configs ${CONFIGS_TEST} --drop_last y \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --checkpoints_name ${CHECKPOINTS_NAME} \
--phase test --gpu 0 1 2 3 --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--test_dir ${DATA_DIR}/test --log_to_file n \
--out_dir ${SAVE_DIR}${CHECKPOINTS_NAME}_test_ms
fi
else
echo "$1"x" is invalid..."
fi |
alpine_url=http://dl-cdn.alpinelinux.org/alpine/v3.9
uboot_tar=alpine-uboot-3.9.0-armv7.tar.gz
uboot_url=$alpine_url/releases/armv7/$uboot_tar
tools_tar=apk-tools-static-2.10.3-r1.apk
tools_url=$alpine_url/main/armv7/$tools_tar
firmware_tar=linux-firmware-other-20190322-r0.apk
firmware_url=$alpine_url/main/armv7/$firmware_tar
linux_dir=tmp/linux-4.19
linux_ver=4.19.84-xilinx
modules_dir=alpine-modloop/lib/modules/$linux_ver
passwd=changeme
test -f $uboot_tar || curl -L $uboot_url -o $uboot_tar
test -f $tools_tar || curl -L $tools_url -o $tools_tar
test -f $firmware_tar || curl -L $firmware_url -o $firmware_tar
for tar in linux-firmware-ath9k_htc-20190322-r0.apk linux-firmware-brcm-20190322-r0.apk linux-firmware-rtlwifi-20190322-r0.apk
do
url=$alpine_url/main/armv7/$tar
test -f $tar || curl -L $url -o $tar
done
mkdir alpine-uboot
tar -zxf $uboot_tar --directory=alpine-uboot
mkdir alpine-apk
tar -zxf $tools_tar --directory=alpine-apk --warning=no-unknown-keyword
mkdir alpine-initramfs
cd alpine-initramfs
gzip -dc ../alpine-uboot/boot/initramfs-vanilla | cpio -id
rm -rf etc/modprobe.d
rm -rf lib/firmware
rm -rf lib/modules
rm -rf var
find . | sort | cpio --quiet -o -H newc | gzip -9 > ../initrd.gz
cd ..
mkimage -A arm -T ramdisk -C gzip -d initrd.gz uInitrd
mkdir -p $modules_dir/kernel
find $linux_dir -name \*.ko -printf '%P\0' | tar --directory=$linux_dir --owner=0 --group=0 --null --files-from=- -zcf - | tar -zxf - --directory=$modules_dir/kernel
cp $linux_dir/modules.order $linux_dir/modules.builtin $modules_dir/
depmod -a -b alpine-modloop $linux_ver
tar -zxf $firmware_tar --directory=alpine-modloop/lib/modules --warning=no-unknown-keyword --strip-components=1 --wildcards lib/firmware/ar* lib/firmware/rt*
for tar in linux-firmware-ath9k_htc-20190322-r0.apk linux-firmware-brcm-20190322-r0.apk linux-firmware-rtlwifi-20190322-r0.apk
do
tar -zxf $tar --directory=alpine-modloop/lib/modules --warning=no-unknown-keyword --strip-components=1
done
mksquashfs alpine-modloop/lib modloop -b 1048576 -comp xz -Xdict-size 100%
rm -rf alpine-uboot alpine-initramfs initrd.gz alpine-modloop
root_dir=alpine-root
mkdir -p $root_dir/usr/bin
cp /usr/bin/qemu-arm-static $root_dir/usr/bin/
mkdir -p $root_dir/etc
cp /etc/resolv.conf $root_dir/etc/
mkdir -p $root_dir/etc/apk
mkdir -p $root_dir/media/mmcblk0p1/cache
ln -s /media/mmcblk0p1/cache $root_dir/etc/apk/cache
cp -r alpine/etc $root_dir/
cp -r alpine/apps $root_dir/media/mmcblk0p1/
for project in led_blinker sdr_receiver_hpsdr sdr_transceiver sdr_transceiver_emb sdr_transceiver_ft8 sdr_transceiver_hpsdr sdr_transceiver_wide sdr_transceiver_wspr mcpha vna
do
mkdir -p $root_dir/media/mmcblk0p1/apps/$project
cp -r projects/$project/server/* $root_dir/media/mmcblk0p1/apps/$project/
cp -r projects/$project/app/* $root_dir/media/mmcblk0p1/apps/$project/
cp tmp/$project.bit $root_dir/media/mmcblk0p1/apps/$project/
done
cp -r alpine-apk/sbin $root_dir/
chroot $root_dir /sbin/apk.static --repository $alpine_url/main --update-cache --allow-untrusted --initdb add alpine-base
echo $alpine_url/main > $root_dir/etc/apk/repositories
echo $alpine_url/community >> $root_dir/etc/apk/repositories
chroot $root_dir /bin/sh <<- EOF_CHROOT
apk update
apk add haveged openssh ucspi-tcp6 iw wpa_supplicant dhcpcd dnsmasq hostapd iptables avahi dbus dcron chrony gpsd libgfortran musl-dev fftw-dev libconfig-dev alsa-lib-dev alsa-utils curl wget less nano bc dos2unix
ln -s /etc/init.d/bootmisc etc/runlevels/boot/bootmisc
ln -s /etc/init.d/hostname etc/runlevels/boot/hostname
ln -s /etc/init.d/hwdrivers etc/runlevels/boot/hwdrivers
ln -s /etc/init.d/modloop etc/runlevels/boot/modloop
ln -s /etc/init.d/swclock etc/runlevels/boot/swclock
ln -s /etc/init.d/sysctl etc/runlevels/boot/sysctl
ln -s /etc/init.d/syslog etc/runlevels/boot/syslog
ln -s /etc/init.d/urandom etc/runlevels/boot/urandom
ln -s /etc/init.d/killprocs etc/runlevels/shutdown/killprocs
ln -s /etc/init.d/mount-ro etc/runlevels/shutdown/mount-ro
ln -s /etc/init.d/savecache etc/runlevels/shutdown/savecache
ln -s /etc/init.d/devfs etc/runlevels/sysinit/devfs
ln -s /etc/init.d/dmesg etc/runlevels/sysinit/dmesg
ln -s /etc/init.d/mdev etc/runlevels/sysinit/mdev
rc-update add avahi-daemon default
rc-update add chronyd default
rc-update add dhcpcd default
rc-update add local default
rc-update add dcron default
rc-update add haveged default
rc-update add sshd default
mkdir -p etc/runlevels/wifi
rc-update -s add default wifi
rc-update add iptables wifi
rc-update add dnsmasq wifi
rc-update add hostapd wifi
sed -i 's/^SAVE_ON_STOP=.*/SAVE_ON_STOP="no"/;s/^IPFORWARD=.*/IPFORWARD="yes"/' etc/conf.d/iptables
sed -i 's/^#PermitRootLogin.*/PermitRootLogin yes/' etc/ssh/sshd_config
echo root:$passwd | chpasswd
setup-hostname red-pitaya
hostname red-pitaya
sed -i 's/^# LBU_MEDIA=.*/LBU_MEDIA=mmcblk0p1/' etc/lbu/lbu.conf
cat <<- EOF_CAT > root/.profile
alias rw='mount -o rw,remount /media/mmcblk0p1'
alias ro='mount -o ro,remount /media/mmcblk0p1'
EOF_CAT
ln -s /media/mmcblk0p1/apps root/apps
ln -s /media/mmcblk0p1/wifi root/wifi
lbu add root
lbu delete etc/resolv.conf
lbu delete etc/periodic/ft8
lbu delete etc/periodic/wspr
lbu delete root/.ash_history
lbu commit -d
apk add subversion make gcc gfortran
for project in server sdr_receiver_hpsdr sdr_transceiver sdr_transceiver_emb sdr_transceiver_ft8 sdr_transceiver_hpsdr sdr_transceiver_wide mcpha vna
do
make -C /media/mmcblk0p1/apps/\$project clean
make -C /media/mmcblk0p1/apps/\$project
done
svn co svn://svn.code.sf.net/p/wsjt/wsjt/wsjtx/trunk/lib/wsprd /media/mmcblk0p1/apps/sdr_transceiver_wspr/wsprd
make -C /media/mmcblk0p1/apps/sdr_transceiver_wspr/wsprd CFLAGS='-O3 -march=armv7-a -mtune=cortex-a9 -mfpu=neon -mfloat-abi=hard -ffast-math -fsingle-precision-constant -mvectorize-with-neon-quad' wsprd
make -C /media/mmcblk0p1/apps/sdr_transceiver_wspr
EOF_CHROOT
cp -r $root_dir/media/mmcblk0p1/apps .
cp -r $root_dir/media/mmcblk0p1/cache .
cp $root_dir/media/mmcblk0p1/red-pitaya.apkovl.tar.gz .
cp -r alpine/wifi .
hostname -F /etc/hostname
rm -rf $root_dir alpine-apk
zip -r red-pitaya-alpine-3.9-armv7-`date +%Y%m%d`.zip apps boot.bin cache devicetree.dtb modloop red-pitaya.apkovl.tar.gz uEnv.txt uImage uInitrd wifi
rm -rf apps cache modloop red-pitaya.apkovl.tar.gz uInitrd wifi
|
TERMUX_PKG_HOMEPAGE=http://md5deep.sourceforge.net/
TERMUX_PKG_DESCRIPTION="Programs to compute hashsums of arbitrary number of files recursively"
TERMUX_PKG_LICENSE="GPL-2.0"
TERMUX_PKG_MAINTAINER="@termux"
TERMUX_PKG_VERSION=4.4
TERMUX_PKG_REVISION=7
TERMUX_PKG_SRCURL=https://github.com/jessek/hashdeep/archive/v$TERMUX_PKG_VERSION.tar.gz
TERMUX_PKG_SHA256=ad78d42142f9a74fe8ec0c61bc78d6588a528cbb9aede9440f50b6ff477f3a7f
TERMUX_PKG_AUTO_UPDATE=true
TERMUX_PKG_DEPENDS="libc++"
termux_step_pre_configure() {
sh bootstrap.sh
}
|
<reponame>mhs1314/allPay
package com.julu.qht.service.impl;
import com.julu.qht.entity.MoneyScore;
import com.julu.qht.mapper.MoneyScoreDao;
import com.julu.qht.service.IMoneyScoreService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 充值积分兑换表,1 服务实现类
* </p>
*
* @author qht
* @since 2018-11-23
*/
@Service
public class MoneyScoreServiceImpl extends ServiceImpl<MoneyScoreDao, MoneyScore> implements IMoneyScoreService {
}
|
<gh_stars>0
class Loadavg
attr_reader :one_minute, :five_minutes, :fifteen_minutes
def initialize
result = File.open('/proc/loadavg', 'r').readline.split(' ')
@one_minute = result[0]
@five_minutes = result[1]
@fifteen_minutes = result[2]
end
end
|
#!/bin/bash
dieharder -d 8 -g 61 -S 3901455061
|
#!/bin/bash
cd /home/pi/LightDance-RPi
source config
python3 ./nthu_controller/wire.py
|
package pl.grzegorz2047.bukkitpe.core.protection;
import net.BukkitPE.Player;
import net.BukkitPE.Server;
import net.BukkitPE.event.EventHandler;
import net.BukkitPE.event.Listener;
import net.BukkitPE.event.entity.EntityDamageByEntityEvent;
import net.BukkitPE.event.entity.EntityDamageEvent;
import net.BukkitPE.level.Location;
import net.BukkitPE.level.Position;
/**
* Created by grzeg on 17.08.2016.
*/
public class AttackListeners implements Listener {
@EventHandler
public void onDamage(EntityDamageEvent e) {/*
Position loc = e.getEntity().getLevel().getSpawnLocation();
Position pLoc = e.getEntity().getPosition();
if (loc.distance(pLoc) < 10) {
e.setCancelled(true);
if (e.getEntity() instanceof Player) {
Player p = (Player) e.getEntity();
p.sendPopup("Nie mozesz bic sie blisko spawnu!");
}
}
e.setCancelled(true);
*/
Server.getInstance().getLogger().info("Wykonalem event!");
}
@EventHandler
public void onDamageSomething(EntityDamageByEntityEvent e) {
// e.setCancelled(true);
}
}
|
<reponame>keller35/ssh2-sftp-client<filename>example/realpath.js<gh_stars>100-1000
'use strict';
const path = require('path');
const dotenvPath = path.join(__dirname, '..', '.env');
require('dotenv').config({path: dotenvPath});
const Client = require('../src/index');
const client = new Client();
const targetPath = process.argv[2];
const config = {
host: process.env.SFTP_SERVER,
username: process.env.SFTP_USER,
password: <PASSWORD>,
port: process.env.SFTP_PORT || 22
};
client
.connect(config)
.then(() => {
return client.realPath(targetPath);
})
.then(absolutePath => {
console.log(`${targetPath} maps to ${absolutePath}`);
//return client.end();
})
.catch(err => {
console.log(`Error: ${err.message}`);
})
.finally(() => {
return client.end();
});
|
import yaml
def read_yaml(file_path: str) -> dict:
with open(file_path, 'r') as file:
object_relationships = yaml.safe_load(file)
return object_relationships |
<filename>src/js/reducers/photos.js<gh_stars>0
import createReducer, {
paginate,
fetchRequest,
fetchSuccessEntities,
fetchSuccess,
fetchFailure,
addToAnObjectWithKey,
removeFromAnObjectByKey
} from "./utilities"
import {
PHOTOS_REQUEST,
PHOTOS_SUCCESS,
PHOTOS_FAILURE,
PHOTOIDS_SELECTED_BY_KEY_SET,
PHOTOIDS_SELECTED_BY_KEY_REMOVE
} from "../actions/types"
// Slice Reducers
const photos = createReducer(
{},
{
PHOTOS_SUCCESS: fetchSuccessEntities
}
)
export const photosBuffered = createReducer(
{},
{
PHOTOS_REQUEST: fetchRequest,
PHOTOS_SUCCESS: fetchSuccess,
PHOTOS_FAILURE: fetchFailure
}
)
export const photosPagination = paginate({
mapActionToKey: action => action.key,
types: [
PHOTOS_REQUEST,
PHOTOS_SUCCESS,
PHOTOS_FAILURE
]
})
export const photoIDsSelectedByKey = createReducer(
{},
{
PHOTOIDS_SELECTED_BY_KEY_SET: addToAnObjectWithKey,
PHOTOIDS_SELECTED_BY_KEY_REMOVE: removeFromAnObjectByKey
}
)
export default photos
|
# common mac config
burrow plugin macos
burrow plugin homebrew
|
<filename>app/src/main/java/com/samourai/wallet/bip47/SendNotifTxFactory.java<gh_stars>1-10
package com.samourai.wallet.bip47;
import com.samourai.wallet.SamouraiWallet;
import java.math.BigInteger;
public class SendNotifTxFactory {
public static final BigInteger _bNotifTxValue = SamouraiWallet.bDust;
public static final BigInteger _bSWFee = SamouraiWallet.bFee;
// public static final BigInteger _bSWCeilingFee = BigInteger.valueOf(50000L);
public static final String SAMOURAI_NOTIF_TX_FEE_ADDRESS = "bc1qnc254nxjfj6ma093ctg79z96klvksvntmkffuq";
public static final String TESTNET_SAMOURAI_NOTIF_TX_FEE_ADDRESS = "tb1qh287jqsh6mkpqmd8euumyfam00fkr78qhrdnde";
// public static final double _dSWFeeUSD = 0.5;
private SendNotifTxFactory () { ; }
}
|
import numpy as np
# Define a function to detect anomalies
def detect_anomalies(data):
anomalies = []
# Calculate mean and standard deviation
mean = np.mean(data)
std = np.std(data)
# Define the threshold
threshold = std * 3
# Iterate over data
for i, point in enumerate(data):
# Check if data point is outside of the thresholds
if abs(point - mean) > threshold:
anomalies.append((i, point))
# Return the anomalies
return anomalies
# Get the data
data = np.load('data.npy')
# Detect the anomalies
anomalies = detect_anomalies(data)
# Print the results
print(anomalies) |
#!/bin/bash
set -eux
ln -sf /etc/puppet/hiera.yaml /etc/hiera.yaml
HOMEDIR="$homedir"
USERNAME=`ls -ld $HOMEDIR | awk {'print $3'}`
GROUPNAME=`ls -ld $HOMEDIR | awk {'print $4'}`
# WRITE OUT STACKRC
touch $HOMEDIR/stackrc
chmod 0600 $HOMEDIR/stackrc
cat > $HOMEDIR/stackrc <<-EOF_CAT
export OS_AUTH_TYPE=password
export OS_PASSWORD=$admin_password
export OS_AUTH_URL=$auth_url
export OS_USERNAME=admin
export OS_PROJECT_NAME=admin
export COMPUTE_API_VERSION=1.1
export NOVA_VERSION=1.1
export OS_NO_CACHE=True
export OS_CLOUDNAME=undercloud
# 1.34 is the latest API version in Ironic Pike supported by ironicclient
export IRONIC_API_VERSION=1.34
export OS_BAREMETAL_API_VERSION=\$IRONIC_API_VERSION
export OS_IDENTITY_API_VERSION='3'
export OS_PROJECT_DOMAIN_NAME='Default'
export OS_USER_DOMAIN_NAME='Default'
EOF_CAT
if [ -n "$internal_tls_ca_file" ]; then
cat >> $HOMEDIR/stackrc <<-EOF_CAT
export OS_CACERT="$internal_tls_ca_file"
EOF_CAT
fi
cat >> $HOMEDIR/stackrc <<-"EOF_CAT"
# Add OS_CLOUDNAME to PS1
if [ -z "${CLOUDPROMPT_ENABLED:-}" ]; then
export PS1=${PS1:-""}
export PS1=\${OS_CLOUDNAME:+"(\$OS_CLOUDNAME)"}\ $PS1
export CLOUDPROMPT_ENABLED=1
fi
EOF_CAT
if [ -n "$ssl_certificate" ]; then
cat >> $HOMEDIR/stackrc <<-EOF_CAT
export PYTHONWARNINGS="ignore:Certificate has no, ignore:A true SSLContext object is not available"
EOF_CAT
fi
chown "$USERNAME:$GROUPNAME" "$HOMEDIR/stackrc"
. $HOMEDIR/stackrc
if [ ! -f $HOMEDIR/.ssh/authorized_keys ]; then
sudo mkdir -p $HOMEDIR/.ssh
sudo chmod 700 $HOMEDIR/.ssh/
sudo touch $HOMEDIR/.ssh/authorized_keys
sudo chmod 600 $HOMEDIR/.ssh/authorized_keys
fi
if [ ! -f $HOMEDIR/.ssh/id_rsa ]; then
ssh-keygen -b 1024 -N '' -f $HOMEDIR/.ssh/id_rsa
fi
if ! grep "$(cat $HOMEDIR/.ssh/id_rsa.pub)" $HOMEDIR/.ssh/authorized_keys; then
cat $HOMEDIR/.ssh/id_rsa.pub >> $HOMEDIR/.ssh/authorized_keys
fi
chown -R "$USERNAME:$GROUPNAME" "$HOMEDIR/.ssh"
if [ "$(hiera nova_api_enabled)" = "true" ]; then
# Disable nova quotas
openstack quota set --cores -1 --instances -1 --ram -1 $(openstack project show admin | awk '$2=="id" {print $4}')
# Configure flavors.
RESOURCES='--property resources:CUSTOM_BAREMETAL=1 --property resources:DISK_GB=0 --property resources:MEMORY_MB=0 --property resources:VCPU=0 --property capabilities:boot_option=local'
SIZINGS='--ram 4096 --vcpus 1 --disk 40'
if ! openstack flavor show baremetal >/dev/null 2>&1; then
openstack flavor create $SIZINGS $RESOURCES baremetal
fi
if ! openstack flavor show control >/dev/null 2>&1; then
openstack flavor create $SIZINGS $RESOURCES --property capabilities:profile=control control
fi
if ! openstack flavor show compute >/dev/null 2>&1; then
openstack flavor create $SIZINGS $RESOURCES --property capabilities:profile=compute compute
fi
if ! openstack flavor show ceph-storage >/dev/null 2>&1; then
openstack flavor create $SIZINGS $RESOURCES --property capabilities:profile=ceph-storage ceph-storage
fi
if ! openstack flavor show block-storage >/dev/null 2>&1; then
openstack flavor create $SIZINGS $RESOURCES --property capabilities:profile=block-storage block-storage
fi
if ! openstack flavor show swift-storage >/dev/null 2>&1; then
openstack flavor create $SIZINGS $RESOURCES --property capabilities:profile=swift-storage swift-storage
fi
fi
# Set up a default keypair.
if [ ! -e $HOMEDIR/.ssh/id_rsa ]; then
sudo -E -u $USERNAME ssh-keygen -t rsa -N '' -f $HOMEDIR/.ssh/id_rsa
fi
if openstack keypair show default; then
echo Keypair already exists.
else
echo Creating new keypair.
openstack keypair create --public-key $HOMEDIR/.ssh/id_rsa.pub 'default'
fi
# MISTRAL WORKFLOW CONFIGURATION
if [ "$(hiera mistral_api_enabled)" = "true" ]; then
echo Configuring Mistral workbooks.
for workbook in $(openstack workbook list | grep tripleo | cut -f 2 -d ' '); do
openstack workbook delete $workbook
done
if openstack cron trigger show publish-ui-logs-hourly >/dev/null 2>&1; then
openstack cron trigger delete publish-ui-logs-hourly
fi
openstack workflow delete $(openstack workflow list -c Name -f value --filter tags=tripleo-common-managed) || true;
for workbook in $(ls /usr/share/openstack-tripleo-common/workbooks/*); do
openstack workbook create $workbook
done
openstack cron trigger create publish-ui-logs-hourly tripleo.plan_management.v1.publish_ui_logs_to_swift --pattern '0 * * * *'
echo Mistral workbooks configured successfully.
# Store the SNMP password in a mistral environment
if ! openstack workflow env show tripleo.undercloud-config >/dev/null 2>&1; then
TMP_MISTRAL_ENV=$(mktemp)
echo "{\"name\": \"tripleo.undercloud-config\", \"variables\": {\"undercloud_ceilometer_snmpd_password\": \"$snmp_readonly_user_password\"}}" > $TMP_MISTRAL_ENV
echo Configure Mistral environment with undercloud-config
openstack workflow env create $TMP_MISTRAL_ENV
fi
if [ "$(hiera enable_validations)" = "true" ]; then
echo Execute copy_ssh_key validations
openstack workflow execution create tripleo.validations.v1.copy_ssh_key
echo Upload validations to Swift
openstack workflow execution create tripleo.validations.v1.upload_validations
fi
fi
|
SELECT name
FROM Customers
WHERE city = 'London'; |
export interface JsxHtmlGlobalProps {
// Define global HTML props here
}
export interface JsxScriptElementProps extends JsxHtmlGlobalProps {
async?: boolean;
crossOrigin?: "anonymous" | "use-credentials";
defer?: boolean;
} |
func extractCategoryNames(from jsonResponse: Data) -> Result<[String], Error> {
do {
let json = try JSONSerialization.jsonObject(with: jsonResponse, options: [])
guard let jsonDict = json as? [String: Any],
let categories = jsonDict["categories"] as? [[String: String]] else {
throw NSError(domain: "InvalidJSON", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON format"])
}
let categoryNames = categories.compactMap { $0["name"] }
return .success(categoryNames)
} catch {
return .failure(error)
}
} |
#!/bin/bash
git fetch --all
git tag "v$npm_package_version-dist" origin/dist
git tag "v$npm_package_version-dist-simple" origin/dist-simple
git tag "v$npm_package_version-dist-selectable" origin/dist-selectable
git tag "v$npm_package_version-dist-placeholder" origin/dist-placeholder
git push --tags
|
package repository
import (
"context"
"fmt"
"gitlab.com/gitlab-org/gitaly/v14/internal/git"
"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
)
func (s *server) removeOriginInRepo(ctx context.Context, repository *gitalypb.Repository) error {
cmd, err := s.gitCmdFactory.New(ctx, repository, git.SubCmd{Name: "remote", Args: []string{"remove", "origin"}}, git.WithRefTxHook(ctx, repository, s.cfg))
if err != nil {
return fmt.Errorf("remote cmd start: %v", err)
}
if err := cmd.Wait(); err != nil {
return fmt.Errorf("remote cmd wait: %v", err)
}
return nil
}
|
def even_or_odd(num):
if num % 2 == 0:
print("The number is even")
else:
print("The number is odd") |
<gh_stars>1-10
require 'binpkgbot/emerge_runner'
module Binpkgbot
module Tasks
module Concern
module Emerge
def emerge_runner(script, **options)
emerge(nil, script: script, **options)
end
def emerge(atom, *args, ephemeral: !@options[:persist], use: @options[:use], accept_keywords: @options[:accept_keywords], unmasks: @options[:unmasks], masks: @options[:masks], script: nil)
EmergeRunner.new(
atom, *args,
ephemeral: ephemeral,
use: use,
accept_keywords: accept_keywords,
unmasks: unmasks,
masks: masks,
config: @config,
script: script,
).run
end
end
end
end
end
|
<filename>modules/component-web-core/src/main/java/com/nortal/spring/cw/core/web/component/composite/simple/AbstractTypeComponent.java
package com.nortal.spring.cw.core.web.component.composite.simple;
import com.nortal.spring.cw.core.web.component.ElementPathMap;
import com.nortal.spring.cw.core.web.component.composite.AbstractBaseComponent;
/**
* Baaskomponendi abstraktsioon koos tüübiga. Kasutatakse lihtkomponentide juures, mis esindavad ühte kindlat mudelobjekti
*
* @author <NAME>
* @since 01.03.2013
*/
public abstract class AbstractTypeComponent<T> extends AbstractBaseComponent implements FormComponent, ElementPathMap {
private static final long serialVersionUID = 1L;
private final Class<T> objectClass;
protected AbstractTypeComponent(String componentName, Class<T> objectClass) {
super(componentName);
this.objectClass = objectClass;
}
public Class<T> getObjectClass() {
return objectClass;
}
@Override
public void initComponentsIfNeeded() {
if (!isInitialized()) {
initComponent();
}
}
@Override
public String getPathKey() {
return getId();
}
}
|
var numero = 1
{
var numero = 2
console.log('dentro =', numero)
}
console.log('fora =', numero)
//Evitar ao máximo usar o sistema de var global pois pode causar muitos bugs no seu código |
@Override
public void run() {
while (true) {
synchronized (buffer) {
// Produce a new product
Product newProduct = randomOperations.generateProduct();
// Put the product into the buffer
buffer.put(newProduct);
// Update the MainPanel dashboard to reflect the production activity
dashboard.updateProduction(newProduct);
}
try {
// Sleep for the specified amount of time
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} |
<filename>src/main/java-gen/io/dronefleet/mavlink/uavionix/UavionixAdsbOutDynamicGpsFix.java
package io.dronefleet.mavlink.uavionix;
import io.dronefleet.mavlink.annotations.MavlinkEntryInfo;
import io.dronefleet.mavlink.annotations.MavlinkEnum;
/**
* Status for ADS-B transponder dynamic input
*/
@MavlinkEnum
public enum UavionixAdsbOutDynamicGpsFix {
/**
*
*/
@MavlinkEntryInfo(0)
UAVIONIX_ADSB_OUT_DYNAMIC_GPS_FIX_NONE_0,
/**
*
*/
@MavlinkEntryInfo(1)
UAVIONIX_ADSB_OUT_DYNAMIC_GPS_FIX_NONE_1,
/**
*
*/
@MavlinkEntryInfo(2)
UAVIONIX_ADSB_OUT_DYNAMIC_GPS_FIX_2D,
/**
*
*/
@MavlinkEntryInfo(3)
UAVIONIX_ADSB_OUT_DYNAMIC_GPS_FIX_3D,
/**
*
*/
@MavlinkEntryInfo(4)
UAVIONIX_ADSB_OUT_DYNAMIC_GPS_FIX_DGPS,
/**
*
*/
@MavlinkEntryInfo(5)
UAVIONIX_ADSB_OUT_DYNAMIC_GPS_FIX_RTK
}
|
#!/bin/bash
#gosdt m2.csv config.json 2>&1 | tee outputs/m2.json
./gosdt experiments/datasets/monk_1/m1.csv experiments/configurations/debug.json >outputs/m1.json
./gosdt m2.csv experiments/configurations/debug.json >outputs/m2.json
./gosdt experiments/datasets/monk_3/m3.csv experiments/configurations/debug.json >outputs/m3.json
./gosdt syn3.txt experiments/configurations/debug.json >outputs/syn3.json
./gosdt syn5.txt experiments/configurations/debug.json >outputs/syn5.json
#./gosdt tic-tac-toe.csv experiments/configurations/debug.json >outputs/tic-tac-toe.json 2>&1
|
/*
* Copyright 2014 Groupon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arpnetworking.configuration;
/**
* Interface for consumers registered for configuration events.
*
* @author <NAME> (ville dot koskela at inscopemetrics dot io)
*/
public interface Listener {
/**
* Invoked before new configuration is applied. Any registered listener
* may reject the configuration by throwing an {@link Exception}. Any
* listener rejecting the configuration rejects the entire configuration
* and the offering instance will log the {@link Exception} with an
* error. Once any listener rejects the {@link Configuration} other
* listeners may not be offered that instance.
*
* @param configuration The new {@link Configuration} to be validated.
* @throws Exception Thrown if the {@link Configuration} should be
* rejected.
*/
void offerConfiguration(Configuration configuration) throws Exception;
/**
* Invoked to apply the most recently offered configuration. Any
* {@link RuntimeException} thrown is logged and ignored. All
* validation must be performed during offer.
*/
void applyConfiguration();
}
|
#!/bin/bash
case $1 in
start)
#echo $$ > /var/run/happyhour.pid;
#exec 2>&1 /usr/bin/python3 /home/ubuntu/happyhour/server.py 1>/tmp/happyhour.out
/home/ubuntu/happyhour/venv/bin/python3 /home/ubuntu/happyhour/server.py &> /tmp/happyhour.out &
echo $! > /var/run/happyhour.pid
;;
stop)
kill `cat /var/run/happyhour.pid` ;;
*)
echo "usage: happyhour {start|stop}" ;;
esac
exit 0
|
#!/bin/sh -e
# There is a bug that causes an infinite loop when building code-gen.
# https://bugs.eclipse.org/bugs/show_bug.cgi?id=489387
# The following is a hack to workaround it. If there is a simpler way, never tell me.
M2="/root/.m2/repository"
export JAVA_HOME="/root/openjdk-8u292-b10"
export PATH="${JAVA_HOME}/bin:${PATH}"
#### HACK STARTS HERE ####
# Download the buggy artifact.
mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
-DrepoUrl=https://download.eclipse.org/releases/photon \
-Dartifact=org.eclipse.tycho:org.eclipse.osgi:3.10.0.v20140606-1445
# Get the source code for the buggy part of the artifact above. Not sure about the version.
git clone --depth 1 --branch I20140606-1215 https://eclipse.googlesource.com/equinox/rt.equinox.framework
# Fix the bug.
cd rt.equinox.framework
git apply --ignore-whitespace <<EOF
--- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java
+++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java
@@ -200,7 +200,7 @@ public class SignatureBlockProcessor implements SignedContentConstants {
if (aDigestLine != null) {
String msgDigestAlgorithm = getDigestAlgorithmFromString(aDigestLine);
if (!msgDigestAlgorithm.equalsIgnoreCase(signerInfo.getMessageDigestAlgorithm()))
- continue; // TODO log error?
+ break; // TODO log error?
byte digestResult[] = getDigestResultsList(aDigestLine);
//
EOF
# Compile the patched class.
javac -cp "${M2}/org/eclipse/tycho/org.eclipse.osgi/3.10.0.v20140606-1445/org.eclipse.osgi-3.10.0.v20140606-1445.jar" \
bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java
# Replace the patched class.
cd bundles/org.eclipse.osgi/container/src
zip "${M2}/org/eclipse/tycho/org.eclipse.osgi/3.10.0.v20140606-1445/org.eclipse.osgi-3.10.0.v20140606-1445.jar" \
org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.class
# Hack to disable jar verification since it will fail on this patched class and I'm not sure how to update the digest in the jar.
zip -d "${M2}/org/eclipse/tycho/org.eclipse.osgi/3.10.0.v20140606-1445/org.eclipse.osgi-3.10.0.v20140606-1445.jar" \
META-INF/ECLIPSE_.RSA
zip -d "${M2}/org/eclipse/tycho/org.eclipse.osgi/3.10.0.v20140606-1445/org.eclipse.osgi-3.10.0.v20140606-1445.jar" \
META-INF/ECLIPSE_.SF
#### HACK STOPS HERE ####
# Clone and build code-gen.
cd /root
git clone --depth 1 https://github.com/TalendStuff/code-gen.git
cd code-gen
mvn clean package |
#!/bin/bash
# usage: ./build-ROS-node name-of-lf-file-without-.lf name-of-ROS-package
lfc -r -n $1.lf
cp -R src-gen/* $2/src/
mv $2/src/$1.c $2/src/$1.cpp
pushd $2
colcon build --packages-select $2
popd
|
<reponame>beamka/Polyclinic<gh_stars>0
/**
*
*/
package ua.clinic.repository;
import org.springframework.data.repository.CrudRepository;
import ua.clinic.jpa.Specialty;
/**
* @author <NAME>
*
*/
public interface SpecialtyCodeRepository extends CrudRepository<Specialty, Long> {
}
|
/*
* Copyright (c) 2018 https://www.reactivedesignpatterns.com/
*
* Copyright (c) 2018 https://rdp.reactiveplatform.xyz/
*
*/
package chapter14;
import chapter14.ComplexCommand.BatchJobJS;
import chapter14.ComplexCommand.PartialResult;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ComplexCommandTest {
public static void main(String[] args) throws IOException {
try (InputStream js = ComplexCommandTest.class.getResourceAsStream("/chapter14/job.js");
Scanner s = new Scanner(js, "UTF-8")) {
s.useDelimiter("\\A");
final BatchJobJS job = new BatchJobJS("", s.next(), "");
final ComplexCommand.WorkerJS worker = new ComplexCommand.WorkerJS();
final PartialResult result = worker.runJob(job);
System.out.println(result);
}
}
}
|
#!/bin/bash
# Install Ubuntu Desktop if not using Vagrant
if [[ $PACKER_BUILD_NAME != vagrant* ]]; then
dpkg --configure -a
apt-get -y update
apt-get -y install ubuntu-desktop
# Customize the message of the day
echo 'Sugar 7 Development Environment (Desktop)' > /etc/motd
# Lets avoid prompting immediately for release upgrade, if users do this it will break stack config
sed -i "s/Prompt=.*/Prompt=never/" /etc/update-manager/release-upgrades
fi |
#include <adiar/zdd.h>
#include <adiar/zdd/zdd_policy.h>
#include <adiar/data.h>
#include <adiar/internal/build.h>
#include <adiar/internal/intercut.h>
namespace adiar
{
class zdd_complement_policy : public zdd_policy
{
public:
static constexpr bool may_skip = false;
static constexpr bool cut_true_sink = true;
static constexpr bool cut_false_sink = true;
public:
static zdd on_empty_labels(const zdd& dd)
{
return dd;
}
static zdd on_sink_input(const bool sink_value, const zdd& /*dd*/, const label_file &universe)
{
return sink_value
// The entire universe minus Ø
? build_chain<false, true, true, false, true>(universe)
// The entire universe
: build_chain<true, true, true, true, true>(universe);
}
// LCOV_EXCL_START
static zdd sink(const bool /*sink_value*/)
{ adiar_unreachable(); }
// LCOV_EXCL_END
// We can improve this by knowing whether we are at the very last label. If
// that is the case, and the high edge becomes F, then it can be skipped.
//
// Yet, this is only 2 nodes that we can kill; that is 4 arcs. This is 32
// bytes of data and very few computation cycles. For very large cases the
// shortcutting in branch-prediction probably offsets this?
static intercut_rec_output hit_existing(const node_t &n)
{
const ptr_t low = is_sink(n.low) ? negate(n.low) : n.low;
const ptr_t high = is_sink(n.high) ? negate(n.high) : n.high;
return intercut_rec_output { low, high };
}
static intercut_rec_output hit_cut(const ptr_t target)
{
// T chain: We are definitely outside of the given set
if (is_sink(target) && value_of(target)) {
return intercut_rec_output { target, target };
}
// Otherwise, check whether this variable is true and so we move to the T chain
return intercut_rec_output { target, create_sink_ptr(true) };
}
// LCOV_EXCL_START
static intercut_rec_output miss_existing(const node_t &/*n*/)
{ adiar_unreachable(); }
// LCOV_EXCL_END
};
__zdd zdd_complement(const zdd &dd, const label_file &universe)
{
return intercut<zdd_complement_policy>(dd, universe);
}
}
|
function min(x, y, z) {
var min = x;
if (min > y) {
min = y;
}
if (min > z) {
min = z;
}
return min;
}
var m = min(4, 3, 9);
console.log(m); // 3 |
<reponame>evenchange4/calendar-todo
// @flow
import {
ApolloClient,
type ApolloClient as ApolloClientType,
} from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import createLogLink from 'apollo-link-log';
import { InMemoryCache } from 'apollo-cache-inmemory';
import dotenv from './dotenv';
import log from './log';
import checkServer from './checkServer';
import { type Dotenv } from './type.flow';
const { API_DOMAIN } = (dotenv: Dotenv);
const { NODE_ENV } = process.env;
export default function createApolloClient(
initialState: Object,
): ApolloClientType<*> {
const httpLink: Object = new HttpLink({
uri: API_DOMAIN,
credentials: 'same-origin',
});
const logLink = createLogLink({
enabled: NODE_ENV !== 'production',
logger: log,
});
return new ApolloClient({
connectToDevTools: !checkServer(),
ssrMode: checkServer(), // Disables forceFetch on the server (so queries are only run once)
link: logLink.concat(httpLink),
cache: new InMemoryCache().restore(initialState),
});
}
|
<gh_stars>0
package com.professorvennie.bronzeage.items;
import com.professorvennie.bronzeage.api.BronzeAgeAPI;
import com.professorvennie.bronzeage.api.wrench.IWrench;
import com.professorvennie.bronzeage.api.wrench.IWrenchable;
import com.professorvennie.bronzeage.api.wrench.WrenchMaterial;
import com.professorvennie.bronzeage.lib.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.input.Keyboard;
import java.util.List;
/**
* Created by ProfessorVennie on 11/26/2014 at 11:50 PM.
*/
public class ItemWrench extends ItemBase implements IWrench {
private final int numOfWrenches = 6;
private IIcon[] icons;
public ItemWrench() {
super("wrench");
setHasSubtypes(true);
setMaxStackSize(1);
}
@Override
public String getUnlocalizedName(ItemStack itemStack) {
if(itemStack.getTagCompound().getBoolean("isBroken"))
return super.getUnlocalizedName(itemStack) + "." + getWrenchMaterial(itemStack).getLocalizedName() + ".broken";
return super.getUnlocalizedName(itemStack) + "." + getWrenchMaterial(itemStack).getLocalizedName();
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tab, List list) {
for (int i = 0; i < numOfWrenches; i++) {
list.add(new ItemStack(item, 1, i));
}
}
@Override
public boolean showDurabilityBar(ItemStack stack) {
return true;
}
@Override
public double getDurabilityForDisplay(ItemStack stack) {
return ((double)getWrenchMaterial(stack).getNumOfUses() - getNumOfUsesRemaining(stack)) / (double)getWrenchMaterial(stack).getNumOfUses();
}
@Override
public int getDurability(ItemStack itemStack) {
return getWrenchMaterial(itemStack).getDurability();
}
@Override
public float getNumOfUsesRemaining(ItemStack itemStack) {
initNBT(itemStack);
return itemStack.getTagCompound().getFloat("NumOfUsesRemaining");
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean b) {
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
list.add(EnumChatFormatting.GOLD + translate("material") + ": " + EnumChatFormatting.DARK_AQUA + getWrenchMaterial(itemStack).getLocalizedName());
list.add(EnumChatFormatting.GOLD + translate("numOfUses") + ": " + EnumChatFormatting.DARK_AQUA + getNumOfUsesRemaining(itemStack));
list.add(EnumChatFormatting.GOLD + translate("rotation") + ": " + EnumChatFormatting.DARK_AQUA + getWrenchMaterial(itemStack).getUsesPerRotation());
list.add(EnumChatFormatting.GOLD + translate("dismantle") + ": " + EnumChatFormatting.DARK_AQUA + getWrenchMaterial(itemStack).getUsesPerDismantle());
list.add(EnumChatFormatting.GOLD + translate("durability") + ": " + EnumChatFormatting.DARK_AQUA + getDurability(itemStack));
} else {
list.add(EnumChatFormatting.GOLD + translate("numOfUses") + ": " + EnumChatFormatting.DARK_AQUA + getNumOfUsesRemaining(itemStack));
list.add(EnumChatFormatting.DARK_GRAY + translate("hold") + " " + EnumChatFormatting.DARK_AQUA + translate("shift") + " " + EnumChatFormatting.DARK_GRAY + translate("moreInfo"));
list.add(EnumChatFormatting.DARK_GRAY + translate("hold") + " " + EnumChatFormatting.DARK_AQUA + translate("shiftandh") + " " + EnumChatFormatting.DARK_GRAY + translate("helpInfo"));
}
if ((Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) && Keyboard.isKeyDown(Keyboard.KEY_H)) {
list.add(EnumChatFormatting.DARK_GRAY + translate("info.0"));
list.add(EnumChatFormatting.DARK_GRAY + translate("info.1"));
list.add(EnumChatFormatting.DARK_GRAY + translate("info.2"));
list.add(EnumChatFormatting.DARK_GRAY + translate("info.3"));
list.add(EnumChatFormatting.DARK_GRAY + translate("info.4"));
list.add(EnumChatFormatting.DARK_GRAY + translate("info.5"));
}
}
private String translate(String name) {
return StatCollector.translateToLocal("tooltip.wrench." + name);
}
@Override
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
float dismanlt = getWrenchMaterial(itemStack).getUsesPerDismantle();
float rotate = getWrenchMaterial(itemStack).getUsesPerRotation();
float usesRemaining = getNumOfUsesRemaining(itemStack);
if (!player.isSneaking()) {
if (world.getBlock(x, y, z) instanceof IWrenchable) {
if (usesRemaining - rotate >= 0 && !world.isRemote && world.getBlock(x, y, z).rotateBlock(world, x, y, z, ForgeDirection.getOrientation(side).getOpposite())) {
subtractUse(itemStack, rotate);
Block block = world.getBlock(x, y, z);
block.rotateBlock(world, x, y, z, ForgeDirection.getOrientation(side).getOpposite());
player.swingItem();
}else if(usesRemaining == 0){
initNBT(itemStack);
itemStack.getTagCompound().setBoolean("isBroken", true);
}
}
} else {
if (world.getBlock(x, y, z) instanceof IWrenchable) {
IWrenchable wrenchable = (IWrenchable) world.getBlock(x, y, z);
if (usesRemaining - dismanlt >= 0 && !world.isRemote) {
subtractUse(itemStack, dismanlt);
if (!world.isRemote) {
player.swingItem();
wrenchable.dismantle(world, player, itemStack, x, y, z);
}
}else if(usesRemaining == 0){
initNBT(itemStack);
itemStack.getTagCompound().setBoolean("isBroken", true);
}
}
}
if(!(usesRemaining - dismanlt >= 0 && usesRemaining - rotate >= 0)){
initNBT(itemStack);
itemStack.getTagCompound().setBoolean("isBroken", true);
}
return super.onItemUseFirst(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ);
}
@Override
public void onUpdate(ItemStack itemStack, World world, Entity entity, int i, boolean b) {
initNBT(itemStack);
if(getNumOfUsesRemaining(itemStack) == 0)
itemStack.getTagCompound().setBoolean("isBroken", true);
super.onUpdate(itemStack, world, entity, i, b);
}
@Override
public WrenchMaterial getWrenchMaterial(ItemStack itemStack) {
switch (itemStack.getItemDamage()) {
case 0:
return BronzeAgeAPI.stoneWrenchMaterial;
case 1:
return BronzeAgeAPI.tinWrenchMaterial;
case 2:
return BronzeAgeAPI.copperWrenchMaterial;
case 3:
return BronzeAgeAPI.ironWrenchMaterial;
case 4:
return BronzeAgeAPI.bronzeWrenchMaterial;
case 5:
return BronzeAgeAPI.diamondWrenchMaterial;
default:
return null;
}
}
@Override
public void addUse(ItemStack itemStack, float amountOfUses) {
initNBT(itemStack);
itemStack.getTagCompound().setFloat("NumOfUsesRemaining", itemStack.getTagCompound().getFloat("NumOfUsesRemaining") + amountOfUses);
}
@Override
public void subtractUse(ItemStack itemStack, float amountOfUses) {
initNBT(itemStack);
itemStack.getTagCompound().setFloat("NumOfUsesRemaining", itemStack.getTagCompound().getFloat("NumOfUsesRemaining") - amountOfUses);
}
private void initNBT(ItemStack itemStack) {
if (itemStack.getTagCompound() == null) {
itemStack.setTagCompound(new NBTTagCompound());
itemStack.getTagCompound().setFloat("NumOfUsesRemaining", getWrenchMaterial(itemStack).getNumOfUses());
}
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister) {
icons = new IIcon[numOfWrenches];
for (int i = 0; i < icons.length; i++)
icons[i] = iconRegister.registerIcon(Reference.MOD_ID + ":" + getWrenchMaterial(new ItemStack(this, 1, i)).getLocalizedName() + "Wrench");
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int i) {
return i < icons.length ? icons[i] : icons[0];
}
}
|
import React, { FC } from 'react';
import style from './Message.module.scss';
import sprite from '../../assets/sprite.svg';
interface IProps {
isReceiving: boolean;
}
const Message: FC<IProps> = React.memo(({ isReceiving }) => {
return (
<div
className={
isReceiving
? `${style.message} ${style.message_received}`
: style.message
}
>
<div className={style.message__container}>
<div
style={{ backgroundImage: 'url("./assets/icon/logIn.svg")' }}
className={style.message__avatar}
/>
<div
// style={{ backgroundImage: 'url("./assets/icon/messageArrow.svg")' }}
className={style.message__wrapper}
>
<svg className={style.message__arrow}>
<use href={`${sprite}#messageArrow`} />
</svg>
<span className={style.message__text}>
Hello, my naa my name is my name is Violanaa my name is my name is
Violanaa my name
</span>
</div>
</div>
</div>
);
});
export default Message;
|
<filename>src/components/Gridlist/strings/ru.js<gh_stars>0
cm.setMessages('Com.Gridlist', {
'counter' : 'Количество: ',
'check_all' : 'Выделить все',
'uncheck_all' : 'Отменить выделение',
'empty' : 'Список элементов пуст',
'actions' : 'Действия'
});
cm.setMessages('Com.GridlistFilter', {
'placeholder' : 'Впишите текст для поиска...',
'search' : '',
'clear' : 'Очистить'
});
|
/*! THIS FILE IS AUTO-GENERATED */
import { customsearch_v1 } from './v1';
export declare const VERSIONS: {
'v1': typeof customsearch_v1.Customsearch;
};
export declare function customsearch(version: 'v1'): customsearch_v1.Customsearch;
export declare function customsearch(options: customsearch_v1.Options): customsearch_v1.Customsearch;
|
#!/bin/bash
RAILS_ENV=$1
if [ -z $RAILS_ENV ]; then
RAILS_ENV="production"
fi
echo "Tailing rails logs with RAILS_ENV=$RAILS_ENV"
docker logs -f rails
|
// Copyright 2016 <NAME>, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package run_test
import (
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"testing"
"github.com/nmiyake/pkg/dirs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/palantir/godel/apps/distgo/cmd/run"
"github.com/palantir/godel/apps/distgo/params"
"github.com/palantir/godel/apps/distgo/pkg/git"
)
const (
runTestMain = `package main
import (
"fmt"
"io/ioutil"
"os"
"path"
)
func main() {
fmt.Println("testMainOutput")
ioutil.WriteFile(path.Join("{{OUTPUT_PATH}}", "runTestMainOutput.txt"), []byte(fmt.Sprintf("%v", os.Args[1:])), 0644)
}
`
runTestMainBar = `package main
import (
"fmt"
"io/ioutil"
"os"
"path"
)
func main() {
bar("testMainOutput")
ioutil.WriteFile(path.Join("{{OUTPUT_PATH}}", "runTestMainOutput.txt"), []byte(fmt.Sprintf("%v", os.Args[1:])), 0644)
}
`
)
func TestRun(t *testing.T) {
tmp, cleanup, err := dirs.TempDir("", "")
defer cleanup()
require.NoError(t, err)
for i, currCase := range []struct {
spec func(projectDir string) params.ProductBuildSpec
runArgs []string
preRunAction func(projectDir string)
validate func(runErr error, caseNum int, projectDir string)
}{
{
// "run" runs main file
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./.",
},
},
params.Project{},
)
},
preRunAction: func(projectDir string) {
err := ioutil.WriteFile(path.Join(projectDir, "main.go"), []byte(strings.Replace(runTestMain, "{{OUTPUT_PATH}}", projectDir, -1)), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.NoError(t, runErr, "Case %d", caseNum)
bytes, err := ioutil.ReadFile(path.Join(projectDir, "runTestMainOutput.txt"))
require.NoError(t, err, "Case %d", caseNum)
assert.Equal(t, "[]", string(bytes))
},
},
{
// "run" uses arguments provided in configuration (but does not evaluate them)
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./.",
},
Run: params.Run{
Args: []string{
"foo",
"bar",
"$GOPATH",
},
},
},
params.Project{},
)
},
preRunAction: func(projectDir string) {
err := ioutil.WriteFile(path.Join(projectDir, "main.go"), []byte(strings.Replace(runTestMain, "{{OUTPUT_PATH}}", projectDir, -1)), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.NoError(t, runErr, "Case %d", caseNum)
bytes, err := ioutil.ReadFile(path.Join(projectDir, "runTestMainOutput.txt"))
require.NoError(t, err, "Case %d", caseNum)
assert.Equal(t, "[foo bar $GOPATH]", string(bytes))
},
},
{
// "run" uses arguments provided in slice
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./.",
},
},
params.Project{},
)
},
runArgs: []string{"foo", "bar", "$GOPATH"},
preRunAction: func(projectDir string) {
err := ioutil.WriteFile(path.Join(projectDir, "main.go"), []byte(strings.Replace(runTestMain, "{{OUTPUT_PATH}}", projectDir, -1)), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.NoError(t, runErr, "Case %d", caseNum)
bytes, err := ioutil.ReadFile(path.Join(projectDir, "runTestMainOutput.txt"))
require.NoError(t, err, "Case %d", caseNum)
assert.Equal(t, "[foo bar $GOPATH]", string(bytes))
},
},
{
// "run" combines arguments in configuration with provided arguments
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./.",
},
Run: params.Run{
Args: []string{
"cfgArg_foo",
"cfgArg_bar",
"$cfgArg",
},
},
},
params.Project{},
)
},
runArgs: []string{"runArg_foo", "runArg_bar", "$runArg"},
preRunAction: func(projectDir string) {
err := ioutil.WriteFile(path.Join(projectDir, "main.go"), []byte(strings.Replace(runTestMain, "{{OUTPUT_PATH}}", projectDir, -1)), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.NoError(t, runErr, "Case %d", caseNum)
bytes, err := ioutil.ReadFile(path.Join(projectDir, "runTestMainOutput.txt"))
require.NoError(t, err, "Case %d", caseNum)
assert.Equal(t, "[cfgArg_foo cfgArg_bar $cfgArg runArg_foo runArg_bar $runArg]", string(bytes))
},
},
{
// "run" works with multiple main package files as long as there is a single main function
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./foo",
},
},
params.Project{},
)
},
preRunAction: func(projectDir string) {
err := os.MkdirAll(path.Join(projectDir, "foo"), 0755)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "main_file.go"), []byte(strings.Replace(runTestMainBar, "{{OUTPUT_PATH}}", projectDir, -1)), 0644)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "other_main_file.go"), []byte(`package main
import "fmt"
func bar(a ...interface{}) (n int, err error) {
return fmt.Println(a...)
}
`), 0644)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "main_test.go"), []byte(`package main_test
func Bar() string {
return "bar"
}
`), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.NoError(t, runErr, "Case %d", caseNum)
bytes, err := ioutil.ReadFile(path.Join(projectDir, "runTestMainOutput.txt"))
require.NoError(t, err, "Case %d", caseNum)
assert.Equal(t, "[]", string(bytes))
},
},
{
// "run" works with multiple main package files with tests
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./foo",
},
},
params.Project{},
)
},
preRunAction: func(projectDir string) {
err := os.MkdirAll(path.Join(projectDir, "foo"), 0755)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "main_file.go"), []byte(strings.Replace(runTestMain, "{{OUTPUT_PATH}}", projectDir, -1)), 0644)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "main_test.go"), []byte(`package main
import "testing"
func TestBar(t *testing.T) {
}
`), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.NoError(t, runErr, "Case %d", caseNum)
bytes, err := ioutil.ReadFile(path.Join(projectDir, "runTestMainOutput.txt"))
require.NoError(t, err, "Case %d", caseNum)
assert.Equal(t, "[]", string(bytes))
},
},
{
// "run" fails if a main package does not exist
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./foo",
},
},
params.Project{},
)
},
preRunAction: func(projectDir string) {
err := os.MkdirAll(path.Join(projectDir, "foo"), 0755)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "not_main_pkg.go"), []byte(`package foo
func main() {
}
`), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.Error(t, runErr, fmt.Sprintf("Case %d", caseNum))
assert.Regexp(t, regexp.MustCompile(`^failed to find main file: no go file with main package and main function exists in directory .+/foo$`), runErr.Error(), "Case %d", caseNum)
},
},
{
// "run" fails if main function does not exist in a main pkg
spec: func(projectDir string) params.ProductBuildSpec {
return params.NewProductBuildSpec(
projectDir,
"foo",
git.ProjectInfo{},
params.Product{
Build: params.Build{
MainPkg: "./foo",
},
},
params.Project{},
)
},
preRunAction: func(projectDir string) {
err := os.MkdirAll(path.Join(projectDir, "foo"), 0755)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "no_main_func.go"), []byte(`package main
func Foo() string {
return "foo"
}
`), 0644)
require.NoError(t, err)
err = ioutil.WriteFile(path.Join(projectDir, "foo", "main_func_not_main_pkg.go"), []byte(`package main_test
func main() {
}
`), 0644)
require.NoError(t, err)
},
validate: func(runErr error, caseNum int, projectDir string) {
assert.Error(t, runErr, fmt.Sprintf("Case %d", caseNum))
assert.Regexp(t, regexp.MustCompile(`^failed to find main file: no go file with main package and main function exists in directory .+/foo$`), runErr.Error(), "Case %d", caseNum)
},
},
} {
currTmpDir, err := ioutil.TempDir(tmp, "")
require.NoError(t, err, "Case %d", i)
if currCase.preRunAction != nil {
currCase.preRunAction(currTmpDir)
}
err = run.DoRun(currCase.spec(currTmpDir), currCase.runArgs, ioutil.Discard, ioutil.Discard)
if currCase.validate != nil {
currCase.validate(err, i, currTmpDir)
}
}
}
|
<filename>lib/mohamed_test.rb
# MohamedTest
class MohamedTest
unloadable
end
|
def override_params(func):
def wrapper(*args, **kwargs):
if len(args) < 2 or not isinstance(args[1], dict):
raise ValueError("Second argument must be a dictionary for parameter overrides")
original_args = list(args)
original_kwargs = kwargs.copy()
overload = args[1]
for key, value in overload.items():
if key in original_kwargs:
original_kwargs[key] = value
else:
if len(original_args) > 1:
original_args = list(original_args[:1]) + [overload] + list(original_args[2:])
else:
original_args.append(overload)
return func(*original_args, **original_kwargs)
return wrapper
@override_params
def example_function(x, overload):
"""
Parameters
----------
x : tensor
Input tensor
overload : dict
All parameters defined at build time can be overridden
at call time.
Returns
-------
"""
print("x:", x)
print("overload:", overload)
# Example usage
x = "original"
result = example_function(x, {'param1': 10, 'param2': 'override'}) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Milight 3.0 (LimitlessLED Wifi Bridge v6.0) library: Control wireless lights (Milight 3.0) with Wifi
Note that this library was tested with Milight Wifi iBox v1 and RGBW lights. It should work with any other
lights and bridge using Milight 3.0 / LimitlessLED v6.0 protocol.
Non-exhaustive functionality using the python class or using this file from shell
(launch this python file with '-h' parameter to get more information):
- Initialize the Wifi bridge
- Link/Unlink lights
- Light on/off
- Wifi bridge lamp on/off
- Set night mode
- Set white mode
- Set color
- Set saturation
- Set brightness
- Set disco mode (9 available)
- Increase/Decrease disco mode speed
- Get Milight wifi bridge MAC address
- ...
Used protocol: http://www.limitlessled.com/dev/ (LimitlessLED Wifi Bridge v6.0 section)
"""
__author__ = '<NAME>'
__email__ = "<EMAIL>"
__license__ = "MIT License"
__copyright__ = "Copyright Quentin Comte-Gaz (2017)"
__python_version__ = "3.+"
__version__ = "1.0 (2017/04/10)"
__status__ = "Usable for any project"
import socket
import time
import collections
import sys, getopt
import binascii
# import logging
class MilightWifiBridge:
"""Milight 3.0 Wifi Bridge class
Calling setup() function is necessary in order to make this class work properly.
"""
######################### Enums #########################
class eZone:
ALL = 0
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
class eDiscoMode:
DISCO_1 = 1
DISCO_2 = 2
DISCO_3 = 3
DISCO_4 = 4
DISCO_5 = 5
DISCO_6 = 6
DISCO_7 = 7
DISCO_8 = 8
DISCO_9 = 9
class eTemperature:
WARM = 0 # 2700K
WARM_WHITE = 8 # 3000K
COOL_WHITE = 35 # 4000K
DAYLIGHT = 61 # 5000K
COOL_DAYLIGHT = 100 # 6500K
######################### static variables/static functions/internal struct #########################
__START_SESSION_MSG = bytearray([0x20, 0x00, 0x00, 0x00, 0x16, 0x02, 0x62, 0x3A, 0xD5, 0xED, 0xA3, 0x01, 0xAE, 0x08,
0x2D, 0x46, 0x61, 0x41, 0xA7, 0xF6, 0xDC, 0xAF, 0xD3, 0xE6, 0x00, 0x00, 0x1E])
# Response sent by the milight wifi bridge after a start session query
# Keyword arguments:
# responseReceived -- (bool) Response valid
# mac -- (string) MAC address of the wifi bridge
# sessionId1 -- (int) First part of the session ID
# sessionId2 -- (int) Second part of the session ID
# sequenceNumber -- (int) Sequence number
__START_SESSION_RESPONSE = collections.namedtuple("StartSessionResponse", "responseReceived mac sessionId1 sessionId2")
__ON_CMD = bytearray([0x31, 0x00, 0x00, 0x08, 0x04, 0x01, 0x00, 0x00, 0x00])
__OFF_CMD = bytearray([0x31, 0x00, 0x00, 0x08, 0x04, 0x02, 0x00, 0x00, 0x00])
__NIGHT_MODE_CMD = bytearray([0x31, 0x00, 0x00, 0x08, 0x04, 0x05, 0x00, 0x00, 0x00])
__WHITE_MODE_CMD = bytearray([0x31, 0x00, 0x00, 0x08, 0x05, 0x64, 0x00, 0x00, 0x00])
__DISCO_MODE_SPEED_UP_CMD = bytearray([0x31, 0x00, 0x00, 0x08, 0x04, 0x03, 0x00, 0x00, 0x00])
__DISCO_MODE_SLOW_DOWN_CMD = bytearray([0x31, 0x00, 0x00, 0x08, 0x04, 0x04, 0x00, 0x00, 0x00])
__LINK_CMD = bytearray([0x3D, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00])
__UNLINK_CMD = bytearray([0x3E, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00])
__WIFI_BRIDGE_LAMP_ON_CMD = bytearray([0x31, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00])
__WIFI_BRIDGE_LAMP_OFF_CMD = bytearray([0x31, 0x00, 0x00, 0x00, 0x03, 0x04, 0x00, 0x00, 0x00])
__WIFI_BRIDGE_LAMP_WHITE_MODE_CMD = bytearray([0x31, 0x00, 0x00, 0x00, 0x03, 0x05, 0x00, 0x00, 0x00])
__WIFI_BRIDGE_LAMP_DISCO_MODE_SPEED_UP_CMD = bytearray([0x31, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00])
__WIFI_BRIDGE_LAMP_DISCO_MODE_SLOW_DOWN_CMD = bytearray([0x31, 0x00, 0x00, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00])
@staticmethod
def __getSetBridgeLampColorCmd(color):
"""Give 'Set color for bridge lamp' command
Keyword arguments:
color -- (int) Color value between 0x00 and 0xFF
examples: 0xFF = Red, 0xD9 = Lavender, 0xBA = Blue, 0x85 = Aqua,
0x7A = Green, 0x54 = Lime, 0x3B = Yellow, 0x1E = Orange
return: (bytearray) 'Set colo for bridge lamp' command
"""
color = int(color) & 0xFF
return bytearray([0x31, 0x00, 0x00, 0x00, 0x01, color, color, color, color])
@staticmethod
def __getSetColorCmd(color):
"""Give 'Set color' command
Keyword arguments:
color -- (int) Color value between 0x00 and 0xFF
examples: 0xFF = Red, 0xD9 = Lavender, 0xBA = Blue, 0x85 = Aqua,
0x7A = Green, 0x54 = Lime, 0x3B = Yellow, 0x1E = Orange
return: (bytearray) 'Set color' command
"""
color = int(color) & 0xFF
return bytearray([0x31, 0x00, 0x00, 0x08, 0x01, color, color, color, color])
@staticmethod
def __getSetDiscoModeForBridgeLampCmd(mode):
"""Give 'Set disco mode for bridge lamp' command
Keyword arguments:
mode -- (int) Disco mode between 1 and 9
return: (bytearray) 'Set disco mode for bridge lamp' command
"""
mode = int(mode) & 0xFF
if mode < 1:
mode = 1
elif mode > 9:
mode = 9
return bytearray([0x31, 0x00, 0x00, 0x00, 0x04, mode, 0x00, 0x00, 0x00])
@staticmethod
def __getSetDiscoModeCmd(mode):
"""Give 'Set disco mode' command
Keyword arguments:
mode -- (int) Disco mode between 1 and 9
return: (bytearray) 'Set disco mode' command
"""
mode = int(mode) & 0xFF
if mode < 1:
mode = 1
elif mode > 9:
mode = 9
return bytearray([0x31, 0x00, 0x00, 0x08, 0x06, mode, 0x00, 0x00, 0x00])
@staticmethod
def __getSetBrightnessForBridgeLampCmd(brightness):
"""Give 'Set brightness for bridge lamp' command
Keyword arguments:
brightness -- (int) Brightness percentage between 0 and 100
return: (bytearray) 'Set brightness for bridge lamp' command
"""
brightness = int(brightness) & 0xFF
if brightness < 0:
brightness = 0
elif brightness > 100:
brightness = 100
return bytearray([0x31, 0x00, 0x00, 0x00, 0x02, brightness, 0x00, 0x00, 0x00])
@staticmethod
def __getSetBrightnessCmd(brightness):
"""Give 'Set brightness' command
Keyword arguments:
brightness -- (int) Brightness percentage between 0 and 100
return: (bytearray) 'Set brightness' command
"""
brightness = int(brightness) & 0xFF
if brightness < 0:
brightness = 0
elif brightness > 100:
brightness = 100
return bytearray([0x31, 0x00, 0x00, 0x08, 0x03, brightness, 0x00, 0x00, 0x00])
@staticmethod
def __getSetSaturationCmd(saturation):
"""Give 'Set saturation' command
Keyword arguments:
saturation -- (int) Saturation percentage between 0 and 100
return: (bytearray) 'Set saturation' command
"""
saturation = int(saturation) & 0xFF
if saturation < 0:
saturation = 0
elif saturation > 100:
saturation = 100
return bytearray([0x31, 0x00, 0x00, 0x08, 0x02, saturation, 0x00, 0x00, 0x00])
@staticmethod
def __getSetTemperatureCmd(temperature):
"""Give 'Set temperature' command
Keyword arguments:
temperature -- (int) Temperature percentage between 0 and 100
0% <=> Warm white (2700K)
100% <=> Cool white (6500K)
return: (bytearray) 'Set temperature' command
"""
temperature = int(temperature) & 0xFF
if temperature < 0:
temperature = 0
elif temperature > 100:
temperature = 100
return bytearray([0x31, 0x00, 0x00, 0x08, 0x05, temperature, 0x00, 0x00, 0x00])
@staticmethod
def __calculateCheckSum(command, zoneId):
"""Calculate request checksum
Note: Request checksum is equal to SUM(all command bytes and of the zone number) & 0xFF
Keyword arguments:
command -- (bytearray) Command
zoneId -- (int) Zone ID
return: (int) Request checksum
"""
checkSum = 0
for byteCommand in command:
checkSum += byteCommand
checkSum += zoneId
return (checkSum & 0xFF)
################################### INIT ####################################
def __init__(self):
"""Class must be initialized with setup()"""
self.close()
################################### SETUP ####################################
def close(self):
"""Close connection with Milight wifi bridge"""
self.__initialized = False
self.__sequence_number = 0
try:
self.__sock.shutdown(socket.SHUT_RDWR)
self.__sock.close()
# logging.debug("Socket closed")
# If close before initialization, better handle attribute error
except AttributeError:
pass
def setup(self, ip, port=5987, timeout_sec=5.0):
"""Initialize the class (can be launched multiple time if setup changed or module crashed)
Keyword arguments:
ip -- (string) IP to communication with the Milight wifi bridge
port -- (int, optional) UDP port to communication with the Milight wifi bridge
timeout_sec -- (int, optional) Timeout in sec for Milight wifi bridge to answer commands
return: (bool) Milight wifi bridge initialized
"""
# Close potential previous Milight wifi bridge session
self.close()
# Create new milight wifi bridge session
try:
self.__sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
self.__ip = ip
self.__port = port
self.__sock.connect((self.__ip, self.__port))
self.__sock.settimeout(timeout_sec)
self.__initialized = True
# logging.debug("UDP connection initialized with ip {} and port {}".format(str(ip), str(port)))
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
# logging.error("Impossible to initialize the UDP connection with ip {} and port {}".format(str(ip), str(port)))
pass
return self.__initialized
######################### INTERNAL UTILITY FUNCTIONS #########################
def __startSession(self):
import logging
"""Send start session request and return start session information
return: (MilightWifiBridge.__START_SESSION_RESPONSE) Start session information containing response received,
mac address and session IDs
"""
# Send start session request
data_to_send = MilightWifiBridge.__START_SESSION_MSG
# logging.debug("Sending frame '{}' to {}:{}".format(str(binascii.hexlify(data_to_send)),
# str(self.__ip), str(self.__port)))
try:
self.__sock.sendto(data_to_send, (self.__ip, self.__port))
response = MilightWifiBridge.__START_SESSION_RESPONSE(responseReceived=False, mac="", sessionId1=-1, sessionId2=-1)
# Receive start session response
data, addr = self.__sock.recvfrom(1024)
if len(data) == 22:
# Parse valid start session response
response = MilightWifiBridge.__START_SESSION_RESPONSE(responseReceived=True,
mac=str("{}:{}:{}:{}:{}:{}".format(format(data[7], 'x'),
format(data[8], 'x'),
format(data[9], 'x'),
format(data[10], 'x'),
format(data[11], 'x'),
format(data[12], 'x'))),
sessionId1=int(data[19]),
sessionId2=int(data[20]))
return response
except socket.timeout:
pass
def __sendRequest(self, command, zoneId):
"""Send command to a specific zone and get response (ACK from the wifi bridge)
Keyword arguments:
command -- (bytearray) Command
zoneId -- (int) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = False
# Send request only if valid parameters
if len(bytearray(command)) == 9:
if int(zoneId) >= 0 and int(zoneId) <= 4:
startSessionResponse = self.__startSession()
try:
if startSessionResponse.responseReceived:
# For each request, increment the sequence number (even if the session ID is regenerated)
# Sequence number must be between 0x01 and 0xFF
self.__sequence_number = (self.__sequence_number + 1) & 0xFF
if self.__sequence_number == 0:
self.__sequence_number = 1
# Prepare request frame to send
bytesToSend = bytearray([0x80, 0x00, 0x00, 0x00, 0x11, startSessionResponse.sessionId1,
startSessionResponse.sessionId2, 0x00, int(self.__sequence_number), 0x00])
bytesToSend += bytearray(command)
bytesToSend += bytearray([int(zoneId), 0x00])
bytesToSend += bytearray([int(MilightWifiBridge.__calculateCheckSum(bytearray(command), int(zoneId)))])
# Send request frame
# logging.debug("Sending request with command '{}' with session ID 1 '{}', session ID 2 '{}' and sequence number '{}'"
# .format(str(binascii.hexlify(command)), str(startSessionResponse.sessionId1),
# str(startSessionResponse.sessionId2), str(self.__sequence_number)))
self.__sock.sendto(bytesToSend, (self.__ip, self.__port))
# Receive response frame
data, addr = self.__sock.recvfrom(64)
if len(data) == 8:
if data[6] == self.__sequence_number:
returnValue = True
except Exception:
returnValue = False
return returnValue
######################### PUBLIC FUNCTIONS #########################
def turnOn(self, zoneId):
"""Request 'Light on' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__ON_CMD, zoneId)
# logging.debug("Turn on zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def turnOff(self, zoneId):
"""Request 'Light off' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__OFF_CMD, zoneId)
# logging.debug("Turn off zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def turnOnWifiBridgeLamp(self):
"""Request 'Wifi bridge lamp on' to a zone
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__WIFI_BRIDGE_LAMP_ON_CMD, 0x01)
# logging.debug("Turn on wifi bridge lamp: {}".format(str(returnValue)))
return returnValue
def turnOffWifiBridgeLamp(self):
"""Request 'Wifi bridge lamp off'
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__WIFI_BRIDGE_LAMP_OFF_CMD, 0x01)
# logging.debug("Turn off wifi bridge lamp: {}".format(str(returnValue)))
return returnValue
def setNightMode(self, zoneId):
"""Request 'Night mode' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__NIGHT_MODE_CMD, zoneId)
# logging.debug("Set night mode to zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def setWhiteMode(self, zoneId):
"""Request 'White mode' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__WHITE_MODE_CMD, zoneId)
# logging.debug("Set white mode to zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def setWhiteModeBridgeLamp(self):
"""Request 'White mode' to the bridge lamp
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__WIFI_BRIDGE_LAMP_WHITE_MODE_CMD, 0x01)
# logging.debug("Set white mode to wifi bridge: {}".format(str(returnValue)))
return returnValue
def setDiscoMode(self, discoMode, zoneId):
"""Request 'Set disco mode' to a zone
Keyword arguments:
discoMode -- (int or MilightWifiBridge.eDiscoMode) Disco mode (9 modes available)
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetDiscoModeCmd(discoMode), zoneId)
# logging.debug("Set disco mode {} to zone {}: {}".format(str(discoMode), str(zoneId), str(returnValue)))
return returnValue
def setDiscoModeBridgeLamp(self, discoMode):
"""Request 'Set disco mode' to the bridge lamp
Keyword arguments:
discoMode -- (int or MilightWifiBridge.eDiscoMode) Disco mode (9 modes available)
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetDiscoModeForBridgeLampCmd(discoMode), 0x01)
# logging.debug("Set disco mode {} to wifi bridge: {}".format(str(discoMode), str(returnValue)))
return returnValue
def speedUpDiscoMode(self, zoneId):
"""Request 'Disco mode speed up' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__DISCO_MODE_SPEED_UP_CMD, zoneId)
#logging.debug("Speed up disco mode to zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def speedUpDiscoModeBridgeLamp(self):
"""Request 'Disco mode speed up' to the wifi bridge
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__WIFI_BRIDGE_LAMP_DISCO_MODE_SPEED_UP_CMD, 0x01)
#logging.debug("Speed up disco mode to wifi bridge: {}".format(str(returnValue)))
return returnValue
def slowDownDiscoMode(self, zoneId):
"""Request 'Disco mode slow down' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__DISCO_MODE_SLOW_DOWN_CMD, zoneId)
#logging.debug("Slow down disco mode to zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def slowDownDiscoModeBridgeLamp(self):
"""Request 'Disco mode slow down' to wifi bridge
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__WIFI_BRIDGE_LAMP_DISCO_MODE_SLOW_DOWN_CMD, 0x01)
#logging.debug("Slow down disco mode to wifi bridge: {}".format(str(returnValue)))
return returnValue
def link(self, zoneId):
"""Request 'Link' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__LINK_CMD, zoneId)
#logging.debug("Link zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def unlink(self, zoneId):
"""Request 'Unlink' to a zone
Keyword arguments:
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__UNLINK_CMD, zoneId)
#logging.debug("Unlink zone {}: {}".format(str(zoneId), str(returnValue)))
return returnValue
def setColor(self, color, zoneId):
"""Request 'Set color' to a zone
Keyword arguments:
color -- (int) Color (between 0x00 and 0xFF)
examples: 0xFF = Red, 0xD9 = Lavender, 0xBA = Blue, 0x85 = Aqua,
0x7A = Green, 0x54 = Lime, 0x3B = Yellow, 0x1E = Orange
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetColorCmd(color), zoneId)
#logging.debug("Set color {} to zone {}: {}".format(str(color), str(zoneId), str(returnValue)))
return returnValue
def setColorBridgeLamp(self, color):
"""Request 'Set color' to wifi bridge
Keyword arguments:
color -- (int) Color (between 0x00 and 0xFF)
examples: 0xFF = Red, 0xD9 = Lavender, 0xBA = Blue, 0x85 = Aqua,
0x7A = Green, 0x54 = Lime, 0x3B = Yellow, 0x1E = Orange
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetBridgeLampColorCmd(color), 0x01)
#logging.debug("Set color {} to wifi bridge: {}".format(str(color), str(returnValue)))
return returnValue
def setBrightness(self, brightness, zoneId):
"""Request 'Set brightness' to a zone
Keyword arguments:
brightness -- (int) Brightness in percentage (between 0 and 100)
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetBrightnessCmd(brightness), zoneId)
#logging.debug("Set brightness {}% to zone {}: {}".format(str(brightness), str(zoneId), str(returnValue)))
return returnValue
def setBrightnessBridgeLamp(self, brightness):
"""Request 'Set brightness' to the wifi bridge
Keyword arguments:
brightness -- (int) Brightness in percentage (between 0 and 100)
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetBrightnessForBridgeLampCmd(brightness), 0x01)
#logging.debug("Set brightness {}% to the wifi bridge: {}".format(str(brightness), str(returnValue)))
return returnValue
def setSaturation(self, saturation, zoneId):
"""Request 'Set saturation' to a zone
Keyword arguments:
brightness -- (int) Saturation in percentage (between 0 and 100)
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetSaturationCmd(saturation), zoneId)
#logging.debug("Set saturation {}% to zone {}: {}".format(str(saturation), str(zoneId), str(returnValue)))
return returnValue
def setTemperature(self, temperature, zoneId):
"""Request 'Set temperature' to a zone
Keyword arguments:
brightness -- (int or MilightWifiBridge.eTemperature) Temperature in percentage (between 0 and 100)
zoneId -- (int or MilightWifiBridge.eZone) Zone ID
return: (bool) Request received by the wifi bridge
"""
returnValue = self.__sendRequest(MilightWifiBridge.__getSetTemperatureCmd(temperature), zoneId)
#logging.debug("Set temperature {}% ({} kelvin) to zone {}: {}"
# .format(str(temperature), str(int(2700 + 38*temperature)), str(zoneId), str(returnValue)))
return returnValue
def getMacAddress(self):
"""Request the MAC address of the milight wifi bridge
return: (string) MAC address of the wifi bridge (empty if an error occured)
"""
returnValue = self.__startSession().mac
#logging.debug("Get MAC address: {}".format(str(returnValue)))
return returnValue
|
import numpy as np
class WeightedBinaryCrossEntropy(LossFunction):
"""Loss function which is used for binary-class classification with weighted samples."""
def get_type(self):
return 'weighted binary cross entropy'
def get(self, y, t, w):
error = -w * (t * np.log(y + self.ep) + (1 - t) * np.log(1 - y + self.ep))
return error.sum() / y.shape[0] |
/*
* Copyright (c) 2015 IBM Corporation and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.brunel.app;
import org.brunel.data.Dataset;
import org.brunel.data.io.CSV;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Created by graham on 8/19/15.
*/
public class DataSetMemoryTaken {
private static byte[] store;
public static void main(String[] args) throws FileNotFoundException {
// Load in the statics
Dataset kill = read(args[0]);
if (kill.rowCount() ==0) throw new IllegalStateException();
kill = null;
int initial = addTillDeath();
System.out.println("With Nothing:\t" + initial +"k");
Dataset d = read(args[0]);
int withData = addTillDeath();
System.out.println("With Data:\t" + withData +"k");
System.out.println("Dataset:\t" + (initial-withData) +"k");
if (d.fields.length ==0) throw new IllegalStateException();
}
private static Dataset read(String loc) throws FileNotFoundException {
String text = new Scanner(new FileInputStream(loc)).useDelimiter("\\A").next();
Dataset dataset = Dataset.make(CSV.read(text));
System.out.println("Expected Size = " + dataset.expectedSize()/1024 + "k");
return dataset;
}
private static int addTillDeath() {
final int BLOCK = 1024;
int max = 1;
try {
for (;;) {
store = null;
store = new byte[max*BLOCK];
store[store.length/2] = 3;
max++;
}
} catch (Throwable ignored) {
// Expected
}
// needed to make sure the store isn't optimized away
if (store != null && store[4] > 10000) throw new IllegalStateException();
return max;
}
}
|
#!/bin/sh
#
# Copyright (C) 2013 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This shell script is used to rebuild the libportable binaries from
# their sources. It requires a working NDK installation.
#
# include common function and variable definitions
. `dirname $0`/prebuilt-common.sh
. `dirname $0`/builder-funcs.sh
PROGRAM_PARAMETERS=""
PROGRAM_DESCRIPTION=\
"Rebuild libportable.a for the Android NDK.
This script builds libportable.a for app link with portable header.
This requires a platform.git/development and a temporary NDK installation
containing platforms and toolchain binaries for all target architectures.
By default, this will try with the current NDK directory, unless
you use the --ndk-dir=<path> option.
The output will be placed in appropriate sub-directories of
<ndk>/$LIBPORTABLE_SUBDIR, but you can override this with the --out-dir=<path>
option.
"
PACKAGE_DIR=
register_var_option "--package-dir=<path>" PACKAGE_DIR "Put prebuilt tarballs into <path>."
NDK_DIR=
register_var_option "--ndk-dir=<path>" NDK_DIR "Specify NDK root path for the build."
BUILD_DIR=
OPTION_BUILD_DIR=
register_var_option "--build-dir=<path>" OPTION_BUILD_DIR "Specify temporary build dir."
OUT_DIR=
register_var_option "--out-dir=<path>" OUT_DIR "Specify output directory directly."
ABIS="$PREBUILT_ABIS"
register_var_option "--abis=<list>" ABIS "Specify list of target ABIs."
NO_MAKEFILE=
register_var_option "--no-makefile" NO_MAKEFILE "Do not use makefile to speed-up build"
VISIBLE_LIBPORTABLE_STATIC=
register_var_option "--visible-libportable-static" VISIBLE_LIBPORTABLE_STATIC "Do not use hidden visibility for libportable.a"
GCC_VERSION=
register_var_option "--gcc-version=<ver>" GCC_VERSION "Specify GCC version"
LLVM_VERSION=
register_var_option "--llvm-version=<ver>" LLVM_VERSION "Specify LLVM version"
register_jobs_option
extract_parameters "$@"
ABIS=$(commas_to_spaces $ABIS)
# Handle NDK_DIR
if [ -z "$NDK_DIR" ] ; then
NDK_DIR=$ANDROID_NDK_ROOT
log "Auto-config: --ndk-dir=$NDK_DIR"
else
if [ ! -d "$NDK_DIR" ] ; then
echo "ERROR: NDK directory does not exists: $NDK_DIR"
exit 1
fi
fi
if [ -z "$OPTION_BUILD_DIR" ]; then
BUILD_DIR=$NDK_TMPDIR/build-libportable
else
BUILD_DIR=$OPTION_BUILD_DIR
fi
mkdir -p "$BUILD_DIR"
fail_panic "Could not create build directory: $BUILD_DIR"
# Location of the libportable source tree base
LIBPORTABLE_SRCDIR_BASE=$ANDROID_NDK_ROOT/../development/ndk/$LIBPORTABLE_SUBDIR
CPUFEATURE_SRCDIR=$ANDROID_NDK_ROOT/sources/android/cpufeatures
# Compiler flags we want to use
LIBPORTABLE_CFLAGS="-fPIC -O2 -DANDROID -D__ANDROID__ -ffunction-sections"
LIBPORTABLE_CFLAGS=$LIBPORTABLE_CFLAGS" -I$LIBPORTABLE_SRCDIR_BASE/common/include -I$CPUFEATURE_SRCDIR -D__HOST__"
LIBPORTABLE_CXXFLAGS="-fno-exceptions -fno-rtti"
LIBPORTABLE_LDFLAGS=""
# If the --no-makefile flag is not used, we're going to put all build
# commands in a temporary Makefile that we will be able to invoke with
# -j$NUM_JOBS to build stuff in parallel.
#
if [ -z "$NO_MAKEFILE" ]; then
MAKEFILE=$BUILD_DIR/Makefile
else
MAKEFILE=
fi
# build_libportable_for_abi
# $1: ABI
# $2: build directory
# $3: (optional) installation directory
build_libportable_libs_for_abi ()
{
local BINPREFIX
local ABI=$1
local BUILDDIR="$2"
local DSTDIR="$3"
local SRC OBJ OBJECTS CFLAGS CXXFLAGS
mkdir -p "$BUILDDIR"
# If the output directory is not specified, use default location
if [ -z "$DSTDIR" ]; then
DSTDIR=$NDK_DIR/$LIBPORTABLE_SUBDIR/libs/$ABI
fi
mkdir -p "$DSTDIR"
ARCH=$(convert_abi_to_arch $ABI)
if [ -n "$GCC_VERSION" ]; then
GCCVER=$GCC_VERSION
else
GCCVER=$(get_default_gcc_version_for_arch $ARCH)
fi
builder_begin_android $ABI "$BUILDDIR" "$GCCVER" "$LLVM_VERSION" "$MAKEFILE"
builder_set_srcdir "$LIBPORTABLE_SRCDIR"
builder_set_dstdir "$DSTDIR"
if [ -z "$VISIBLE_LIBLIBPORTABLE_STATIC" ]; then
# No -fvisibility-inlines-hidden because it is for C++, and there is
# no C++ code in libportable
builder_cflags "$LIBPORTABLE_CFLAGS" # ToDo: -fvisibility=hidden
else
builder_cflags "$LIBPORTABLE_CFLAGS"
fi
builder_ldflags "$LIBPORTABLE_LDFLAGS"
builder_sources $LIBPORTABLE_SOURCES
builder_set_srcdir "$CPUFEATURE_SRCDIR"
builder_sources $CPUFEATURE_SOURCES
log "Building $DSTDIR/libportable.a"
builder_static_library libportable
builder_end
# Extract __wrap functions and create a *.wrap file of "--wrap=symbol".
# This file will be passed to g++ doing the link in
#
# g++ -Wl,@/path/to/libportable.wrap
#
nm -a $DSTDIR/libportable.a | grep __wrap_ | awk '{print $3}' | sed '/^$/d' | \
sed 's/_wrap_/|/' | awk -F'|' '{print $2}' | sort | uniq | \
awk '{printf "--wrap=%s\n",$1}' > "$DSTDIR/libportable.wrap"
}
for ABI in $ABIS; do
# List of sources to compile
ARCH=$(convert_abi_to_arch $ABI)
LIBPORTABLE_SRCDIR=$LIBPORTABLE_SRCDIR_BASE/arch-$ARCH
LIBPORTABLE_SOURCES=$(cd $LIBPORTABLE_SRCDIR && ls *.[cS])
CPUFEATURE_SOURCES=$(cd $CPUFEATURE_SRCDIR && ls *.[cS])
build_libportable_libs_for_abi $ABI "$BUILD_DIR/$ABI" "$OUT_DIR"
done
# If needed, package files into tarballs
if [ -n "$PACKAGE_DIR" ] ; then
for ABI in $ABIS; do
FILES="$LIBPORTABLE_SUBDIR/libs/$ABI/libportable.*"
PACKAGE="$PACKAGE_DIR/libportable-libs-$ABI.tar.bz2"
log "Packaging: $PACKAGE"
pack_archive "$PACKAGE" "$NDK_DIR" "$FILES"
fail_panic "Could not package $ABI libportable binaries!"
dump "Packaging: $PACKAGE"
done
fi
if [ -z "$OPTION_BUILD_DIR" ]; then
log "Cleaning up..."
rm -rf $BUILD_DIR
else
log "Don't forget to cleanup: $BUILD_DIR"
fi
log "Done!"
|
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved.
*/
#include "pair.h"
struct double_pair {
struct pair *p1;
struct pair *p2;
};
int sum_double_pairs(struct double_pair *p) {
return sum(p->p1) + sum(p->p2);
}
|
export * from "./RegisterTokenButton";
|
#!/bin/bash
# check if the directory exists
if [ -d "/my_directory" ]; then
echo "Directory /my_directory exists."
else
echo "Directory /my_directory does not exist."
fi |
#!/usr/bin/env sh
bundle exec rails db:create
RAILS_ENV=test bundle exec rails db:create
bundle exec rails db:schema:load
bundle exec rails db:seed
rails db:environment:set RAILS_ENV=test
RAILS_ENV=test bundle exec rails db:schema:load
rails db:environment:set RAILS_ENV=test
RAILS_ENV=test bundle exec rails db:seed
|
<reponame>modzy/sdk-javascript<filename>src/api-error.js
const logger = require('log4js').getLogger("modzy");
/**
* Represent a error on the SDK
*/
class ApiError{
/**
* Create a ApiError
* @param {Error} error - the base error throwed by axios
* @param {string} url - the url of the Modzy Api
* @param {number} code - http error code
* @param {string} message - error message
*/
constructor(error=null, url="", code=500, message="Unexpected"){
this.error = error !== null ? error.toJSON() : message;
this.url = error !== null ? this.error.config.url : url;
this.code = error !== null ? ( error.response?.data ? error.response.data.statusCode : code ) : code;
this.message = error !== null ? ( error.response?.data ? error.response.data.message : this.error.message ) : message;
}
/**
* Convert this error to string
* @return {string} The string representation of this object
*/
toString(){
return `${this.code} :: ${this.message} :: ${this.url}`;
}
}
module.exports = ApiError; |
<gh_stars>0
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { CreateQuizQuestionPageRoutingModule } from './create-quiz-question-routing.module';
import { CreateQuizQuestionPage } from './create-quiz-question.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
CreateQuizQuestionPageRoutingModule
],
declarations: [CreateQuizQuestionPage]
})
export class CreateQuizQuestionPageModule {}
|
#
# Copyright 2019 Xilinx, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
export XPART=xcu200-fsgd2104-2-e
echo "XPART: $XPART"
export DEVICE=
echo "DEVICE: $DEVICE"
|
class InvalidCommandError(Exception):
pass
class RobotController:
def __init__(self):
self.x = 0
self.y = 0
self.direction = "N"
def execute_command(self, command):
if command == "F":
if self.direction == "N":
self.y += 1
elif self.direction == "S":
self.y -= 1
elif self.direction == "E":
self.x += 1
elif self.direction == "W":
self.x -= 1
elif command == "B":
if self.direction == "N":
self.y -= 1
elif self.direction == "S":
self.y += 1
elif self.direction == "E":
self.x -= 1
elif self.direction == "W":
self.x += 1
elif command == "L":
if self.direction == "N":
self.direction = "W"
elif self.direction == "S":
self.direction = "E"
elif self.direction == "E":
self.direction = "N"
elif self.direction == "W":
self.direction = "S"
elif command == "R":
if self.direction == "N":
self.direction = "E"
elif self.direction == "S":
self.direction = "W"
elif self.direction == "E":
self.direction = "S"
elif self.direction == "W":
self.direction = "N"
elif command == "S":
print(f"Current position: ({self.x}, {self.y}), Facing: {self.direction}")
else:
raise InvalidCommandError("Invalid command")
# Example usage
robot = RobotController()
robot.execute_command("F")
robot.execute_command("R")
robot.execute_command("F")
robot.execute_command("L")
robot.execute_command("B")
robot.execute_command("S") |
${BIN_DIR}/binomialOptions > stdout.txt 2> stderr.txt
|
<reponame>ituk-ttu/ITUK-API
package ee.ituk.api.common;
import java.util.UUID;
public class GlobalUtil {
private GlobalUtil() {
}
public static String generateCode() {
return UUID.randomUUID().toString().replace("-", "");
}
}
|
<filename>task_2.py
a=1
b=1
res=0
while a<4000000:
(a,b)=(a+b,a)
if a%2==0:
res+=a
print(res)
|
<reponame>ericdriggs/karate-parallel-runner-concurrent-access<gh_stars>0
function karateConfig() {
var env = karate.env; // get java system property 'karate.env'
karate.log('karate.env system property was:', env);
if (!env) {
env = 'dev'; // a custom 'intelligent' default
}
karate.log('env:', env);
var config = { // base config JSON
env: env
};
config = karate.callSingle('classpath:setup.feature', config);
karate.configure('connectTimeout', 300000);
karate.configure('readTimeout', 300000);
karate.configure('logPrettyResponse', true);
karate.configure('logPrettyRequest', true);
return config;
} |
#!/bin/bash
#PBS -P kv78
#PBS -l walltime=24:00:00
#PBS -l wd
#PBS -e /home/150/sxk150/qsub_error
#PBS -o /home/150/sxk150/qsub_out
#PBS -l ncpus=1
#PBS -M skurscheid@gmail.com
#PBS -m abe
#PBS -q express
#PBS -N kirc_fastq_processing_master
source ~/.bashrc
/short/rl2/miniconda3/envs/snakemake/bin/snakemake -s /home/150/sxk150/camda2019-workflows/Snakefile all_fastqProcessing_kirc\
--use-conda\
--cluster "qsub -P {cluster.P}\
-l ncpus={cluster.ncpus}\
-q {cluster.queue}\
-l mem={cluster.mem}\
-l wd\
-l walltime={cluster.walltime}\
-M {cluster.M}\
-m {cluster.m}\
-e {cluster.error_out_dir}\
-o {cluster.std1_out_dir}\
-N {cluster.name}"\
--jobs 128\
-d /short/kv78/\
--local-cores 1\
--cluster-config /home/150/sxk150/camda2019-workflows/cluster.json\
-pr
|
#!/bin/sh
. "${TEST_INIT:-./test-init.sh}"
if [ "$1" = 'actual' ]; then
mkdir .calcurse || exit 1
cp "$DATA_DIR/conf" .calcurse || exit 1
"$CALCURSE" -D "$PWD/.calcurse" -i "$DATA_DIR/ical-001.ical"
"$CALCURSE" -D "$PWD/.calcurse" -s01/01/1980 -r2
"$CALCURSE" -D "$PWD/.calcurse" -t
rm -rf .calcurse || exit 1
elif [ "$1" = 'expected' ]; then
cat <<EOD
Import process report: 0017 lines read
1 app / 0 events / 1 todo / 0 skipped
01/01/80:
- 00:01 -> ..:..
Calibrator's
01/02/80:
- ..:.. -> 09:18
Calibrator's
to do:
1. Nary parabled Louvre's fleetest mered
EOD
else
./run-test "$0"
fi
|
import re
s = "Hello World"
p = "W.*d"
m = re.match(p, s)
if m is not None:
print("Match found!")
print("Position: " + str(m.start()) + "," + str(m.end()))
print("Matched string: " + m.group())
else:
print("No match found!") |
import React, { useRef, useEffect } from 'react';
import { useFrame, useThree } from '@react-three/fiber';
import { lerp, mapRange } from 'canvas-sketch-util/math';
import {Mesh, ShaderMaterial, Material} from 'three';
import {useCurrentFrame, useVideoConfig, interpolate} from 'remotion';
import useStore from './store';
// import {noise1D} from './util';
import './SilkyMaterial';
//http://www.clicktorelease.com/blog/vertex-displacement-noise-3d-webgl-glsl-three-js/
export const Planet: React.FC<{
distortionScale: number
}> = ({ distortionScale }) => {
const frame = useCurrentFrame();
const {fps, width, height} = useVideoConfig();
const Random = useStore((state) => state.random);
const planet = useRef<Mesh>();
const { size } = useThree();
const distortFactor = 1;
const melodyRef = useRef<number>(0.2);
useEffect(() => {
const elapsedTime = frame/fps;
if (planet.current) {
planet.current.material.uniforms.u_resolution.value = [
width,
height,
];
planet.current.material.uniforms.u_music.value =
distortionScale * (Math.sin(elapsedTime)/20);
// distortionScale * melodyRef.current;
planet.current.material.uniforms.u_time.value = elapsedTime;
planet.current.material.uniforms.u_distort.value = distortFactor;
const off = Random.noise1D(elapsedTime, 0.25);
// const off = noise1D(elapsedTime, 0.25, 1, 1)
// const tOff = mapRange(off, -1, 1, 0, 1);
const tOff = interpolate(off, [-1, 1], [0, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
planet.current.rotation.x = lerp(0.1, 0.8, tOff);
planet.current.rotation.y = lerp(0.4, 1.2, tOff);
planet.current.rotation.z = lerp(0.8, 1.6, tOff);
}
}, [frame]);
return (
<mesh ref={planet} scale={[10, 10, 10]}>
<icosahedronBufferGeometry args={[1, 60]} />
<silkyMaterial />
</mesh>
);
} |
/*
* create_messages_table.sql
* Chapter 11, Oracle10g PL/SQL Programming
* by <NAME>, <NAME> and <NAME>
*
* This script builds table an object for DBMS_ALERT triggers.
*/
BEGIN
FOR i IN (SELECT null
FROM user_tables
WHERE table_name = 'MESSAGES') LOOP
EXECUTE IMMEDIATE 'DROP TABLE messages CASCADE CONSTRAINTS';
END LOOP;
END;
/
BEGIN
FOR i IN (SELECT null
FROM user_tables
WHERE table_name = 'MESSAGES_ALERTS') LOOP
EXECUTE IMMEDIATE 'DROP TABLE messages_alerts CASCADE CONSTRAINTS';
END LOOP;
END;
/
CREATE TABLE messages
(message_id INTEGER NOT NULL
,message_source VARCHAR2(30 CHAR) NOT NULL
,message_destination VARCHAR2(30 CHAR) NOT NULL
,message VARCHAR2(30 CHAR) NOT NULL
,CONSTRAINT message_pk PRIMARY KEY (message_id));
INSERT
INTO messages
VALUES (1,'PLSQL','USERA','Keep your powder dry!');
INSERT
INTO messages
VALUES (2,'PLSQL','USERA','Meet yourself in St. Louis');
INSERT
INTO messages
VALUES (3,'PLSQL','USERA','Cry in your coffee.');
CREATE TABLE messages_alerts
(message VARCHAR2(30 CHAR) NOT NULL);
|
import React from 'react'
import Layout from '../../components/layout'
import {graphql, StaticQuery} from 'gatsby'
import Img from 'gatsby-image'
import "../../styles/items.scss"
import {Link} from 'gatsby'
import withLocation from '../../components/withLocation'
import PropTypes from 'prop-types'
const barang = ({search}) => {
const { item } = search;
const bolditem = <b>{item}</b>
return(
<StaticQuery
query={graphql`
query SearchQuery {
products: allDatoCmsProduct(limit: 5000) {
edges {
node {
id
name
pricetext
shortdescription
description
productseo
genre{
id
genreseo
}
image {
url
sizes(maxWidth: 300, imgixParams: { fm: "jpg" }) {
...GatsbyDatoCmsSizes
}
}
}
}
}
categories: allDatoCmsGenre {
edges {
node {
id
name
genreseo
}
}
}
}
`}
render={data => (
<Layout>
<div className="cookie__crumble">
<span><Link to="/" className="cookie__link">Home</Link> / Produk</span>
</div>
<div className="products__container">
<div className="sidenav">
<span className="sidenav__title">kategori</span>
<div className="kategori__list">
<ul>
{data.categories.edges.map(({node: category})=> (
<Link className="link" to={`/products/${category.genreseo}`}>
<li key={category.id}>{category.name}</li>
</Link>
))}
</ul>
</div>
</div>
<div className="content">
<div className="item__count">
<span> {data.products.edges.filter(({node: produk}) => produk.name.toLowerCase().includes(item)).length} barang</span>
</div>
<span className="list__info">{data.products.edges.filter(({node: produk}) => produk.name.toLowerCase().includes(item)).length == 0 ? "Hasil pencarian tidak ditemukan" : `Hasil pencarian "${item}"` }</span>
<div className="items">
{data.products.edges.filter(({node: product}) => product.name.toLowerCase().includes(item)).map(({node: product}) => (
<Link className="link" to={`/product/${product.productseo}-${product.genre.genreseo}/`}>
<div className="list__container">
<div className="list__image">
<Img sizes={product.image.sizes} />
</div>
<div className="list__content">
<span className="list__title">{product.name}</span>
<span className="list__desc">{product.shortdescription}</span>
<span className="list__desc">{product.descriptionukuran}</span>
<span className="list__price">Rp{product.pricetext}</span>
</div>
</div>
</Link>
))}
</div>
</div>
</div>
</Layout>
)}
/>
)
}
barang.propTypes = {
search: PropTypes.object,
}
export default withLocation(barang) |
export { default as Card, CardSet } from './src/Card.js'
export { default as Player } from './src/Player.js'
export { default } from './src/Game.js'
export * as Details from './src/Details.js'
|
<gh_stars>1-10
/**
* Type annotation for `Color` prop
* @see https://developer.apple.com/documentation/apple_news/color
*/
export type Color = string;
/**
* `Color` prop validation lambda function. Adheres to official document spec
* @param {AppleNews.Color} s
* @returns {AppleNews.Color|undefined} The color string, if it's valid. Undefined if not.
* @see https://developer.apple.com/documentation/apple_news/color
*/
export const Color =
(s: Color): Color | undefined =>
!!(String(s)!.match(/^(\#\w{8})|(\#\w{6})|(\#\w{4})|(\#\w{3})|([a-z]{0,20})$/)![0] === s)
? s
: void 0;
|
#!/usr/bin/env bash
rm /tmp/alice2.log
touch /tmp/alice2.log
tail -f /tmp/alice2.log |
<reponame>chen19901225/vscode-file-watcher
import * as vscode from "vscode";
export default class StatusBar {
private _statusBarItem: vscode.StatusBarItem;
private _errorColor: vscode.ThemeColor;
private _normalColor: string | vscode.ThemeColor | undefined;
constructor() {
const priority: number = 1000;
this._statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, priority);
this._errorColor = new vscode.ThemeColor("filewatcher.error");
this._normalColor = this._statusBarItem.color;
}
/**
* Show message in status bar
*/
public showMessage(message: string): void {
this._statusBarItem.color = this._normalColor;
this._statusBarItem.text = message;
this._statusBarItem.show();
}
/**
* Show error in status bar
*/
public showError(): void {
const stopIcon: string = "$(stop)";
this._statusBarItem.color = this._errorColor;
this._statusBarItem.text = `${stopIcon} File Watcher Error`;
this._statusBarItem.show();
}
}
|
<reponame>jae1911/newer.jae.fi
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import Link from 'next/link'
import Clock from 'react-live-clock'
import os from 'os';
// Custom components
import Art from 'components/art'
const Home: NextPage = () => {
let network = os.hostname();
return (
<div>
<Head>
<title>Jae's website</title>
<meta name="description" content="Official website of Jae" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="main crt">
<Art />
<br/>
<p><Link href="/">Return to the index</Link></p>
<br/>
<p>All pictures in those albums are under the <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="noreferrer">CC-BY-SA 4.0</a> license.</p>
<br/>
<p>- All the current photo albums -</p>
<ul>
<li><a href="https://pix.jae.fi/s/jae/landscape" rel="noreferrer" target="_blank">Landscapes</a></li>
<li><a href="https://pix.jae.fi/s/jae/city" rel="noreferrer" target="_blank">City</a></li>
<li><a href="https://pix.jae.fi/s/jae/misc" rel="noreferrer" target="_blank">Misc</a></li>
<li><a href="https://pix.jae.fi/s/jae/infrastructure" rel="noreferrer" target="_blank">Infrastructure</a></li>
</ul>
</div>
</div>
)
}
export default Home
|
export class ForceSimulationAnalizer{
constructor() {
this._find = {
text: ""
}
this._background = {
color: "white"
}
this._link = {
colorScale: "default"
}
this.analizerDiv = d3.select("body").append("div").attr('id', "forceAnalizers");
this.findDiv = this.analizerDiv.append("div").classed("analize", true);
this.findDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("find");
this.findDivLabel = this.findDiv.append("div").append("label").html("find:");
this.findDivOutput = this.findDivLabel.append("output").html(this._find.text);
this.findDiv.append("input")
.attr('type', "text")
.attr("value", this._find.text)
.classed("text", true)
.attr('id', "textValue")
.on("change", ()=>{this.update()});
this.findDiv.append("input")
.attr('type', "button")
.attr("value", "find")
.attr('id', "findButton")
this.backGroundDiv = this.analizerDiv.append("div").classed("analize", true);
this.backGroundDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("background");
this.backGroundDivSelect = this.backGroundDiv.append("select")
.attr('id', "backgroundValue")
.on("change", ()=>{this.update()});
this.backGroundDivSelect.append("option").attr("value", "white").html("white");
this.backGroundDivSelect.append("option").attr("value", "black").html("black");
this.backGroundDiv.append("input")
.attr('type', "button")
.attr("value", "apply")
.attr('id', "backgroundButton")
this.linkDiv = this.analizerDiv.append("div").classed("analize", true);
this.linkDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("link");
this.linkDivLabel = this.linkDiv.append("div").append("label").html("coloring");
this.linkDivSelect = this.linkDiv.append("select")
.attr('id', "linkValue")
.on("change", ()=>{this.update()});
this.linkDivSelect.append("option").attr("value", null).html("black");
this.linkDivSelect.append("option").attr("value", "interpolateBrBG").html("interpolateBrBG");
this.linkDivSelect.append("option").attr("value", "interpolatePRGn").html("interpolatePRGn");
this.linkDivSelect.append("option").attr("value", "interpolatePiYG").html("interpolatePiYG");
this.linkDivSelect.append("option").attr("value", "interpolatePuOr").html("interpolatePuOr");
this.linkDivSelect.append("option").attr("value", "interpolateRdBu").html("interpolateRdBu");
this.linkDivSelect.append("option").attr("value", "interpolateRdGy").html("interpolateRdGy");
this.linkDivSelect.append("option").attr("value", "interpolateRdYlBu").html("interpolateRdYlBu");
this.linkDivSelect.append("option").attr("value", "interpolateRdYlGn").html("interpolateRdYlGn");
this.linkDivSelect.append("option").attr("value", "interpolateSpectral").html("interpolateSpectral");
this.linkDivSelect.append("option").attr("value", "interpolateBlues").html("interpolateBlues");
this.linkDivSelect.append("option").attr("value", "interpolateGreens").html("interpolateGreens");
this.linkDivSelect.append("option").attr("value", "interpolateGreys").html("interpolateGreys");
this.linkDivSelect.append("option").attr("value", "interpolateOranges").html("interpolateOranges");
this.linkDivSelect.append("option").attr("value", "interpolatePurples").html("interpolatePurples");
this.linkDivSelect.append("option").attr("value", "interpolateReds").html("interpolateReds");
this.linkDivSelect.append("option").attr("value", "interpolateViridis").html("interpolateViridis");
this.linkDivSelect.append("option").attr("value", "interpolateInferno").html("interpolateInferno");
this.linkDivSelect.append("option").attr("value", "interpolateMagma").html("interpolateMagma");
this.linkDivSelect.append("option").attr("value", "interpolatePlasma").html("interpolatePlasma");
this.linkDivSelect.append("option").attr("value", "interpolateWarm").html("interpolateWarm");
this.linkDivSelect.append("option").attr("value", "interpolateCool").html("interpolateCool");
this.linkDivSelect.append("option").attr("value", "interpolateCubehelixDefault").html("interpolateCubehelixDefault");
this.linkDivSelect.append("option").attr("value", "interpolateBuGn").html("interpolateBuGn");
this.linkDivSelect.append("option").attr("value", "interpolateBuPu").html("interpolateBuPu");
this.linkDivSelect.append("option").attr("value", "interpolateGnBu").html("interpolateGnBu");
this.linkDivSelect.append("option").attr("value", "interpolateOrRd").html("interpolateOrRd");
this.linkDivSelect.append("option").attr("value", "interpolatePuBuGn").html("interpolatePuBuGn");
this.linkDivSelect.append("option").attr("value", "interpolatePuBu").html("interpolatePuBu");
this.linkDivSelect.append("option").attr("value", "interpolatePuRd").html("interpolatePuRd");
this.linkDivSelect.append("option").attr("value", "interpolateRdPu").html("interpolateRdPu");
this.linkDivSelect.append("option").attr("value", "interpolateYlGnBu").html("interpolateYlGnBu");
this.linkDivSelect.append("option").attr("value", "interpolateYlGn").html("interpolateYlGn");
this.linkDivSelect.append("option").attr("value", "interpolateYlOrBr").html("interpolateYlOrBr");
this.linkDivSelect.append("option").attr("value", "interpolateYlOrRd").html("interpolateYlOrRd");
this.linkDivSelect.append("option").attr("value", "interpolateRainbow").html("interpolateRainbow");
this.linkDiv.append("input")
.attr('type', "button")
.attr("value", "apply")
.attr('id', "linkButton")
}
update(){
this._find = {
text: d3.select("#textValue").property("value")
}
this.findDivOutput.html(this._find.text);
this._link = {
colorScale: d3.select("#linkValue").property("value")
}
this._background = {
color: d3.select("#backgroundValue").property("value")
}
}
get find(){
return this._find;
}
set find(val){
this._find = val;
}
get link(){
return this._link;
}
set link(val){
this._link = val;
}
get background(){
return this._background;
}
set background(val){
this._background = val;
}
} |
<reponame>Alex-Diez/java-tdd-Katas
package kata.java;
import java.util.List;
import io.reactivex.Observable;
public class RxFizzBuzz {
public List<String> fizzBuzz(Integer... numbers) {
return Observable.fromArray(numbers)
.map(n -> toStringIfEmpty(n, toFizzOrEmpty(n) + toBuzzOrEmpty(n)))
.toList()
.blockingGet();
}
private String toStringIfEmpty(int n, String val) {
return val.isEmpty() ? String.valueOf(n) : val;
}
private String toFizzOrEmpty(int n) {
return n % 3 == 0 ? "Fizz" : "";
}
private String toBuzzOrEmpty(int n) {
return n % 5 == 0 ? "Buzz" : "";
}
}
|
<reponame>samuel/go-dsp
package dsp
type ComplexSource interface {
Source() ([]complex64, error)
}
type RealSink interface {
Sink([]float32) error
}
type ComplexFilter interface {
Filter([]complex64) ([]complex64, error)
}
type Demodulator interface {
Demodulate(input []complex64, output []float32) (int, error)
}
type Rotate90Filter struct {
}
func (fi *Rotate90Filter) Filter(samples []complex64) []complex64 {
return rotate90FilterAsm(fi, samples)
}
func rotate90FilterAsm(fi *Rotate90Filter, samples []complex64) []complex64
func rotate90Filter(fi *Rotate90Filter, samples []complex64) []complex64 {
for i := 0; i < len(samples); i += 4 {
samples[i+1] = complex(-imag(samples[i+1]), real(samples[i+1]))
samples[i+2] = -samples[i+2]
samples[i+3] = complex(imag(samples[i+3]), -real(samples[i+3]))
}
return samples
}
type I32Rotate90Filter struct {
}
func (fi *I32Rotate90Filter) Filter(samples []int32) []int32 {
return i32Rotate90FilterAsm(fi, samples)
}
func i32Rotate90FilterAsm(fi *I32Rotate90Filter, samples []int32) []int32
func i32Rotate90Filter(fi *I32Rotate90Filter, samples []int32) []int32 {
for i := 0; i < len(samples); i += 8 {
samples[i+2], samples[i+3] = -samples[i+3], samples[i+2]
samples[i+4] = -samples[i+4]
samples[i+5] = -samples[i+5]
samples[i+6], samples[i+7] = samples[i+7], -samples[i+6]
}
return samples
}
func rtoc(r []float64) []complex128 {
c := make([]complex128, len(r))
for i, v := range r {
c[i] = complex(v, 0)
}
return c
}
func rtoc32(r []float32) []complex64 {
c := make([]complex64, len(r))
for i, v := range r {
c[i] = complex(v, 0)
}
return c
}
|
<reponame>developedbygeo/Crypto-Checker
import { cryptoSymbol } from 'crypto-symbol';
const { nameLookup } = cryptoSymbol({});
function closeError() {
const errorDiv = this.parentElement.parentElement;
errorDiv.classList.toggle('error-wrapper-active');
}
function handleError(err = '') {
const errorDiv = document.querySelector('.error-wrapper');
const errorMsg = document.querySelector('.error-msg');
if (err !== '') {
errorMsg.textContent = err;
} else {
errorMsg.textContent = 'Something went wrong!';
}
errorDiv.classList.add('error-wrapper-active');
}
function submitQuery(e) {
const queryPair = e.target.parentElement[1].value;
let queryText = nameLookup(e.target.parentElement[0].value);
if (queryText === undefined) {
queryText = e.target.parentElement[0].value;
}
return { coin: queryText.toLowerCase(), pair: queryPair };
}
function convertToCurrency(value) {
let str;
// Evaluation
if (Number(value) >= 1.0e12) {
str = `${(Math.abs(Number(value)) / 1.0e12).toFixed(2)}T`;
} else if (Number(value) >= 1.0e9) {
str = `${(Math.abs(Number(value)) / 1.0e9).toFixed(2)}B`;
} else if (Number(value) >= 1.0e6) {
str = `${(Math.abs(Number(value)) / 1.0e9).toFixed(2)}B`;
} else if (Number(value) >= 1.0e3) {
str = `${(Math.abs(Number(value)) / 1.0e3).toFixed(2)}K`;
} else if (Number.isNaN(value)) {
str = `Unavailable`;
} else {
str = Math.abs(Number(value));
}
return str;
}
export { closeError, handleError, submitQuery, convertToCurrency };
|
#
# This file is part of KwarqsDashboard.
#
# KwarqsDashboard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# KwarqsDashboard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with KwarqsDashboard. If not, see <http://www.gnu.org/licenses/>.
#
import os
import cairo
import gtk
import glib
data_dir = os.path.join(os.path.dirname(__file__), 'data')
def initialize_from_xml(this, other=None):
'''
Initializes the widgets and signals from a GtkBuilder XML file. Looks
for the following attributes in the instance you pass:
ui_filename = builder filename
ui_widgets = [list of widget names]
ui_signals = [list of function names to connect to a signal]
For each widget in ui_widgets, it will be retrieved from the builder
object and
other is a list of widgets to also initialize with the same file
Returns the builder object when done
'''
builder = gtk.Builder()
builder.add_from_file(os.path.join(data_dir, this.ui_filename))
objects = [this]
if other is not None:
objects.extend(other)
for obj in objects:
if hasattr(obj, 'ui_widgets') and obj.ui_widgets is not None:
for widget_name in obj.ui_widgets:
widget = builder.get_object(widget_name)
if widget is None:
raise RuntimeError("Widget '%s' is not present in '%s'" % (widget_name, this.ui_filename))
setattr(obj, widget_name, widget)
signals = None
for obj in objects:
if hasattr(obj, 'ui_signals') and obj.ui_signals is not None:
if signals is None:
signals = {}
for signal_name in obj.ui_signals:
if not hasattr(obj, signal_name):
raise RuntimeError("Function '%s' is not present in '%s'" % (signal_name, obj))
signals[signal_name] = getattr(obj, signal_name)
if signals is not None:
missing = builder.connect_signals(signals, None)
if missing is not None:
err = 'The following signals were found in %s but have no assigned handler: %s' % (this.ui_filename, str(missing))
raise RuntimeError(err)
return builder
def replace_widget(old_widget, new_widget):
# TODO: This could be better
parent = old_widget.get_parent()
packing = None
position = None
try:
position = parent.child_get_property(old_widget, 'position')
except:
pass
try:
packing = parent.query_child_packing(old_widget)
except:
pass
child_options = {}
try:
# save/restore table options
for prop in ['bottom-attach', 'left-attach', 'right-attach', 'top-attach', 'x-options', 'x-padding', 'y-options', 'y-padding']:
child_options[prop] = parent.child_get_property(old_widget, prop)
except:
pass
try:
# save/restore fixed options
for prop in ['x', 'y']:
child_options[prop] = parent.child_get_property(old_widget, prop)
except:
pass
parent.remove(old_widget)
new_widget.unparent()
parent.add(new_widget)
if len(child_options) != 0:
for k, v in child_options.iteritems():
parent.child_set_property(new_widget, k, v)
if position is not None:
parent.child_set_property(new_widget, 'position', position)
if packing is not None:
parent.set_child_packing(new_widget, *packing)
return new_widget
def pixbuf_from_stock(stock_id, stock_size):
render_widget = gtk.Button()
return render_widget.render_icon(stock_id, stock_size)
def pixbuf_from_file(filename):
return gtk.gdk.pixbuf_new_from_file(os.path.join(data_dir, filename))
def surface_from_png(filename):
return cairo.ImageSurface.create_from_png(os.path.join(data_dir, filename))
def get_directory(default=None):
dialog = gtk.FileChooserDialog("Open directory", action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
if default is not None:
dialog.set_current_folder(default)
response = dialog.run()
if response != gtk.RESPONSE_OK:
return None
ret = dialog.get_filename()
dialog.destroy()
return ret
def get_text(parent, message, default='', validator=None):
"""
Display a dialog with a text entry.
Returns the text, or None if canceled.
Modified from http://stackoverflow.com/questions/8290740/
"""
d = gtk.MessageDialog(parent,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_OK_CANCEL,
message)
entry = gtk.Entry()
entry.set_text(default)
entry.show()
d.vbox.pack_end(entry)
entry.connect('activate', lambda _: d.response(gtk.RESPONSE_OK))
d.set_default_response(gtk.RESPONSE_OK)
while True:
r = d.run()
text = entry.get_text()
if r != gtk.RESPONSE_OK:
text = None
break
if validator is not None:
response = validator(text)
if response is not True:
d.format_secondary_markup('<b>ERROR</b>: <span foreground="red">%s</span>' %
glib.markup_escape_text(response))
entry.grab_focus()
continue
break
d.destroy()
return text
def show_error(parent, message):
'''Shows an error message to the user'''
dialog = gtk.MessageDialog(parent, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE)
dialog.set_property('text',message)
dialog.run()
dialog.destroy()
def yesno(parent, message):
'''Gets a Yes/No response from a user'''
dlg = gtk.MessageDialog(parent=parent, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format=message)
response = dlg.run()
dlg.destroy()
return response
|
<gh_stars>0
// Copyright ©2016 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mathext
import "github.com/ArkaGPL/gonum/mathext/internal/gonum"
// Beta returns the value of the complete beta function B(a, b). It is defined as
// Γ(a)Γ(b) / Γ(a+b)
// Special cases are:
// B(a,b) returns NaN if a or b is Inf
// B(a,b) returns NaN if a and b are 0
// B(a,b) returns NaN if a or b is NaN
// B(a,b) returns NaN if a or b is < 0
// B(a,b) returns +Inf if a xor b is 0.
//
// See http://mathworld.wolfram.com/BetaFunction.html for more detailed informations.
func Beta(a, b float64) float64 {
return gonum.Beta(a, b)
}
// Lbeta returns the natural logarithm of the complete beta function B(a,b).
// Lbeta is defined as:
// Ln(Γ(a)Γ(b)/Γ(a+b))
// Special cases are:
// Lbeta(a,b) returns NaN if a or b is Inf
// Lbeta(a,b) returns NaN if a and b are 0
// Lbeta(a,b) returns NaN if a or b is NaN
// Lbeta(a,b) returns NaN if a or b is < 0
// Lbeta(a,b) returns +Inf if a xor b is 0.
func Lbeta(a, b float64) float64 {
return gonum.Lbeta(a, b)
}
|
<gh_stars>0
#<pycode_BC695(py_frame)>
add_auto_stkpnt2=add_auto_stkpnt
# in fact, we cannot simulate add_stkvar[23] here, because we simply
# don't have the insn_t object -- and no way of retrieving it, either,
# since cmd is gone
def get_stkvar(*args):
if len(args) == 2:
import ida_ua
insn, op, v = ida_ua.cmd, args[0], args[1]
else:
insn, op, v = args
return _ida_frame.get_stkvar(insn, op, v)
def get_frame_part(*args):
import ida_funcs
if isinstance(args[0], ida_funcs.func_t): # 6.95: pfn, part, range
rnge, pfn, part = args[2], args[0], args[1]
else: # 7.00: range, pfn, part
rnge, pfn, part = args
return _ida_frame.get_frame_part(rnge, pfn, part)
#</pycode_BC695(py_frame)>
|
import importlib
import pkgutil
from typing import List
def import_all_modules(package_name: str) -> List[str]:
imported_modules = []
package = importlib.import_module(package_name)
for _, module_name, _ in pkgutil.walk_packages(package.__path__, prefix=package.__name__ + '.'):
imported_module = importlib.import_module(module_name)
imported_modules.append(imported_module.__name__)
return imported_modules |
<reponame>pritam19798/BPCS-Steganography<filename>stegano.py
#!/usr/bin/python3
import argparse
import cv2
import math
import numpy as np
from bpcs import BPCS
from error import ImageNotFoundError,BitplaneOverflowError
from message import Message
def psnr(img1, img2):
rms = math.sqrt(np.sum((img1.astype('float') - img2.astype('float')) ** 2) / np.prod(img1.shape))
return 20 * math.log10(256 / rms)
def create_arguments():
parser = argparse.ArgumentParser(
description='A BPCS-based algorithm Steganography Program'
)
parser.add_argument("original_img", help="The original image path that you will put a hidden message")
parser.add_argument("secret_message", help="Your secret message file path. The message must be stored inside a file.")
parser.add_argument("threshold", help="Treshold in BPCS algorithm", type=float)
parser.add_argument("-e", "--extract", help="Extract the secret message from a stegano image. \n If this option is used, <original_image> argument is treated as <stegano_image> and <secret_message> will become the stored secret message path", action="store_true")
parser.add_argument("-o", "--output", help="Stegano Image output. The image that has a hidden message stored inside.")
return parser.parse_args()
def extract(args):
try:
bpcs = BPCS(args.original_img)
except ImageNotFoundError:
print("Image Not Found Please Give Right File Path!!!")
return
bitplane_msg = bpcs.show( threshold = args.threshold)
msg = Message()
msg.from_bitplane_array(bitplane_msg)
msg.write_msg(args.secret_message)
return
# create stegano image
def create(args):
try:
bpcs = BPCS(args.original_img)
except ImageNotFoundError:
print("Image Not Found Please Give Right File Path!!!")
return
orig_extension = args.original_img.split('.')[-1]
try:
msg = Message(pathname=args.secret_message, threshold = args.threshold)
except FileNotFoundError:
print("Message File Not Found Please Give Right File Path!!!")
return
bitplane_msg = msg.create_message()
#print(bitplane_msg[:10])
try:
img_result = bpcs.hide(bitplane_msg, threshold = args.threshold)
except BitplaneOverflowError:
print("Carrier image don't have much bit plan with complexcity more than {} to store all message bit plane !!!".format(args.threshold))
return
if args.output == None:
args.output = 'output'
args.output += "." + orig_extension
cv2.imwrite(args.output, img_result)
origin_image = cv2.imread(args.original_img, -1)
embed_image = cv2.imread(args.output,-1)
psnr_value = psnr(origin_image, embed_image)
print("PSNR: {}".format(psnr_value))
# show embedded & original image
cv2.imshow('Original Image', origin_image)
cv2.imshow("Embedded Image (PSNR: {})".format(psnr_value),embed_image)
cv2.waitKey(0)
return
if __name__ == '__main__':
args = create_arguments()
#print(args)
#print("Original Image: {}".format(args.original_img))
if args.extract:
extract(args)
else:
create(args)
|
<reponame>chenhaitian001/springboot<filename>src/main/java/com/four/server/bsm/impl/RecordBsmImpl.java
/* 1: */ package com.four.server.bsm.impl;
/* 2: */
/* 3: */ import com.four.common.tpm.RecordTpm;
/* 4: */ import com.four.common.tpm.UserTpm;
/* 5: */ import com.four.server.bsm.RecordBsm;
/* 6: */ import com.four.server.dsm.RecordDsm;
/* 7: */ import java.util.ArrayList;
/* 8: */ import java.util.List;
/* 9: */ import org.springframework.beans.factory.annotation.Autowired;
/* 10: */ import org.springframework.context.annotation.Scope;
/* 11: */ import org.springframework.stereotype.Repository;
/* 12: */
/* 13: */ @Scope("singleton")
/* 14: */ @Repository("recordBsm")
/* 15: */ public class RecordBsmImpl
/* 16: */ implements RecordBsm
/* 17: */ {
/* 18: */ @Autowired
/* 19: */ RecordDsm recordDsm;
/* 20: */
/* 21: */ public boolean saveRecords(List<RecordTpm> records)
/* 22: */ {
/* 23:32 */ if ((records == null) || (records.size() == 0)) {
/* 24:33 */ return true;
/* 25: */ }
/* 26:35 */ int SQL_BATCH = 200;
/* 27:36 */ int SIZE = records.size();
/* 28:37 */ for (int i = 0; i < SIZE; i += 200)
/* 29: */ {
/* 30:38 */ int fromIndex = i;
/* 31:39 */ int toIndex = fromIndex + 200;
/* 32:40 */ toIndex = toIndex > SIZE ? SIZE : toIndex;
/* 33:41 */ this.recordDsm.insertRecords(records.subList(fromIndex, toIndex));
/* 34: */ }
/* 35:44 */ return true;
/* 36: */ }
/* 37: */
/* 38: */ public UserTpm getUserByCardId(String cardId)
/* 39: */ {
/* 40:49 */ return this.recordDsm.getUserByCardId(cardId);
/* 41: */ }
/* 42: */
/* 43: */ public List<UserTpm> getUserByCardIds(List<String> cardIds)
/* 44: */ {
/* 45:54 */ if ((cardIds == null) || (cardIds.size() == 0)) {
/* 46:55 */ return null;
/* 47: */ }
/* 48:58 */ List<UserTpm> userTpmList = new ArrayList();
/* 49:59 */ int step = 500;
/* 50:60 */ int size = cardIds.size();
/* 51:61 */ for (int i = 0; i < size; i += 500)
/* 52: */ {
/* 53:62 */ int fromIndex = i;
/* 54:63 */ int toIndex = fromIndex + 500;
/* 55:64 */ toIndex = toIndex > size ? size : toIndex;
/* 56:65 */ List<UserTpm> sub = this.recordDsm.getUserByCardIds(cardIds.subList(fromIndex, toIndex));
/* 57:66 */ if (sub != null) {
/* 58:67 */ userTpmList.addAll(sub);
/* 59: */ }
/* 60: */ }
/* 61:71 */ return userTpmList;
/* 62: */ }
/* 63: */ }
/* Location: E:\Henuo\public\public\bin\convertdata-1.0.jar
* Qualified Name: com.four.server.bsm.impl.RecordBsmImpl
* JD-Core Version: 0.7.0.1
*/ |
<gh_stars>0
export const formatPath = (path: string) => {
// \ を / に置換
path.replace(/\\/g, "/");
// テストファイルのパスを整形(末尾に\または/があれば削除)
const lastCharOfPath = path.substring(path.length - 1);
if (lastCharOfPath == "\\" || lastCharOfPath == "/") {
path = path.substring(0, path.length - 1);
}
} |
<gh_stars>0
function greeter(person:string) {
return "Hello, " + person;
}
let user = "<NAME>";
var url = "https://en.wikipedia.org/w/api.php";
var params = {
action: "query",
format: "json",
list: "logevents",
lelimit: "3",
letitle: "Ocala, Florida",
//leaction: "protect/protect",
};
url = url + "?origin=*";
Object.keys(params).forEach(function(key){url += "&" + key + "=" + params[key];});
var PromiseA = fetch(url).then(function(response){return response.json();}).then(function(response) {
return response.query.logevents}).then(function(response) {
var events = response;
var first_event_type:string;
var first_event_title:string;
var c:number = 0;
for (var l in events) {
c = c + 1;
first_event_type = events[l].type;
first_event_title = events[l].title;
}
//document.body.textContent = greeter(user);
document.body.textContent = " Type: " + first_event_type + " Title: " + first_event_title + " Number of Events: " + c;
}).catch(function(error){console.log(error);});
|
<reponame>mwouts/world_bank_data<gh_stars>10-100
import pytest
import numbers
import random
from world_bank_data import get_indicators, get_series
from .tools import assert_numeric_or_string
from pandas.testing import assert_frame_equal
def test_indicators_one():
idx = get_indicators('SP.POP.TOTL')
assert idx.index == ['SP.POP.TOTL']
assert_numeric_or_string(idx)
def test_indicators_two():
with pytest.raises(RuntimeError):
get_indicators(['SP.POP.0014.TO.ZS', 'SP.POP.TOTL'])
def test_indicators():
idx = get_indicators()
assert len(idx.index) > 16000
assert_numeric_or_string(idx)
def test_indicators_per_page():
idx = get_indicators().sort_index()
idx2 = get_indicators(per_page=5000).sort_index()
assert_frame_equal(idx, idx2)
def test_indicators_topic():
idx = get_indicators(topic=5)
assert len(idx.index) < 100
assert_numeric_or_string(idx)
def test_indicators_source():
idx = get_indicators(source=11)
assert len(idx.index) < 2000
assert_numeric_or_string(idx)
with pytest.raises(ValueError):
get_indicators(source=21)
def test_indicator_most_recent_value():
idx = get_series('SP.POP.TOTL', mrv=1)
assert len(idx.index) > 200
assert_numeric_or_string(idx)
idx_mrv5 = get_series('SP.POP.TOTL', mrv=5)
assert len(idx_mrv5.index) == 5 * len(idx.index)
assert_numeric_or_string(idx_mrv5)
def test_non_wdi_indicator():
idx = get_series('TX.VAL.MRCH.CD.WB', mrv=1)
assert len(idx.index) > 50
assert_numeric_or_string(idx)
def test_indicator_use_id():
idx = get_series('SP.POP.TOTL', mrv=1, id_or_value='id', simplify_index=True)
assert len(idx.index) > 200
assert_numeric_or_string(idx)
assert idx.name == 'SP.POP.TOTL'
assert idx.index.names == ['Country']
def test_indicator_simplify_scalar():
pop = get_series('SP.POP.TOTL', 'CHN', mrv=1, simplify_index=True)
assert isinstance(pop, numbers.Number)
def test_indicator_date():
idx = get_series('SP.POP.TOTL', date='2010:2018')
assert len(idx.index) > 200 * 8
assert_numeric_or_string(idx)
def test_indicator_values():
idx = get_series('SP.POP.TOTL', date='2017', simplify_index=True).sort_values(ascending=False)
assert len(idx.index) > 200
assert idx.index.values[0] == 'World'
assert idx.iloc[0] == 7509065705.0
idx = get_series('SP.POP.TOTL', date='2017', simplify_index=True, id_or_value='id').sort_values(ascending=False)
assert len(idx.index) > 200
assert idx.index.values[0] == 'WLD'
assert idx.iloc[0] == 7509065705.0
@pytest.mark.skip('jsonstat format not supported here')
def test_indicator_monthly():
idx = get_series('DPANUSSPB', country=['CHN', 'BRA'], date='2012M01:2012M08')
assert len(idx.index) > 200 * 12
assert_numeric_or_string(idx)
def random_indicators():
random.seed(2019)
all_indicators = get_indicators()
return random.sample(all_indicators.index.tolist(), 12)
@pytest.mark.parametrize('indicator', random_indicators())
def test_random_indicators(indicator):
try:
idx = get_series(indicator, mrv=1)
assert_numeric_or_string(idx)
except ValueError as err:
assert 'The indicator was not found' in str(err)
def test_json_error():
indicator = 'NV.IND.MANF.KD.87'
with pytest.raises(ValueError, match='The indicator was not found. It may have been deleted or archived.'):
get_series(indicator, mrv=1)
|
def extract_substring(input_string, start_char, end_char):
start_index = input_string.find(start_char)
end_index = input_string.find(end_char)
if start_index != -1 and end_index != -1:
return input_string[start_index + 1:end_index]
else:
return ""
# Test the function
input_str = "The @quick# brown fox"
start = "@"
end = "#"
print("The substring between", start, "and", end, "is:", extract_substring(input_str, start, end)) # Output: "The substring between @ and # is: quick" |
#!/bin/sh
set -eux
npm install -g \
yarn \
create-react-app \
create-next-app \
aws-cdk \
cdk8s-cli \
@aws-amplify/cli \
cdktf-cli \
@google/clasp \
textlint \
textlint-rule-preset-ja-spacing \
textlint-rule-preset-ja-technical-writing \
textlint-rule-spellcheck-tech-word \
textlint-rule-prh \
@proofdict/textlint-rule-proofdict \
# https://blitzjs.com/docs/get-started
npm install -g blitz --legacy-peer-deps
|
<filename>client/src/components/ShowQRCode.tsx
import React from 'react';
import QRCode from "qrcode.react";
export interface ShowQRCodeProps {
clientId: string;
}
export const ShowQRCode = (props: ShowQRCodeProps) => {
return (
<>
<QRCode includeMargin={true} size={256} level="M" id="QRCode" value={window.location.origin + "?pcid=" + props.clientId} />
</>
);
} |
#!/bin/bash
set -ue
# set -x
RELEASE_VERSION="0.x.0"
RELEASE_TAG="0.x.0"
RELEASE_URL="https://github.com/comby-tools/comby/releases"
INSTALL_DIR=/usr/local/bin
function ctrl_c() {
rm -f $TMP/$RELEASE_BIN &> /dev/null
printf "${RED}[-]${NORMAL} Installation cancelled. Please see https://github.com/comby-tools/comby/releases if you prefer to install manually.\n"
exit 1
}
trap ctrl_c INT
colors=0
if [ -z "$TERM" ] && which tput >/dev/null 2>&1; then
colors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$colors" ] && [ "$colors" -ge 8 ]; then
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
YELLOW="$(tput setaf 3)"
BOLD="$(tput bold)"
NORMAL="$(tput sgr0)"
else
RED=""
GREEN=""
YELLOW=""
BOLD=""
NORMAL=""
fi
EXISTS=$(command -v comby || echo)
if [ -n "$EXISTS" ]; then
INSTALL_DIR=$(dirname $EXISTS)
fi
if [ ! -d "$INSTALL_DIR" ]; then
printf "${YELLOW}[-]${NORMAL} $INSTALL_DIR does not exist. Please download the binary from ${RELEASE_URL} and install it manually.\n"
exit 1
fi
TMP=${TMPDIR:-/tmp}
ARCH=$(uname -m || echo dunno)
case "$ARCH" in
x86_64|amd64) ARCH="x86_64";;
# x86|i?86) ARCH="i686";;
*) ARCH="OTHER"
esac
OS=$(uname -s || echo dunno)
if [ "$OS" = "Darwin" ]; then
OS=macos
fi
if [ "$OS" = "Linux" ]; then
OS=linux
fi
RELEASE_BIN="comby-${RELEASE_TAG}-${ARCH}-${OS}"
RELEASE_TAR="$RELEASE_BIN.tar.gz"
RELEASE_URL="https://github.com/comby-tools/comby/releases/download/${RELEASE_TAG}/${RELEASE_TAR}"
if [ ! -e "$TMP/$RELEASE_TAR" ]; then
printf "${GREEN}[+]${NORMAL} Downloading ${YELLOW}comby $RELEASE_VERSION${NORMAL}\n"
SUCCESS=$(curl -s -L -o "$TMP/$RELEASE_TAR" "$RELEASE_URL" --write-out "%{http_code}")
if [ "$SUCCESS" == "404" ]; then
printf "${RED}[-]${NORMAL} No binary release available for your system.\n"
rm -f $TMP/$RELEASE_TAR
exit 1
fi
printf "${GREEN}[+]${NORMAL} Download complete.\n"
fi
cd "$TMP" && tar -xzf "$RELEASE_TAR"
chmod 755 "$TMP/$RELEASE_BIN"
echo "${GREEN}[+]${NORMAL} Installing comby to $INSTALL_DIR"
if [ ! $OS == "macos" ]; then
sudo cp "$TMP/$RELEASE_BIN" "$INSTALL_DIR/comby"
else
cp "$TMP/$RELEASE_BIN" "$INSTALL_DIR/comby"
fi
SUCCESS_IN_PATH=$(command -v comby || echo notinpath)
if [ $SUCCESS_IN_PATH == "notinpath" ]; then
printf "${BOLD}[*]${NORMAL} Comby is not in your PATH. You should add $INSTALL_DIR to your PATH.\n"
rm -f $TMP/$RELEASE_TAR
rm -f $TMP/$RELEASE_BIN
exit 1
fi
CHECK=$(printf 'printf("hello world!\\\n");' | $INSTALL_DIR/comby 'printf("hello :[1]!\\n");' 'printf("hello comby!\\n");' .c -stdin || echo broken)
if [ "$CHECK" == "broken" ]; then
printf "${RED}[-]${NORMAL} ${YELLOW}comby${NORMAL} did not install correctly.\n"
printf "${YELLOW}[-]${NORMAL} My guess is that you need to install the pcre library on your system. Try:\n"
if [ $OS == "macos" ]; then
printf "${YELLOW}[*]${NORMAL} ${BOLD}brew install pcre && bash <(curl -sL get.comby.dev)${NORMAL}\n"
else
printf "${YELLOW}[*]${NORMAL} ${BOLD}sudo apt-get install libpcre3-dev && bash <(curl -sL get.comby.dev)${NORMAL}\n"
fi
rm -f $TMP/$RELEASE_BIN
rm -f $TMP/$RELEASE_TAR
exit 1
fi
rm -f $TMP/$RELEASE_BIN
rm -f $TMP/$RELEASE_TAR
printf "${GREEN}[+]${NORMAL} ${YELLOW}comby${NORMAL} is installed!\n"
printf "${GREEN}[+]${NORMAL} The licenses for this distribution are included in this script. Licenses are also available at https://github.com/comby-tools/comby/tree/master/docs/third-party-licenses\n"
printf "${GREEN}[+]${NORMAL} Running example command:\n"
echo "${YELLOW}------------------------------------------------------------"
printf "${YELLOW}comby${NORMAL} 'printf(\"${GREEN}:[1] :[2]${NORMAL}!\")' 'printf(\"comby, ${GREEN}:[1]${NORMAL}!\")' .c -stdin << EOF\n"
printf "int main(void) {\n"
printf " printf(\"hello world!\");\n"
printf "}\n"
printf "EOF\n"
echo "${YELLOW}------------------------------------------------------------"
printf "${GREEN}[+]${NORMAL} Output:\n"
echo "${GREEN}------------------------------------------------------------${NORMAL}"
comby 'printf(":[1] :[2]!")' 'printf("comby, :[1]!")' .c -stdin << EOF
int main(void) {
printf("hello world!");
}
EOF
echo "${GREEN}------------------------------------------------------------${NORMAL}"
# comby license
#
# Apache License
# Version 2.0, January 2004
# http://www.apache.org/licenses/
#
# TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
#
# 1. Definitions.
#
# "License" shall mean the terms and conditions for use, reproduction,
# and distribution as defined by Sections 1 through 9 of this document.
#
# "Licensor" shall mean the copyright owner or entity authorized by
# the copyright owner that is granting the License.
#
# "Legal Entity" shall mean the union of the acting entity and all
# other entities that control, are controlled by, or are under common
# control with that entity. For the purposes of this definition,
# "control" means (i) the power, direct or indirect, to cause the
# direction or management of such entity, whether by contract or
# otherwise, or (ii) ownership of fifty percent (50%) or more of the
# outstanding shares, or (iii) beneficial ownership of such entity.
#
# "You" (or "Your") shall mean an individual or Legal Entity
# exercising permissions granted by this License.
#
# "Source" form shall mean the preferred form for making modifications,
# including but not limited to software source code, documentation
# source, and configuration files.
#
# "Object" form shall mean any form resulting from mechanical
# transformation or translation of a Source form, including but
# not limited to compiled object code, generated documentation,
# and conversions to other media types.
#
# "Work" shall mean the work of authorship, whether in Source or
# Object form, made available under the License, as indicated by a
# copyright notice that is included in or attached to the work
# (an example is provided in the Appendix below).
#
# "Derivative Works" shall mean any work, whether in Source or Object
# form, that is based on (or derived from) the Work and for which the
# editorial revisions, annotations, elaborations, or other modifications
# represent, as a whole, an original work of authorship. For the purposes
# of this License, Derivative Works shall not include works that refoo
# separable from, or merely link (or bind by name) to the interfaces of,
# the Work and Derivative Works thereof.
#
# "Contribution" shall mean any work of authorship, including
# the original version of the Work and any modifications or additions
# to that Work or Derivative Works thereof, that is intentionally
# submitted to Licensor for inclusion in the Work by the copyright owner
# or by an individual or Legal Entity authorized to submit on behalf of
# the copyright owner. For the purposes of this definition, "submitted"
# means any form of electronic, verbal, or written communication sent
# to the Licensor or its representatives, including but not limited to
# communication on electronic mailing lists, source code control systems,
# and issue tracking systems that are managed by, or on behalf of, the
# Licensor for the purpose of discussing and improving the Work, but
# excluding communication that is conspicuously marked or otherwise
# designated in writing by the copyright owner as "Not a Contribution."
#
# "Contributor" shall mean Licensor and any individual or Legal Entity
# on behalf of whom a Contribution has been received by Licensor and
# subsequently incorporated within the Work.
#
# 2. Grant of Copyright License. Subject to the terms and conditions of
# this License, each Contributor hereby grants to You a perpetual,
# worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# copyright license to reproduce, prepare Derivative Works of,
# publicly display, publicly perform, sublicense, and distribute the
# Work and such Derivative Works in Source or Object form.
#
# 3. Grant of Patent License. Subject to the terms and conditions of
# this License, each Contributor hereby grants to You a perpetual,
# worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# (except as stated in this section) patent license to make, have made,
# use, offer to sell, sell, import, and otherwise transfer the Work,
# where such license applies only to those patent claims licensable
# by such Contributor that are necessarily infringed by their
# Contribution(s) alone or by combination of their Contribution(s)
# with the Work to which such Contribution(s) was submitted. If You
# institute patent litigation against any entity (including a
# cross-claim or counterclaim in a lawsuit) alleging that the Work
# or a Contribution incorporated within the Work constitutes direct
# or contributory patent infringement, then any patent licenses
# granted to You under this License for that Work shall terminate
# as of the date such litigation is filed.
#
# 4. Redistribution. You may reproduce and distribute copies of the
# Work or Derivative Works thereof in any medium, with or without
# modifications, and in Source or Object form, provided that You
# meet the following conditions:
#
# (a) You must give any other recipients of the Work or
# Derivative Works a copy of this License; and
#
# (b) You must cause any modified files to carry prominent notices
# stating that You changed the files; and
#
# (c) You must retain, in the Source form of any Derivative Works
# that You distribute, all copyright, patent, trademark, and
# attribution notices from the Source form of the Work,
# excluding those notices that do not pertain to any part of
# the Derivative Works; and
#
# (d) If the Work includes a "NOTICE" text file as part of its
# distribution, then any Derivative Works that You distribute must
# include a readable copy of the attribution notices contained
# within such NOTICE file, excluding those notices that do not
# pertain to any part of the Derivative Works, in at least one
# of the following places: within a NOTICE text file distributed
# as part of the Derivative Works; within the Source form or
# documentation, if provided along with the Derivative Works; or,
# within a display generated by the Derivative Works, if and
# wherever such third-party notices normally appear. The contents
# of the NOTICE file are for informational purposes only and
# do not modify the License. You may add Your own attribution
# notices within Derivative Works that You distribute, alongside
# or as an addendum to the NOTICE text from the Work, provided
# that such additional attribution notices cannot be construed
# as modifying the License.
#
# You may add Your own copyright statement to Your modifications and
# may provide additional or different license terms and conditions
# for use, reproduction, or distribution of Your modifications, or
# for any such Derivative Works as a whole, provided Your use,
# reproduction, and distribution of the Work otherwise complies with
# the conditions stated in this License.
#
# 5. Submission of Contributions. Unless You explicitly state otherwise,
# any Contribution intentionally submitted for inclusion in the Work
# by You to the Licensor shall be under the terms and conditions of
# this License, without any additional terms or conditions.
# Notwithstanding the above, nothing herein shall supersede or modify
# the terms of any separate license agreement you may have executed
# with Licensor regarding such Contributions.
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor,
# except as required for reasonable and customary use in describing the
# origin of the Work and reproducing the content of the NOTICE file.
#
# 7. Disclaimer of Warranty. Unless required by applicable law or
# agreed to in writing, Licensor provides the Work (and each
# Contributor provides its Contributions) on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied, including, without limitation, any warranties or conditions
# of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
# PARTICULAR PURPOSE. You are solely responsible for determining the
# appropriateness of using or redistributing the Work and assume any
# risks associated with Your exercise of permissions under this License.
#
# 8. Limitation of Liability. In no event and under no legal theory,
# whether in tort (including negligence), contract, or otherwise,
# unless required by applicable law (such as deliberate and grossly
# negligent acts) or agreed to in writing, shall any Contributor be
# liable to You for damages, including any direct, indirect, special,
# incidental, or consequential damages of any character arising as a
# result of this License or out of the use or inability to use the
# Work (including but not limited to damages for loss of goodwill,
# work stoppage, computer failure or malfunction, or any and all
# other commercial damages or losses), even if such Contributor
# has been advised of the possibility of such damages.
#
# 9. Accepting Warranty or Additional Liability. While redistributing
# the Work or Derivative Works thereof, You may choose to offer,
# and charge a fee for, acceptance of support, warranty, indemnity,
# or other liability obligations and/or rights consistent with this
# License. However, in accepting such obligations, You may act only
# on Your own behalf and on Your sole responsibility, not on behalf
# of any other Contributor, and only if You agree to indemnify,
# defend, and hold each Contributor harmless for any liability
# incurred by, or claims asserted against, such Contributor by reason
# of your accepting any such warranty or additional liability.
#
# END OF TERMS AND CONDITIONS
#
# APPENDIX: How to apply the Apache License to your work.
#
# To apply the Apache License to your work, attach the following
# boilerplate notice, with the fields enclosed by brackets "[]"
# replaced with your own identifying information. (Don't include
# the brackets!) The text should be enclosed in the appropriate
# comment syntax for the file format. We also recommend that a
# file or class name and description of purpose be included on the
# same "printed page" as the copyright notice for easier
# identification within third-party archives.
#
# Copyright 2019 Rijnard van Tonder
#
# 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.
# Begin third party licenses
# LICENSE FOR ppx_deriving_yojson:
#
# Copyright (c) 2014-2018 whitequark <whitequark@whitequark.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# LICENSE FOR core:
#
# The MIT License
#
# Copyright (c) 2008--2021 Jane Street Group, LLC <opensource@janestreet.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# LICENSE FOR ppxlib:
#
# The MIT License
#
# Copyright (c) 2018 Jane Street Group, LLC <opensource@janestreet.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# LICENSE FOR ppx_deriving:
#
# Copyright (c) 2014-2016 whitequark <whitequark@whitequark.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# LICENSE FOR hack_parallel:
#
# MIT License
#
# Copyright (c) 2013-present, Facebook, Inc.
# Modified work Copyright (c) 2018-2019 Rijnard van Tonder
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# LICENSE FOR opium:
#
# # This file is generated by dune, edit dune-project instead
# opam-version: "2.0"
# synopsis: "OCaml web framework"
# description:
# "Opium is a web framework for OCaml that provides everything you need to build safe, fast and extensible web applications."
# maintainer: ["Rudi Grinberg <me@rgrinberg.com>"]
# authors: ["Rudi Grinberg" "Anurag Soni" "Thibaut Mattio"]
# license: "MIT"
# homepage: "https://github.com/rgrinberg/opium"
# doc: "https://rgrinberg.github.io/opium/"
# bug-reports: "https://github.com/rgrinberg/opium/issues"
# depends: [
# "dune" {>= "2.0"}
# "ocaml" {>= "4.08"}
# "rock" {= version}
# "lwt" {>= "5.3.0"}
# "httpaf-lwt-unix"
# "logs"
# "fmt"
# "mtime"
# "cmdliner"
# "ptime"
# "magic-mime"
# "yojson"
# "tyxml"
# "mirage-crypto"
# "base64" {>= "3.0.0"}
# "astring"
# "re"
# "uri"
# "multipart-form-data"
# "result" {>= "1.5"}
# "odoc" {with-doc}
# "alcotest" {with-test}
# "alcotest-lwt" {with-test}
# ]
# build: [
# ["dune" "subst"] {pinned}
# [
# "dune"
# "build"
# "-p"
# name
# "-j"
# jobs
# "@install"
# "@runtest" {with-test}
# "@doc" {with-doc}
# ]
# ]
# dev-repo: "git+https://github.com/rgrinberg/opium.git"
#
# LICENSE FOR pcre-ocaml:
#
# Copyright (c) 1999- Markus Mottl <markus.mottl@gmail.com>
#
# The Library is distributed under the terms of the GNU Lesser General
# Public License version 2.1 (included below).
#
# As a special exception to the GNU Lesser General Public License, you
# may link, statically or dynamically, a "work that uses the Library"
# with a publicly distributed version of the Library to produce an
# executable file containing portions of the Library, and distribute that
# executable file under terms of your choice, without any of the additional
# requirements listed in clause 6 of the GNU Lesser General Public License.
# By "a publicly distributed version of the Library", we mean either the
# unmodified Library as distributed by the authors, or a modified version
# of the Library that is distributed under the conditions defined in clause
# 3 of the GNU Lesser General Public License. This exception does not
# however invalidate any other reasons why the executable file might be
# covered by the GNU Lesser General Public License.
#
# ---------------------------------------------------------------------------
#
# ### GNU LESSER GENERAL PUBLIC LICENSE
#
# Version 2.1, February 1999
#
# Copyright (C) 1991, 1999 Free Software Foundation, Inc.
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
# [This is the first released version of the Lesser GPL. It also counts
# as the successor of the GNU Library Public License, version 2, hence
# the version number 2.1.]
#
# ### Preamble
#
# The licenses for most software are designed to take away your freedom
# to share and change it. By contrast, the GNU General Public Licenses
# are intended to guarantee your freedom to share and change free
# software--to make sure the software is free for all its users.
#
# This license, the Lesser General Public License, applies to some
# specially designated software packages--typically libraries--of the
# Free Software Foundation and other authors who decide to use it. You
# can use it too, but we suggest you first think carefully about whether
# this license or the ordinary General Public License is the better
# strategy to use in any particular case, based on the explanations
# below.
#
# When we speak of free software, we are referring to freedom of use,
# not price. Our General Public Licenses are designed to make sure that
# you have the freedom to distribute copies of free software (and charge
# for this service if you wish); that you receive source code or can get
# it if you want it; that you can change the software and use pieces of
# it in new free programs; and that you are informed that you can do
# these things.
#
# To protect your rights, we need to make restrictions that forbid
# distributors to deny you these rights or to ask you to surrender these
# rights. These restrictions translate to certain responsibilities for
# you if you distribute copies of the library or if you modify it.
#
# For example, if you distribute copies of the library, whether gratis
# or for a fee, you must give the recipients all the rights that we gave
# you. You must make sure that they, too, receive or can get the source
# code. If you link other code with the library, you must provide
# complete object files to the recipients, so that they can relink them
# with the library after making changes to the library and recompiling
# it. And you must show them these terms so they know their rights.
#
# We protect your rights with a two-step method: (1) we copyright the
# library, and (2) we offer you this license, which gives you legal
# permission to copy, distribute and/or modify the library.
#
# To protect each distributor, we want to make it very clear that there
# is no warranty for the free library. Also, if the library is modified
# by someone else and passed on, the recipients should know that what
# they have is not the original version, so that the original author's
# reputation will not be affected by problems that might be introduced
# by others.
#
# Finally, software patents pose a constant threat to the existence of
# any free program. We wish to make sure that a company cannot
# effectively restrict the users of a free program by obtaining a
# restrictive license from a patent holder. Therefore, we insist that
# any patent license obtained for a version of the library must be
# consistent with the full freedom of use specified in this license.
#
# Most GNU software, including some libraries, is covered by the
# ordinary GNU General Public License. This license, the GNU Lesser
# General Public License, applies to certain designated libraries, and
# is quite different from the ordinary General Public License. We use
# this license for certain libraries in order to permit linking those
# libraries into non-free programs.
#
# When a program is linked with a library, whether statically or using a
# shared library, the combination of the two is legally speaking a
# combined work, a derivative of the original library. The ordinary
# General Public License therefore permits such linking only if the
# entire combination fits its criteria of freedom. The Lesser General
# Public License permits more lax criteria for linking other code with
# the library.
#
# We call this license the "Lesser" General Public License because it
# does Less to protect the user's freedom than the ordinary General
# Public License. It also provides other free software developers Less
# of an advantage over competing non-free programs. These disadvantages
# are the reason we use the ordinary General Public License for many
# libraries. However, the Lesser license provides advantages in certain
# special circumstances.
#
# For example, on rare occasions, there may be a special need to
# encourage the widest possible use of a certain library, so that it
# becomes a de-facto standard. To achieve this, non-free programs must
# be allowed to use the library. A more frequent case is that a free
# library does the same job as widely used non-free libraries. In this
# case, there is little to gain by limiting the free library to free
# software only, so we use the Lesser General Public License.
#
# In other cases, permission to use a particular library in non-free
# programs enables a greater number of people to use a large body of
# free software. For example, permission to use the GNU C Library in
# non-free programs enables many more people to use the whole GNU
# operating system, as well as its variant, the GNU/Linux operating
# system.
#
# Although the Lesser General Public License is Less protective of the
# users' freedom, it does ensure that the user of a program that is
# linked with the Library has the freedom and the wherewithal to run
# that program using a modified version of the Library.
#
# The precise terms and conditions for copying, distribution and
# modification follow. Pay close attention to the difference between a
# "work based on the library" and a "work that uses the library". The
# former contains code derived from the library, whereas the latter must
# be combined with the library in order to run.
#
# ### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# **0.** This License Agreement applies to any software library or other
# program which contains a notice placed by the copyright holder or
# other authorized party saying it may be distributed under the terms of
# this Lesser General Public License (also called "this License"). Each
# licensee is addressed as "you".
#
# A "library" means a collection of software functions and/or data
# prepared so as to be conveniently linked with application programs
# (which use some of those functions and data) to form executables.
#
# The "Library", below, refers to any such software library or work
# which has been distributed under these terms. A "work based on the
# Library" means either the Library or any derivative work under
# copyright law: that is to say, a work containing the Library or a
# portion of it, either verbatim or with modifications and/or translated
# straightforwardly into another language. (Hereinafter, translation is
# included without limitation in the term "modification".)
#
# "Source code" for a work means the preferred form of the work for
# making modifications to it. For a library, complete source code means
# all the source code for all modules it contains, plus any associated
# interface definition files, plus the scripts used to control
# compilation and installation of the library.
#
# Activities other than copying, distribution and modification are not
# covered by this License; they are outside its scope. The act of
# running a program using the Library is not restricted, and output from
# such a program is covered only if its contents constitute a work based
# on the Library (independent of the use of the Library in a tool for
# writing it). Whether that is true depends on what the Library does and
# what the program that uses the Library does.
#
# **1.** You may copy and distribute verbatim copies of the Library's
# complete source code as you receive it, in any medium, provided that
# you conspicuously and appropriately publish on each copy an
# appropriate copyright notice and disclaimer of warranty; keep intact
# all the notices that refer to this License and to the absence of any
# warranty; and distribute a copy of this License along with the
# Library.
#
# You may charge a fee for the physical act of transferring a copy, and
# you may at your option offer warranty protection in exchange for a
# fee.
#
# **2.** You may modify your copy or copies of the Library or any
# portion of it, thus forming a work based on the Library, and copy and
# distribute such modifications or work under the terms of Section 1
# above, provided that you also meet all of these conditions:
#
# - **a)** The modified work must itself be a software library.
# - **b)** You must cause the files modified to carry prominent
# notices stating that you changed the files and the date of
# any change.
# - **c)** You must cause the whole of the work to be licensed at no
# charge to all third parties under the terms of this License.
# - **d)** If a facility in the modified Library refers to a function
# or a table of data to be supplied by an application program that
# uses the facility, other than as an argument passed when the
# facility is invoked, then you must make a good faith effort to
# ensure that, in the event an application does not supply such
# function or table, the facility still operates, and performs
# whatever part of its purpose remains meaningful.
#
# (For example, a function in a library to compute square roots has
# a purpose that is entirely well-defined independent of
# the application. Therefore, Subsection 2d requires that any
# application-supplied function or table used by this function must
# be optional: if the application does not supply it, the square
# root function must still compute square roots.)
#
# These requirements apply to the modified work as a whole. If
# identifiable sections of that work are not derived from the Library,
# and can be reasonably considered independent and separate works in
# themselves, then this License, and its terms, do not apply to those
# sections when you distribute them as separate works. But when you
# distribute the same sections as part of a whole which is a work based
# on the Library, the distribution of the whole must be on the terms of
# this License, whose permissions for other licensees extend to the
# entire whole, and thus to each and every part regardless of who wrote
# it.
#
# Thus, it is not the intent of this section to claim rights or contest
# your rights to work written entirely by you; rather, the intent is to
# exercise the right to control the distribution of derivative or
# collective works based on the Library.
#
# In addition, mere aggregation of another work not based on the Library
# with the Library (or with a work based on the Library) on a volume of
# a storage or distribution medium does not bring the other work under
# the scope of this License.
#
# **3.** You may opt to apply the terms of the ordinary GNU General
# Public License instead of this License to a given copy of the Library.
# To do this, you must alter all the notices that refer to this License,
# so that they refer to the ordinary GNU General Public License, version
# 2, instead of to this License. (If a newer version than version 2 of
# the ordinary GNU General Public License has appeared, then you can
# specify that version instead if you wish.) Do not make any other
# change in these notices.
#
# Once this change is made in a given copy, it is irreversible for that
# copy, so the ordinary GNU General Public License applies to all
# subsequent copies and derivative works made from that copy.
#
# This option is useful when you wish to copy part of the code of the
# Library into a program that is not a library.
#
# **4.** You may copy and distribute the Library (or a portion or
# derivative of it, under Section 2) in object code or executable form
# under the terms of Sections 1 and 2 above provided that you accompany
# it with the complete corresponding machine-readable source code, which
# must be distributed under the terms of Sections 1 and 2 above on a
# medium customarily used for software interchange.
#
# If distribution of object code is made by offering access to copy from
# a designated place, then offering equivalent access to copy the source
# code from the same place satisfies the requirement to distribute the
# source code, even though third parties are not compelled to copy the
# source along with the object code.
#
# **5.** A program that contains no derivative of any portion of the
# Library, but is designed to work with the Library by being compiled or
# linked with it, is called a "work that uses the Library". Such a work,
# in isolation, is not a derivative work of the Library, and therefore
# falls outside the scope of this License.
#
# However, linking a "work that uses the Library" with the Library
# creates an executable that is a derivative of the Library (because it
# contains portions of the Library), rather than a "work that uses the
# library". The executable is therefore covered by this License. Section
# 6 states terms for distribution of such executables.
#
# When a "work that uses the Library" uses material from a header file
# that is part of the Library, the object code for the work may be a
# derivative work of the Library even though the source code is not.
# Whether this is true is especially significant if the work can be
# linked without the Library, or if the work is itself a library. The
# threshold for this to be true is not precisely defined by law.
#
# If such an object file uses only numerical parameters, data structure
# layouts and accessors, and small macros and small inline functions
# (ten lines or less in length), then the use of the object file is
# unrestricted, regardless of whether it is legally a derivative work.
# (Executables containing this object code plus portions of the Library
# will still fall under Section 6.)
#
# Otherwise, if the work is a derivative of the Library, you may
# distribute the object code for the work under the terms of Section 6.
# Any executables containing that work also fall under Section 6,
# whether or not they are linked directly with the Library itself.
#
# **6.** As an exception to the Sections above, you may also combine or
# link a "work that uses the Library" with the Library to produce a work
# containing portions of the Library, and distribute that work under
# terms of your choice, provided that the terms permit modification of
# the work for the customer's own use and reverse engineering for
# debugging such modifications.
#
# You must give prominent notice with each copy of the work that the
# Library is used in it and that the Library and its use are covered by
# this License. You must supply a copy of this License. If the work
# during execution displays copyright notices, you must include the
# copyright notice for the Library among them, as well as a reference
# directing the user to the copy of this License. Also, you must do one
# of these things:
#
# - **a)** Accompany the work with the complete corresponding
# machine-readable source code for the Library including whatever
# changes were used in the work (which must be distributed under
# Sections 1 and 2 above); and, if the work is an executable linked
# with the Library, with the complete machine-readable "work that
# uses the Library", as object code and/or source code, so that the
# user can modify the Library and then relink to produce a modified
# executable containing the modified Library. (It is understood that
# the user who changes the contents of definitions files in the
# Library will not necessarily be able to recompile the application
# to use the modified definitions.)
# - **b)** Use a suitable shared library mechanism for linking with
# the Library. A suitable mechanism is one that (1) uses at run time
# a copy of the library already present on the user's computer
# system, rather than copying library functions into the executable,
# and (2) will operate properly with a modified version of the
# library, if the user installs one, as long as the modified version
# is interface-compatible with the version that the work was
# made with.
# - **c)** Accompany the work with a written offer, valid for at least
# three years, to give the same user the materials specified in
# Subsection 6a, above, for a charge no more than the cost of
# performing this distribution.
# - **d)** If distribution of the work is made by offering access to
# copy from a designated place, offer equivalent access to copy the
# above specified materials from the same place.
# - **e)** Verify that the user has already received a copy of these
# materials or that you have already sent this user a copy.
#
# For an executable, the required form of the "work that uses the
# Library" must include any data and utility programs needed for
# reproducing the executable from it. However, as a special exception,
# the materials to be distributed need not include anything that is
# normally distributed (in either source or binary form) with the major
# components (compiler, kernel, and so on) of the operating system on
# which the executable runs, unless that component itself accompanies
# the executable.
#
# It may happen that this requirement contradicts the license
# restrictions of other proprietary libraries that do not normally
# accompany the operating system. Such a contradiction means you cannot
# use both them and the Library together in an executable that you
# distribute.
#
# **7.** You may place library facilities that are a work based on the
# Library side-by-side in a single library together with other library
# facilities not covered by this License, and distribute such a combined
# library, provided that the separate distribution of the work based on
# the Library and of the other library facilities is otherwise
# permitted, and provided that you do these two things:
#
# - **a)** Accompany the combined library with a copy of the same work
# based on the Library, uncombined with any other
# library facilities. This must be distributed under the terms of
# the Sections above.
# - **b)** Give prominent notice with the combined library of the fact
# that part of it is a work based on the Library, and explaining
# where to find the accompanying uncombined form of the same work.
#
# **8.** You may not copy, modify, sublicense, link with, or distribute
# the Library except as expressly provided under this License. Any
# attempt otherwise to copy, modify, sublicense, link with, or
# distribute the Library is void, and will automatically terminate your
# rights under this License. However, parties who have received copies,
# or rights, from you under this License will not have their licenses
# terminated so long as such parties remain in full compliance.
#
# **9.** You are not required to accept this License, since you have not
# signed it. However, nothing else grants you permission to modify or
# distribute the Library or its derivative works. These actions are
# prohibited by law if you do not accept this License. Therefore, by
# modifying or distributing the Library (or any work based on the
# Library), you indicate your acceptance of this License to do so, and
# all its terms and conditions for copying, distributing or modifying
# the Library or works based on it.
#
# **10.** Each time you redistribute the Library (or any work based on
# the Library), the recipient automatically receives a license from the
# original licensor to copy, distribute, link with or modify the Library
# subject to these terms and conditions. You may not impose any further
# restrictions on the recipients' exercise of the rights granted herein.
# You are not responsible for enforcing compliance by third parties with
# this License.
#
# **11.** If, as a consequence of a court judgment or allegation of
# patent infringement or for any other reason (not limited to patent
# issues), conditions are imposed on you (whether by court order,
# agreement or otherwise) that contradict the conditions of this
# License, they do not excuse you from the conditions of this License.
# If you cannot distribute so as to satisfy simultaneously your
# obligations under this License and any other pertinent obligations,
# then as a consequence you may not distribute the Library at all. For
# example, if a patent license would not permit royalty-free
# redistribution of the Library by all those who receive copies directly
# or indirectly through you, then the only way you could satisfy both it
# and this License would be to refrain entirely from distribution of the
# Library.
#
# If any portion of this section is held invalid or unenforceable under
# any particular circumstance, the balance of the section is intended to
# apply, and the section as a whole is intended to apply in other
# circumstances.
#
# It is not the purpose of this section to induce you to infringe any
# patents or other property right claims or to contest validity of any
# such claims; this section has the sole purpose of protecting the
# integrity of the free software distribution system which is
# implemented by public license practices. Many people have made
# generous contributions to the wide range of software distributed
# through that system in reliance on consistent application of that
# system; it is up to the author/donor to decide if he or she is willing
# to distribute software through any other system and a licensee cannot
# impose that choice.
#
# This section is intended to make thoroughly clear what is believed to
# be a consequence of the rest of this License.
#
# **12.** If the distribution and/or use of the Library is restricted in
# certain countries either by patents or by copyrighted interfaces, the
# original copyright holder who places the Library under this License
# may add an explicit geographical distribution limitation excluding
# those countries, so that distribution is permitted only in or among
# countries not thus excluded. In such case, this License incorporates
# the limitation as if written in the body of this License.
#
# **13.** The Free Software Foundation may publish revised and/or new
# versions of the Lesser General Public License from time to time. Such
# new versions will be similar in spirit to the present version, but may
# differ in detail to address new problems or concerns.
#
# Each version is given a distinguishing version number. If the Library
# specifies a version number of this License which applies to it and
# "any later version", you have the option of following the terms and
# conditions either of that version or of any later version published by
# the Free Software Foundation. If the Library does not specify a
# license version number, you may choose any version ever published by
# the Free Software Foundation.
#
# **14.** If you wish to incorporate parts of the Library into other
# free programs whose distribution conditions are incompatible with
# these, write to the author to ask for permission. For software which
# is copyrighted by the Free Software Foundation, write to the Free
# Software Foundation; we sometimes make exceptions for this. Our
# decision will be guided by the two goals of preserving the free status
# of all derivatives of our free software and of promoting the sharing
# and reuse of software generally.
#
# **NO WARRANTY**
#
# **15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
# WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
# EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
# OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
# KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
# LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
# THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
#
# **16.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
# WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
# AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
# FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
# CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
# LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
# RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
# FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
# SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGES.
#
# ### END OF TERMS AND CONDITIONS
#
# ### How to Apply These Terms to Your New Libraries
#
# If you develop a new library, and you want it to be of the greatest
# possible use to the public, we recommend making it free software that
# everyone can redistribute and change. You can do so by permitting
# redistribution under these terms (or, alternatively, under the terms
# of the ordinary General Public License).
#
# To apply these terms, attach the following notices to the library. It
# is safest to attach them to the start of each source file to most
# effectively convey the exclusion of warranty; and each file should
# have at least the "copyright" line and a pointer to where the full
# notice is found.
#
# one line to give the library's name and an idea of what it does.
# Copyright (C) year name of author
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Also add information on how to contact you by electronic and paper
# mail.
#
# You should also get your employer (if you work as a programmer) or
# your school, if any, to sign a "copyright disclaimer" for the library,
# if necessary. Here is a sample; alter the names:
#
# Yoyodyne, Inc., hereby disclaims all copyright interest in
# the library `Frob' (a library for tweaking knobs) written
# by James Random Hacker.
#
# signature of Ty Coon, 1 April 1990
# Ty Coon, President of Vice
#
# That's all there is to it!
#
# LICENSE FOR ocaml-tls:
#
# Copyright (c) 2014, David Kaloper and Hannes Mehnert
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# LICENSE FOR camlzip:
#
# This Library is distributed under the terms of the GNU Lesser General
# Public License (LGPL) version 2.1 or above (included below).
#
# As a special exception to the GNU Lesser General Public License, you
# may link, statically or dynamically, a "work that uses the Library"
# with a publicly distributed version of the Library to produce an
# executable file containing portions of the Library, and distribute
# that executable file under terms of your choice, without any of the
# additional requirements listed in clause 6 of the GNU Lesser General
# Public License. By "a publicly distributed version of the Library",
# we mean either the unmodified Library as distributed by INRIA, or a
# modified version of the Library that is distributed under the
# conditions defined in clause 3 of the GNU Lesser General Public
# License. This exception does not however invalidate any other reasons
# why the executable file might be covered by the GNU Lesser General
# Public License.
#
# ----------------------------------------------------------------------
#
# GNU LESSER GENERAL PUBLIC LICENSE
# Version 2.1, February 1999
#
# Copyright (C) 1991, 1999 Free Software Foundation, Inc.
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
# [This is the first released version of the Lesser GPL. It also counts
# as the successor of the GNU Library Public License, version 2, hence
# the version number 2.1.]
#
# Preamble
#
# The licenses for most software are designed to take away your
# freedom to share and change it. By contrast, the GNU General Public
# Licenses are intended to guarantee your freedom to share and change
# free software--to make sure the software is free for all its users.
#
# This license, the Lesser General Public License, applies to some
# specially designated software packages--typically libraries--of the
# Free Software Foundation and other authors who decide to use it. You
# can use it too, but we suggest you first think carefully about whether
# this license or the ordinary General Public License is the better
# strategy to use in any particular case, based on the explanations below.
#
# When we speak of free software, we are referring to freedom of use,
# not price. Our General Public Licenses are designed to make sure that
# you have the freedom to distribute copies of free software (and charge
# for this service if you wish); that you receive source code or can get
# it if you want it; that you can change the software and use pieces of
# it in new free programs; and that you are informed that you can do
# these things.
#
# To protect your rights, we need to make restrictions that forbid
# distributors to deny you these rights or to ask you to surrender these
# rights. These restrictions translate to certain responsibilities for
# you if you distribute copies of the library or if you modify it.
#
# For example, if you distribute copies of the library, whether gratis
# or for a fee, you must give the recipients all the rights that we gave
# you. You must make sure that they, too, receive or can get the source
# code. If you link other code with the library, you must provide
# complete object files to the recipients, so that they can relink them
# with the library after making changes to the library and recompiling
# it. And you must show them these terms so they know their rights.
#
# We protect your rights with a two-step method: (1) we copyright the
# library, and (2) we offer you this license, which gives you legal
# permission to copy, distribute and/or modify the library.
#
# To protect each distributor, we want to make it very clear that
# there is no warranty for the free library. Also, if the library is
# modified by someone else and passed on, the recipients should know
# that what they have is not the original version, so that the original
# author's reputation will not be affected by problems that might be
# introduced by others.
#
# Finally, software patents pose a constant threat to the existence of
# any free program. We wish to make sure that a company cannot
# effectively restrict the users of a free program by obtaining a
# restrictive license from a patent holder. Therefore, we insist that
# any patent license obtained for a version of the library must be
# consistent with the full freedom of use specified in this license.
#
# Most GNU software, including some libraries, is covered by the
# ordinary GNU General Public License. This license, the GNU Lesser
# General Public License, applies to certain designated libraries, and
# is quite different from the ordinary General Public License. We use
# this license for certain libraries in order to permit linking those
# libraries into non-free programs.
#
# When a program is linked with a library, whether statically or using
# a shared library, the combination of the two is legally speaking a
# combined work, a derivative of the original library. The ordinary
# General Public License therefore permits such linking only if the
# entire combination fits its criteria of freedom. The Lesser General
# Public License permits more lax criteria for linking other code with
# the library.
#
# We call this license the "Lesser" General Public License because it
# does Less to protect the user's freedom than the ordinary General
# Public License. It also provides other free software developers Less
# of an advantage over competing non-free programs. These disadvantages
# are the reason we use the ordinary General Public License for many
# libraries. However, the Lesser license provides advantages in certain
# special circumstances.
#
# For example, on rare occasions, there may be a special need to
# encourage the widest possible use of a certain library, so that it becomes
# a de-facto standard. To achieve this, non-free programs must be
# allowed to use the library. A more frequent case is that a free
# library does the same job as widely used non-free libraries. In this
# case, there is little to gain by limiting the free library to free
# software only, so we use the Lesser General Public License.
#
# In other cases, permission to use a particular library in non-free
# programs enables a greater number of people to use a large body of
# free software. For example, permission to use the GNU C Library in
# non-free programs enables many more people to use the whole GNU
# operating system, as well as its variant, the GNU/Linux operating
# system.
#
# Although the Lesser General Public License is Less protective of the
# users' freedom, it does ensure that the user of a program that is
# linked with the Library has the freedom and the wherewithal to run
# that program using a modified version of the Library.
#
# The precise terms and conditions for copying, distribution and
# modification follow. Pay close attention to the difference between a
# "work based on the library" and a "work that uses the library". The
# former contains code derived from the library, whereas the latter must
# be combined with the library in order to run.
#
# GNU LESSER GENERAL PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. This License Agreement applies to any software library or other
# program which contains a notice placed by the copyright holder or
# other authorized party saying it may be distributed under the terms of
# this Lesser General Public License (also called "this License").
# Each licensee is addressed as "you".
#
# A "library" means a collection of software functions and/or data
# prepared so as to be conveniently linked with application programs
# (which use some of those functions and data) to form executables.
#
# The "Library", below, refers to any such software library or work
# which has been distributed under these terms. A "work based on the
# Library" means either the Library or any derivative work under
# copyright law: that is to say, a work containing the Library or a
# portion of it, either verbatim or with modifications and/or translated
# straightforwardly into another language. (Hereinafter, translation is
# included without limitation in the term "modification".)
#
# "Source code" for a work means the preferred form of the work for
# making modifications to it. For a library, complete source code means
# all the source code for all modules it contains, plus any associated
# interface definition files, plus the scripts used to control compilation
# and installation of the library.
#
# Activities other than copying, distribution and modification are not
# covered by this License; they are outside its scope. The act of
# running a program using the Library is not restricted, and output from
# such a program is covered only if its contents constitute a work based
# on the Library (independent of the use of the Library in a tool for
# writing it). Whether that is true depends on what the Library does
# and what the program that uses the Library does.
#
# 1. You may copy and distribute verbatim copies of the Library's
# complete source code as you receive it, in any medium, provided that
# you conspicuously and appropriately publish on each copy an
# appropriate copyright notice and disclaimer of warranty; keep intact
# all the notices that refer to this License and to the absence of any
# warranty; and distribute a copy of this License along with the
# Library.
#
# You may charge a fee for the physical act of transferring a copy,
# and you may at your option offer warranty protection in exchange for a
# fee.
#
# 2. You may modify your copy or copies of the Library or any portion
# of it, thus forming a work based on the Library, and copy and
# distribute such modifications or work under the terms of Section 1
# above, provided that you also meet all of these conditions:
#
# a) The modified work must itself be a software library.
#
# b) You must cause the files modified to carry prominent notices
# stating that you changed the files and the date of any change.
#
# c) You must cause the whole of the work to be licensed at no
# charge to all third parties under the terms of this License.
#
# d) If a facility in the modified Library refers to a function or a
# table of data to be supplied by an application program that uses
# the facility, other than as an argument passed when the facility
# is invoked, then you must make a good faith effort to ensure that,
# in the event an application does not supply such function or
# table, the facility still operates, and performs whatever part of
# its purpose remains meaningful.
#
# (For example, a function in a library to compute square roots has
# a purpose that is entirely well-defined independent of the
# application. Therefore, Subsection 2d requires that any
# application-supplied function or table used by this function must
# be optional: if the application does not supply it, the square
# root function must still compute square roots.)
#
# These requirements apply to the modified work as a whole. If
# identifiable sections of that work are not derived from the Library,
# and can be reasonably considered independent and separate works in
# themselves, then this License, and its terms, do not apply to those
# sections when you distribute them as separate works. But when you
# distribute the same sections as part of a whole which is a work based
# on the Library, the distribution of the whole must be on the terms of
# this License, whose permissions for other licensees extend to the
# entire whole, and thus to each and every part regardless of who wrote
# it.
#
# Thus, it is not the intent of this section to claim rights or contest
# your rights to work written entirely by you; rather, the intent is to
# exercise the right to control the distribution of derivative or
# collective works based on the Library.
#
# In addition, mere aggregation of another work not based on the Library
# with the Library (or with a work based on the Library) on a volume of
# a storage or distribution medium does not bring the other work under
# the scope of this License.
#
# 3. You may opt to apply the terms of the ordinary GNU General Public
# License instead of this License to a given copy of the Library. To do
# this, you must alter all the notices that refer to this License, so
# that they refer to the ordinary GNU General Public License, version 2,
# instead of to this License. (If a newer version than version 2 of the
# ordinary GNU General Public License has appeared, then you can specify
# that version instead if you wish.) Do not make any other change in
# these notices.
#
# Once this change is made in a given copy, it is irreversible for
# that copy, so the ordinary GNU General Public License applies to all
# subsequent copies and derivative works made from that copy.
#
# This option is useful when you wish to copy part of the code of
# the Library into a program that is not a library.
#
# 4. You may copy and distribute the Library (or a portion or
# derivative of it, under Section 2) in object code or executable form
# under the terms of Sections 1 and 2 above provided that you accompany
# it with the complete corresponding machine-readable source code, which
# must be distributed under the terms of Sections 1 and 2 above on a
# medium customarily used for software interchange.
#
# If distribution of object code is made by offering access to copy
# from a designated place, then offering equivalent access to copy the
# source code from the same place satisfies the requirement to
# distribute the source code, even though third parties are not
# compelled to copy the source along with the object code.
#
# 5. A program that contains no derivative of any portion of the
# Library, but is designed to work with the Library by being compiled or
# linked with it, is called a "work that uses the Library". Such a
# work, in isolation, is not a derivative work of the Library, and
# therefore falls outside the scope of this License.
#
# However, linking a "work that uses the Library" with the Library
# creates an executable that is a derivative of the Library (because it
# contains portions of the Library), rather than a "work that uses the
# library". The executable is therefore covered by this License.
# Section 6 states terms for distribution of such executables.
#
# When a "work that uses the Library" uses material from a header file
# that is part of the Library, the object code for the work may be a
# derivative work of the Library even though the source code is not.
# Whether this is true is especially significant if the work can be
# linked without the Library, or if the work is itself a library. The
# threshold for this to be true is not precisely defined by law.
#
# If such an object file uses only numerical parameters, data
# structure layouts and accessors, and small macros and small inline
# functions (ten lines or less in length), then the use of the object
# file is unrestricted, regardless of whether it is legally a derivative
# work. (Executables containing this object code plus portions of the
# Library will still fall under Section 6.)
#
# Otherwise, if the work is a derivative of the Library, you may
# distribute the object code for the work under the terms of Section 6.
# Any executables containing that work also fall under Section 6,
# whether or not they are linked directly with the Library itself.
#
# 6. As an exception to the Sections above, you may also combine or
# link a "work that uses the Library" with the Library to produce a
# work containing portions of the Library, and distribute that work
# under terms of your choice, provided that the terms permit
# modification of the work for the customer's own use and reverse
# engineering for debugging such modifications.
#
# You must give prominent notice with each copy of the work that the
# Library is used in it and that the Library and its use are covered by
# this License. You must supply a copy of this License. If the work
# during execution displays copyright notices, you must include the
# copyright notice for the Library among them, as well as a reference
# directing the user to the copy of this License. Also, you must do one
# of these things:
#
# a) Accompany the work with the complete corresponding
# machine-readable source code for the Library including whatever
# changes were used in the work (which must be distributed under
# Sections 1 and 2 above); and, if the work is an executable linked
# with the Library, with the complete machine-readable "work that
# uses the Library", as object code and/or source code, so that the
# user can modify the Library and then relink to produce a modified
# executable containing the modified Library. (It is understood
# that the user who changes the contents of definitions files in the
# Library will not necessarily be able to recompile the application
# to use the modified definitions.)
#
# b) Use a suitable shared library mechanism for linking with the
# Library. A suitable mechanism is one that (1) uses at run time a
# copy of the library already present on the user's computer system,
# rather than copying library functions into the executable, and (2)
# will operate properly with a modified version of the library, if
# the user installs one, as long as the modified version is
# interface-compatible with the version that the work was made with.
#
# c) Accompany the work with a written offer, valid for at
# least three years, to give the same user the materials
# specified in Subsection 6a, above, for a charge no more
# than the cost of performing this distribution.
#
# d) If distribution of the work is made by offering access to copy
# from a designated place, offer equivalent access to copy the above
# specified materials from the same place.
#
# e) Verify that the user has already received a copy of these
# materials or that you have already sent this user a copy.
#
# For an executable, the required form of the "work that uses the
# Library" must include any data and utility programs needed for
# reproducing the executable from it. However, as a special exception,
# the materials to be distributed need not include anything that is
# normally distributed (in either source or binary form) with the major
# components (compiler, kernel, and so on) of the operating system on
# which the executable runs, unless that component itself accompanies
# the executable.
#
# It may happen that this requirement contradicts the license
# restrictions of other proprietary libraries that do not normally
# accompany the operating system. Such a contradiction means you cannot
# use both them and the Library together in an executable that you
# distribute.
#
# 7. You may place library facilities that are a work based on the
# Library side-by-side in a single library together with other library
# facilities not covered by this License, and distribute such a combined
# library, provided that the separate distribution of the work based on
# the Library and of the other library facilities is otherwise
# permitted, and provided that you do these two things:
#
# a) Accompany the combined library with a copy of the same work
# based on the Library, uncombined with any other library
# facilities. This must be distributed under the terms of the
# Sections above.
#
# b) Give prominent notice with the combined library of the fact
# that part of it is a work based on the Library, and explaining
# where to find the accompanying uncombined form of the same work.
#
# 8. You may not copy, modify, sublicense, link with, or distribute
# the Library except as expressly provided under this License. Any
# attempt otherwise to copy, modify, sublicense, link with, or
# distribute the Library is void, and will automatically terminate your
# rights under this License. However, parties who have received copies,
# or rights, from you under this License will not have their licenses
# terminated so long as such parties remain in full compliance.
#
# 9. You are not required to accept this License, since you have not
# signed it. However, nothing else grants you permission to modify or
# distribute the Library or its derivative works. These actions are
# prohibited by law if you do not accept this License. Therefore, by
# modifying or distributing the Library (or any work based on the
# Library), you indicate your acceptance of this License to do so, and
# all its terms and conditions for copying, distributing or modifying
# the Library or works based on it.
#
# 10. Each time you redistribute the Library (or any work based on the
# Library), the recipient automatically receives a license from the
# original licensor to copy, distribute, link with or modify the Library
# subject to these terms and conditions. You may not impose any further
# restrictions on the recipients' exercise of the rights granted herein.
# You are not responsible for enforcing compliance by third parties with
# this License.
#
# 11. If, as a consequence of a court judgment or allegation of patent
# infringement or for any other reason (not limited to patent issues),
# conditions are imposed on you (whether by court order, agreement or
# otherwise) that contradict the conditions of this License, they do not
# excuse you from the conditions of this License. If you cannot
# distribute so as to satisfy simultaneously your obligations under this
# License and any other pertinent obligations, then as a consequence you
# may not distribute the Library at all. For example, if a patent
# license would not permit royalty-free redistribution of the Library by
# all those who receive copies directly or indirectly through you, then
# the only way you could satisfy both it and this License would be to
# refrain entirely from distribution of the Library.
#
# If any portion of this section is held invalid or unenforceable under any
# particular circumstance, the balance of the section is intended to apply,
# and the section as a whole is intended to apply in other circumstances.
#
# It is not the purpose of this section to induce you to infringe any
# patents or other property right claims or to contest validity of any
# such claims; this section has the sole purpose of protecting the
# integrity of the free software distribution system which is
# implemented by public license practices. Many people have made
# generous contributions to the wide range of software distributed
# through that system in reliance on consistent application of that
# system; it is up to the author/donor to decide if he or she is willing
# to distribute software through any other system and a licensee cannot
# impose that choice.
#
# This section is intended to make thoroughly clear what is believed to
# be a consequence of the rest of this License.
#
# 12. If the distribution and/or use of the Library is restricted in
# certain countries either by patents or by copyrighted interfaces, the
# original copyright holder who places the Library under this License may add
# an explicit geographical distribution limitation excluding those countries,
# so that distribution is permitted only in or among countries not thus
# excluded. In such case, this License incorporates the limitation as if
# written in the body of this License.
#
# 13. The Free Software Foundation may publish revised and/or new
# versions of the Lesser General Public License from time to time.
# Such new versions will be similar in spirit to the present version,
# but may differ in detail to address new problems or concerns.
#
# Each version is given a distinguishing version number. If the Library
# specifies a version number of this License which applies to it and
# "any later version", you have the option of following the terms and
# conditions either of that version or of any later version published by
# the Free Software Foundation. If the Library does not specify a
# license version number, you may choose any version ever published by
# the Free Software Foundation.
#
# 14. If you wish to incorporate parts of the Library into other free
# programs whose distribution conditions are incompatible with these,
# write to the author to ask for permission. For software which is
# copyrighted by the Free Software Foundation, write to the Free
# Software Foundation; we sometimes make exceptions for this. Our
# decision will be guided by the two goals of preserving the free status
# of all derivatives of our free software and of promoting the sharing
# and reuse of software generally.
#
# NO WARRANTY
#
# 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
# WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
# EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
# OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
# KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
# LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
# THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
#
# 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
# WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
# AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
# FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
# CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
# LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
# RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
# FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
# SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGES.
#
# END OF TERMS AND CONDITIONS
#
# How to Apply These Terms to Your New Libraries
#
# If you develop a new library, and you want it to be of the greatest
# possible use to the public, we recommend making it free software that
# everyone can redistribute and change. You can do so by permitting
# redistribution under these terms (or, alternatively, under the terms of the
# ordinary General Public License).
#
# To apply these terms, attach the following notices to the library. It is
# safest to attach them to the start of each source file to most effectively
# convey the exclusion of warranty; and each file should have at least the
# "copyright" line and a pointer to where the full notice is found.
#
# <one line to give the library's name and a brief idea of what it does.>
# Copyright (C) <year> <name of author>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Also add information on how to contact you by electronic and paper mail.
#
# You should also get your employer (if you work as a programmer) or your
# school, if any, to sign a "copyright disclaimer" for the library, if
# necessary. Here is a sample; alter the names:
#
# Yoyodyne, Inc., hereby disclaims all copyright interest in the
# library `Frob' (a library for tweaking knobs) written by James Random Hacker.
#
# <signature of Ty Coon>, 1 April 1990
# Ty Coon, President of Vice
#
# That's all there is to it!
#
# LICENSE FOR bisect_ppx:
#
# Copyright © 2008-2021 Xavier Clerc, Leonid Rozenberg, Anton Bachin
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the “Software”), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# LICENSE FOR mparser:
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (LGPL) as
# published by the Free Software Foundation; either version 2.1 of the
# License (see below), or (at your option) any later version.
#
# As a special exception to the GNU Lesser General Public License, you
# may link, statically or dynamically, a "work that uses the Library"
# with a publicly distributed version of the Library to produce an
# executable file containing portions of the Library, and distribute
# that executable file under terms of your choice, without any of the
# additional requirements listed in clause 6 of the GNU Lesser General
# Public License. By "a publicly distributed version of the Library", we
# mean either the unmodified Library as distributed, or a modified
# version of the Library that is distributed under the conditions
# defined in clause 2 of the GNU Lesser General Public License. This
# exception does not however invalidate any other reasons why the
# executable file might be covered by the GNU Lesser General Public
# License.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# ======================================================================
#
#
# GNU LESSER GENERAL PUBLIC LICENSE
# Version 2.1, February 1999
#
# Copyright (C) 1991, 1999 Free Software Foundation, Inc.
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
# [This is the first released version of the Lesser GPL. It also counts
# as the successor of the GNU Library Public License, version 2, hence
# the version number 2.1.]
#
# Preamble
#
# The licenses for most software are designed to take away your
# freedom to share and change it. By contrast, the GNU General Public
# Licenses are intended to guarantee your freedom to share and change
# free software--to make sure the software is free for all its users.
#
# This license, the Lesser General Public License, applies to some
# specially designated software packages--typically libraries--of the
# Free Software Foundation and other authors who decide to use it. You
# can use it too, but we suggest you first think carefully about whether
# this license or the ordinary General Public License is the better
# strategy to use in any particular case, based on the explanations below.
#
# When we speak of free software, we are referring to freedom of use,
# not price. Our General Public Licenses are designed to make sure that
# you have the freedom to distribute copies of free software (and charge
# for this service if you wish); that you receive source code or can get
# it if you want it; that you can change the software and use pieces of
# it in new free programs; and that you are informed that you can do
# these things.
#
# To protect your rights, we need to make restrictions that forbid
# distributors to deny you these rights or to ask you to surrender these
# rights. These restrictions translate to certain responsibilities for
# you if you distribute copies of the library or if you modify it.
#
# For example, if you distribute copies of the library, whether gratis
# or for a fee, you must give the recipients all the rights that we gave
# you. You must make sure that they, too, receive or can get the source
# code. If you link other code with the library, you must provide
# complete object files to the recipients, so that they can relink them
# with the library after making changes to the library and recompiling
# it. And you must show them these terms so they know their rights.
#
# We protect your rights with a two-step method: (1) we copyright the
# library, and (2) we offer you this license, which gives you legal
# permission to copy, distribute and/or modify the library.
#
# To protect each distributor, we want to make it very clear that
# there is no warranty for the free library. Also, if the library is
# modified by someone else and passed on, the recipients should know
# that what they have is not the original version, so that the original
# author's reputation will not be affected by problems that might be
# introduced by others.
#
# Finally, software patents pose a constant threat to the existence of
# any free program. We wish to make sure that a company cannot
# effectively restrict the users of a free program by obtaining a
# restrictive license from a patent holder. Therefore, we insist that
# any patent license obtained for a version of the library must be
# consistent with the full freedom of use specified in this license.
#
# Most GNU software, including some libraries, is covered by the
# ordinary GNU General Public License. This license, the GNU Lesser
# General Public License, applies to certain designated libraries, and
# is quite different from the ordinary General Public License. We use
# this license for certain libraries in order to permit linking those
# libraries into non-free programs.
#
# When a program is linked with a library, whether statically or using
# a shared library, the combination of the two is legally speaking a
# combined work, a derivative of the original library. The ordinary
# General Public License therefore permits such linking only if the
# entire combination fits its criteria of freedom. The Lesser General
# Public License permits more lax criteria for linking other code with
# the library.
#
# We call this license the "Lesser" General Public License because it
# does Less to protect the user's freedom than the ordinary General
# Public License. It also provides other free software developers Less
# of an advantage over competing non-free programs. These disadvantages
# are the reason we use the ordinary General Public License for many
# libraries. However, the Lesser license provides advantages in certain
# special circumstances.
#
# For example, on rare occasions, there may be a special need to
# encourage the widest possible use of a certain library, so that it becomes
# a de-facto standard. To achieve this, non-free programs must be
# allowed to use the library. A more frequent case is that a free
# library does the same job as widely used non-free libraries. In this
# case, there is little to gain by limiting the free library to free
# software only, so we use the Lesser General Public License.
#
# In other cases, permission to use a particular library in non-free
# programs enables a greater number of people to use a large body of
# free software. For example, permission to use the GNU C Library in
# non-free programs enables many more people to use the whole GNU
# operating system, as well as its variant, the GNU/Linux operating
# system.
#
# Although the Lesser General Public License is Less protective of the
# users' freedom, it does ensure that the user of a program that is
# linked with the Library has the freedom and the wherewithal to run
# that program using a modified version of the Library.
#
# The precise terms and conditions for copying, distribution and
# modification follow. Pay close attention to the difference between a
# "work based on the library" and a "work that uses the library". The
# former contains code derived from the library, whereas the latter must
# be combined with the library in order to run.
#
# GNU LESSER GENERAL PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. This License Agreement applies to any software library or other
# program which contains a notice placed by the copyright holder or
# other authorized party saying it may be distributed under the terms of
# this Lesser General Public License (also called "this License").
# Each licensee is addressed as "you".
#
# A "library" means a collection of software functions and/or data
# prepared so as to be conveniently linked with application programs
# (which use some of those functions and data) to form executables.
#
# The "Library", below, refers to any such software library or work
# which has been distributed under these terms. A "work based on the
# Library" means either the Library or any derivative work under
# copyright law: that is to say, a work containing the Library or a
# portion of it, either verbatim or with modifications and/or translated
# straightforwardly into another language. (Hereinafter, translation is
# included without limitation in the term "modification".)
#
# "Source code" for a work means the preferred form of the work for
# making modifications to it. For a library, complete source code means
# all the source code for all modules it contains, plus any associated
# interface definition files, plus the scripts used to control compilation
# and installation of the library.
#
# Activities other than copying, distribution and modification are not
# covered by this License; they are outside its scope. The act of
# running a program using the Library is not restricted, and output from
# such a program is covered only if its contents constitute a work based
# on the Library (independent of the use of the Library in a tool for
# writing it). Whether that is true depends on what the Library does
# and what the program that uses the Library does.
#
# 1. You may copy and distribute verbatim copies of the Library's
# complete source code as you receive it, in any medium, provided that
# you conspicuously and appropriately publish on each copy an
# appropriate copyright notice and disclaimer of warranty; keep intact
# all the notices that refer to this License and to the absence of any
# warranty; and distribute a copy of this License along with the
# Library.
#
# You may charge a fee for the physical act of transferring a copy,
# and you may at your option offer warranty protection in exchange for a
# fee.
#
# 2. You may modify your copy or copies of the Library or any portion
# of it, thus forming a work based on the Library, and copy and
# distribute such modifications or work under the terms of Section 1
# above, provided that you also meet all of these conditions:
#
# a) The modified work must itself be a software library.
#
# b) You must cause the files modified to carry prominent notices
# stating that you changed the files and the date of any change.
#
# c) You must cause the whole of the work to be licensed at no
# charge to all third parties under the terms of this License.
#
# d) If a facility in the modified Library refers to a function or a
# table of data to be supplied by an application program that uses
# the facility, other than as an argument passed when the facility
# is invoked, then you must make a good faith effort to ensure that,
# in the event an application does not supply such function or
# table, the facility still operates, and performs whatever part of
# its purpose remains meaningful.
#
# (For example, a function in a library to compute square roots has
# a purpose that is entirely well-defined independent of the
# application. Therefore, Subsection 2d requires that any
# application-supplied function or table used by this function must
# be optional: if the application does not supply it, the square
# root function must still compute square roots.)
#
# These requirements apply to the modified work as a whole. If
# identifiable sections of that work are not derived from the Library,
# and can be reasonably considered independent and separate works in
# themselves, then this License, and its terms, do not apply to those
# sections when you distribute them as separate works. But when you
# distribute the same sections as part of a whole which is a work based
# on the Library, the distribution of the whole must be on the terms of
# this License, whose permissions for other licensees extend to the
# entire whole, and thus to each and every part regardless of who wrote
# it.
#
# Thus, it is not the intent of this section to claim rights or contest
# your rights to work written entirely by you; rather, the intent is to
# exercise the right to control the distribution of derivative or
# collective works based on the Library.
#
# In addition, mere aggregation of another work not based on the Library
# with the Library (or with a work based on the Library) on a volume of
# a storage or distribution medium does not bring the other work under
# the scope of this License.
#
# 3. You may opt to apply the terms of the ordinary GNU General Public
# License instead of this License to a given copy of the Library. To do
# this, you must alter all the notices that refer to this License, so
# that they refer to the ordinary GNU General Public License, version 2,
# instead of to this License. (If a newer version than version 2 of the
# ordinary GNU General Public License has appeared, then you can specify
# that version instead if you wish.) Do not make any other change in
# these notices.
#
# Once this change is made in a given copy, it is irreversible for
# that copy, so the ordinary GNU General Public License applies to all
# subsequent copies and derivative works made from that copy.
#
# This option is useful when you wish to copy part of the code of
# the Library into a program that is not a library.
#
# 4. You may copy and distribute the Library (or a portion or
# derivative of it, under Section 2) in object code or executable form
# under the terms of Sections 1 and 2 above provided that you accompany
# it with the complete corresponding machine-readable source code, which
# must be distributed under the terms of Sections 1 and 2 above on a
# medium customarily used for software interchange.
#
# If distribution of object code is made by offering access to copy
# from a designated place, then offering equivalent access to copy the
# source code from the same place satisfies the requirement to
# distribute the source code, even though third parties are not
# compelled to copy the source along with the object code.
#
# 5. A program that contains no derivative of any portion of the
# Library, but is designed to work with the Library by being compiled or
# linked with it, is called a "work that uses the Library". Such a
# work, in isolation, is not a derivative work of the Library, and
# therefore falls outside the scope of this License.
#
# However, linking a "work that uses the Library" with the Library
# creates an executable that is a derivative of the Library (because it
# contains portions of the Library), rather than a "work that uses the
# library". The executable is therefore covered by this License.
# Section 6 states terms for distribution of such executables.
#
# When a "work that uses the Library" uses material from a header file
# that is part of the Library, the object code for the work may be a
# derivative work of the Library even though the source code is not.
# Whether this is true is especially significant if the work can be
# linked without the Library, or if the work is itself a library. The
# threshold for this to be true is not precisely defined by law.
#
# If such an object file uses only numerical parameters, data
# structure layouts and accessors, and small macros and small inline
# functions (ten lines or less in length), then the use of the object
# file is unrestricted, regardless of whether it is legally a derivative
# work. (Executables containing this object code plus portions of the
# Library will still fall under Section 6.)
#
# Otherwise, if the work is a derivative of the Library, you may
# distribute the object code for the work under the terms of Section 6.
# Any executables containing that work also fall under Section 6,
# whether or not they are linked directly with the Library itself.
#
# 6. As an exception to the Sections above, you may also combine or
# link a "work that uses the Library" with the Library to produce a
# work containing portions of the Library, and distribute that work
# under terms of your choice, provided that the terms permit
# modification of the work for the customer's own use and reverse
# engineering for debugging such modifications.
#
# You must give prominent notice with each copy of the work that the
# Library is used in it and that the Library and its use are covered by
# this License. You must supply a copy of this License. If the work
# during execution displays copyright notices, you must include the
# copyright notice for the Library among them, as well as a reference
# directing the user to the copy of this License. Also, you must do one
# of these things:
#
# a) Accompany the work with the complete corresponding
# machine-readable source code for the Library including whatever
# changes were used in the work (which must be distributed under
# Sections 1 and 2 above); and, if the work is an executable linked
# with the Library, with the complete machine-readable "work that
# uses the Library", as object code and/or source code, so that the
# user can modify the Library and then relink to produce a modified
# executable containing the modified Library. (It is understood
# that the user who changes the contents of definitions files in the
# Library will not necessarily be able to recompile the application
# to use the modified definitions.)
#
# b) Use a suitable shared library mechanism for linking with the
# Library. A suitable mechanism is one that (1) uses at run time a
# copy of the library already present on the user's computer system,
# rather than copying library functions into the executable, and (2)
# will operate properly with a modified version of the library, if
# the user installs one, as long as the modified version is
# interface-compatible with the version that the work was made with.
#
# c) Accompany the work with a written offer, valid for at
# least three years, to give the same user the materials
# specified in Subsection 6a, above, for a charge no more
# than the cost of performing this distribution.
#
# d) If distribution of the work is made by offering access to copy
# from a designated place, offer equivalent access to copy the above
# specified materials from the same place.
#
# e) Verify that the user has already received a copy of these
# materials or that you have already sent this user a copy.
#
# For an executable, the required form of the "work that uses the
# Library" must include any data and utility programs needed for
# reproducing the executable from it. However, as a special exception,
# the materials to be distributed need not include anything that is
# normally distributed (in either source or binary form) with the major
# components (compiler, kernel, and so on) of the operating system on
# which the executable runs, unless that component itself accompanies
# the executable.
#
# It may happen that this requirement contradicts the license
# restrictions of other proprietary libraries that do not normally
# accompany the operating system. Such a contradiction means you cannot
# use both them and the Library together in an executable that you
# distribute.
#
# 7. You may place library facilities that are a work based on the
# Library side-by-side in a single library together with other library
# facilities not covered by this License, and distribute such a combined
# library, provided that the separate distribution of the work based on
# the Library and of the other library facilities is otherwise
# permitted, and provided that you do these two things:
#
# a) Accompany the combined library with a copy of the same work
# based on the Library, uncombined with any other library
# facilities. This must be distributed under the terms of the
# Sections above.
#
# b) Give prominent notice with the combined library of the fact
# that part of it is a work based on the Library, and explaining
# where to find the accompanying uncombined form of the same work.
#
# 8. You may not copy, modify, sublicense, link with, or distribute
# the Library except as expressly provided under this License. Any
# attempt otherwise to copy, modify, sublicense, link with, or
# distribute the Library is void, and will automatically terminate your
# rights under this License. However, parties who have received copies,
# or rights, from you under this License will not have their licenses
# terminated so long as such parties remain in full compliance.
#
# 9. You are not required to accept this License, since you have not
# signed it. However, nothing else grants you permission to modify or
# distribute the Library or its derivative works. These actions are
# prohibited by law if you do not accept this License. Therefore, by
# modifying or distributing the Library (or any work based on the
# Library), you indicate your acceptance of this License to do so, and
# all its terms and conditions for copying, distributing or modifying
# the Library or works based on it.
#
# 10. Each time you redistribute the Library (or any work based on the
# Library), the recipient automatically receives a license from the
# original licensor to copy, distribute, link with or modify the Library
# subject to these terms and conditions. You may not impose any further
# restrictions on the recipients' exercise of the rights granted herein.
# You are not responsible for enforcing compliance by third parties with
# this License.
#
# 11. If, as a consequence of a court judgment or allegation of patent
# infringement or for any other reason (not limited to patent issues),
# conditions are imposed on you (whether by court order, agreement or
# otherwise) that contradict the conditions of this License, they do not
# excuse you from the conditions of this License. If you cannot
# distribute so as to satisfy simultaneously your obligations under this
# License and any other pertinent obligations, then as a consequence you
# may not distribute the Library at all. For example, if a patent
# license would not permit royalty-free redistribution of the Library by
# all those who receive copies directly or indirectly through you, then
# the only way you could satisfy both it and this License would be to
# refrain entirely from distribution of the Library.
#
# If any portion of this section is held invalid or unenforceable under any
# particular circumstance, the balance of the section is intended to apply,
# and the section as a whole is intended to apply in other circumstances.
#
# It is not the purpose of this section to induce you to infringe any
# patents or other property right claims or to contest validity of any
# such claims; this section has the sole purpose of protecting the
# integrity of the free software distribution system which is
# implemented by public license practices. Many people have made
# generous contributions to the wide range of software distributed
# through that system in reliance on consistent application of that
# system; it is up to the author/donor to decide if he or she is willing
# to distribute software through any other system and a licensee cannot
# impose that choice.
#
# This section is intended to make thoroughly clear what is believed to
# be a consequence of the rest of this License.
#
# 12. If the distribution and/or use of the Library is restricted in
# certain countries either by patents or by copyrighted interfaces, the
# original copyright holder who places the Library under this License may add
# an explicit geographical distribution limitation excluding those countries,
# so that distribution is permitted only in or among countries not thus
# excluded. In such case, this License incorporates the limitation as if
# written in the body of this License.
#
# 13. The Free Software Foundation may publish revised and/or new
# versions of the Lesser General Public License from time to time.
# Such new versions will be similar in spirit to the present version,
# but may differ in detail to address new problems or concerns.
#
# Each version is given a distinguishing version number. If the Library
# specifies a version number of this License which applies to it and
# "any later version", you have the option of following the terms and
# conditions either of that version or of any later version published by
# the Free Software Foundation. If the Library does not specify a
# license version number, you may choose any version ever published by
# the Free Software Foundation.
#
# 14. If you wish to incorporate parts of the Library into other free
# programs whose distribution conditions are incompatible with these,
# write to the author to ask for permission. For software which is
# copyrighted by the Free Software Foundation, write to the Free
# Software Foundation; we sometimes make exceptions for this. Our
# decision will be guided by the two goals of preserving the free status
# of all derivatives of our free software and of promoting the sharing
# and reuse of software generally.
#
# NO WARRANTY
#
# 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
# WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
# EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
# OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
# KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
# LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
# THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
#
# 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
# WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
# AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
# FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
# CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
# LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
# RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
# FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
# SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGES.
#
# END OF TERMS AND CONDITIONS
#
#
# ======================================================================
#
# How to Apply These Terms to Your New Libraries
#
# If you develop a new library, and you want it to be of the greatest
# possible use to the public, we recommend making it free software that
# everyone can redistribute and change. You can do so by permitting
# redistribution under these terms (or, alternatively, under the terms
# of the ordinary General Public License).
#
# To apply these terms, attach the following notices to the library.
# It is safest to attach them to the start of each source file to most
# effectively convey the exclusion of warranty; and each file should
# have at least the "copyright" line and a pointer to where the full
# notice is found.
#
#
# <one line to give the library's name and a brief idea of what it does.>
# Copyright (C) <year> <name of author>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# Also add information on how to contact you by electronic and paper mail.
#
# You should also get your employer (if you work as a programmer) or
# your school, if any, to sign a "copyright disclaimer" for the library,
# if necessary. Here is a sample; alter the names:
#
# Yoyodyne, Inc., hereby disclaims all copyright interest in the
# library `Frob' (a library for tweaking knobs) written by James
# Random Hacker.
#
# <signature of Ty Coon>, 1 April 1990
# Ty Coon, President of Vice
#
# That's all there is to it!
#
# LICENSE FOR ocaml-ci-scripts:
#
# ## ISC License
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# LICENSE FOR patdiff:
#
# The MIT License
#
# Copyright (c) 2005--2021 Jane Street Group, LLC <opensource@janestreet.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# LICENSE FOR lwt:
#
# Copyright (c) 1999-2020, the Authors of Lwt (docs/AUTHORS)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# LICENSE FOR toml:
#
# GNU Lesser General Public License
# =================================
#
# _Version 3, 29 June 2007_
# _Copyright © 2007 Free Software Foundation, Inc. <<http://fsf.org/>>_
#
# Everyone is permitted to copy and distribute verbatim copies
# of this license document, but changing it is not allowed.
#
#
# This version of the GNU Lesser General Public License incorporates
# the terms and conditions of version 3 of the GNU General Public
# License, supplemented by the additional permissions listed below.
#
# ### 0. Additional Definitions
#
# As used herein, “this License” refers to version 3 of the GNU Lesser
# General Public License, and the “GNU GPL” refers to version 3 of the GNU
# General Public License.
#
# “The Library” refers to a covered work governed by this License,
# other than an Application or a Combined Work as defined below.
#
# An “Application” is any work that makes use of an interface provided
# by the Library, but which is not otherwise based on the Library.
# Defining a subclass of a class defined by the Library is deemed a mode
# of using an interface provided by the Library.
#
# A “Combined Work” is a work produced by combining or linking an
# Application with the Library. The particular version of the Library
# with which the Combined Work was made is also called the “Linked
# Version”.
#
# The “Minimal Corresponding Source” for a Combined Work means the
# Corresponding Source for the Combined Work, excluding any source code
# for portions of the Combined Work that, considered in isolation, are
# based on the Application, and not on the Linked Version.
#
# The “Corresponding Application Code” for a Combined Work means the
# object code and/or source code for the Application, including any data
# and utility programs needed for reproducing the Combined Work from the
# Application, but excluding the System Libraries of the Combined Work.
#
# ### 1. Exception to Section 3 of the GNU GPL
#
# You may convey a covered work under sections 3 and 4 of this License
# without being bound by section 3 of the GNU GPL.
#
# ### 2. Conveying Modified Versions
#
# If you modify a copy of the Library, and, in your modifications, a
# facility refers to a function or data to be supplied by an Application
# that uses the facility (other than as an argument passed when the
# facility is invoked), then you may convey a copy of the modified
# version:
#
# * **a)** under this License, provided that you make a good faith effort to
# ensure that, in the event an Application does not supply the
# function or data, the facility still operates, and performs
# whatever part of its purpose remains meaningful, or
#
# * **b)** under the GNU GPL, with none of the additional permissions of
# this License applicable to that copy.
#
# ### 3. Object Code Incorporating Material from Library Header Files
#
# The object code form of an Application may incorporate material from
# a header file that is part of the Library. You may convey such object
# code under terms of your choice, provided that, if the incorporated
# material is not limited to numerical parameters, data structure
# layouts and accessors, or small macros, inline functions and templates
# (ten or fewer lines in length), you do both of the following:
#
# * **a)** Give prominent notice with each copy of the object code that the
# Library is used in it and that the Library and its use are
# covered by this License.
# * **b)** Accompany the object code with a copy of the GNU GPL and this license
# document.
#
# ### 4. Combined Works
#
# You may convey a Combined Work under terms of your choice that,
# taken together, effectively do not restrict modification of the
# portions of the Library contained in the Combined Work and reverse
# engineering for debugging such modifications, if you also do each of
# the following:
#
# * **a)** Give prominent notice with each copy of the Combined Work that
# the Library is used in it and that the Library and its use are
# covered by this License.
#
# * **b)** Accompany the Combined Work with a copy of the GNU GPL and this license
# document.
#
# * **c)** For a Combined Work that displays copyright notices during
# execution, include the copyright notice for the Library among
# these notices, as well as a reference directing the user to the
# copies of the GNU GPL and this license document.
#
# * **d)** Do one of the following:
# - **0)** Convey the Minimal Corresponding Source under the terms of this
# License, and the Corresponding Application Code in a form
# suitable for, and under terms that permit, the user to
# recombine or relink the Application with a modified version of
# the Linked Version to produce a modified Combined Work, in the
# manner specified by section 6 of the GNU GPL for conveying
# Corresponding Source.
# - **1)** Use a suitable shared library mechanism for linking with the
# Library. A suitable mechanism is one that **(a)** uses at run time
# a copy of the Library already present on the user's computer
# system, and **(b)** will operate properly with a modified version
# of the Library that is interface-compatible with the Linked
# Version.
#
# * **e)** Provide Installation Information, but only if you would otherwise
# be required to provide such information under section 6 of the
# GNU GPL, and only to the extent that such information is
# necessary to install and execute a modified version of the
# Combined Work produced by recombining or relinking the
# Application with a modified version of the Linked Version. (If
# you use option **4d0**, the Installation Information must accompany
# the Minimal Corresponding Source and Corresponding Application
# Code. If you use option **4d1**, you must provide the Installation
# Information in the manner specified by section 6 of the GNU GPL
# for conveying Corresponding Source.)
#
# ### 5. Combined Libraries
#
# You may place library facilities that are a work based on the
# Library side by side in a single library together with other library
# facilities that are not Applications and are not covered by this
# License, and convey such a combined library under terms of your
# choice, if you do both of the following:
#
# * **a)** Accompany the combined library with a copy of the same work based
# on the Library, uncombined with any other library facilities,
# conveyed under the terms of this License.
# * **b)** Give prominent notice with the combined library that part of it
# is a work based on the Library, and explaining where to find the
# accompanying uncombined form of the same work.
#
# ### 6. Revised Versions of the GNU Lesser General Public License
#
# The Free Software Foundation may publish revised and/or new versions
# of the GNU Lesser General Public License from time to time. Such new
# versions will be similar in spirit to the present version, but may
# differ in detail to address new problems or concerns.
#
# Each version is given a distinguishing version number. If the
# Library as you received it specifies that a certain numbered version
# of the GNU Lesser General Public License “or any later version”
# applies to it, you have the option of following the terms and
# conditions either of that published version or of any later version
# published by the Free Software Foundation. If the Library as you
# received it does not specify a version number of the GNU Lesser
# General Public License, you may choose any version of the GNU Lesser
# General Public License ever published by the Free Software Foundation.
#
# If the Library as you received it specifies that a proxy can decide
# whether future versions of the GNU Lesser General Public License shall
# apply, that proxy's public statement of acceptance of any version is
# permanent authorization for you to choose that version for the
# Library.
#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.