text
stringlengths 1
1.05M
|
|---|
<reponame>igor-buzhinsky/nusmv_counterexample_visualizer
package nusmv_counterexample_visualizer;
/**
* Created by buzhinsky on 9/3/17.
*/
class VarNameCause {
private final int position;
private final String varName;
VarNameCause(int position, String varName) {
this.position = position;
this.varName = varName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VarNameCause clause = (VarNameCause) o;
return position == clause.position && varName.equals(clause.varName);
}
@Override
public int hashCode() {
int result = position;
result = 31 * result + varName.hashCode();
return result;
}
@Override
public String toString() {
return varName + "@" + position;
}
}
|
#!/usr/bin/env sh
# A script that is executed when `tem env` is run. The file name must not have a .pre
# or .post suffix.
#
# In order to be run correctly, it must be executable by the user (you might
# need a shebang).
# Alternatively, if you want to source this file using your current shell, you
# must have the appropriate extension installed and this file name must have the
# appropriate suffix (e.g. .bash, .zsh or .fish)
#
# Note: tem will first try to execute the file. The file will be sourced into
# the shell only if it fails to execute.
|
#include <iostream>
#include <unordered_map>
enum Interrupt {
SYSCTL,
FLASH,
GPIOF,
UART2,
SSI1,
TIMER3A,
TIMER3B,
I2C1,
QEI1,
CAN0,
CAN1,
};
int getInterruptNumber(Interrupt interrupt) {
static const std::unordered_map<Interrupt, int> interruptMap = {
{Interrupt::SYSCTL, 28},
{Interrupt::FLASH, 29},
{Interrupt::GPIOF, 30},
{Interrupt::UART2, 33},
{Interrupt::SSI1, 34},
{Interrupt::TIMER3A, 35},
{Interrupt::TIMER3B, 36},
{Interrupt::I2C1, 37},
{Interrupt::QEI1, 38},
{Interrupt::CAN0, 39},
{Interrupt::CAN1, 40}
};
auto it = interruptMap.find(interrupt);
if (it != interruptMap.end()) {
return it->second;
} else {
return -1;
}
}
int main() {
std::cout << getInterruptNumber(Interrupt::SSI1) << std::endl; // Output: 34
std::cout << getInterruptNumber(Interrupt::CAN1) << std::endl; // Output: 40
std::cout << getInterruptNumber(Interrupt::ADC) << std::endl; // Output: -1
return 0;
}
|
def pick_first_round():
global first_round_post_iss, rounds_avail
reducer = lambda x, y: x.intersection(y) # Define a set intersection reducer function
first_round_post_iss = min(reduce(reducer, rounds_avail.values())) # Find the minimum common number
|
#!/bin/sh
### BEGIN INIT INFO
# Provides: scsitools
# Required-Start: checkroot
# Required-Stop:
# X-Start-Before: checkfs
# Default-Start: S
# Default-Stop:
# Short-Description: Create aliases for SCSI devices under /dev/scsi
### END INIT INFO
#
# This is the second part of populating /dev/scsi. Now / is writable, so
# remove the ramdisk and recreate the tree.
# When used with restart/force-reload argument, also rescan the SCSI bus to be
# sure the contents of /dev/scsi is in sync with accessible hardware.
#
# Written by Eric Delaunay <delaunay@debian.org> based on sources found in
# scsidev 2.10 from Kurt Garloff <garloff@suse.de>.
#
# Licensed under GPL.
. /etc/default/rcS
scsidevrw=0 # is /dev/scsi writable at boot time?
needscsidev=0 # is scsidev needed at all?
swapdev=0 # is there swap device on /dev/scsi/... ?
# set needscsidev to 1 if /dev/scsi is referenced in /etc/fstab and set
# scsidevrw to 1 if /dev/scsi is a ramdisk (mounted from scsitools-pre.sh)
if [ ! -e /dev/.devfsd ]; then
if grep -q '^/dev/scsi' /etc/fstab; then
needscsidev=1
if [ ! -d /dev/scsi/lost+found ]; then
scsidevrw=1
fi
fi
fi
case "$1" in
start)
# if running from rcS, needscsidev & scsidevrw are already set by
# scsitools-pre.sh to either 0 or 1.
if [ -x /sbin/scsidev -a "$needscsidev" = 1 -a "$scsidevrw" = 0 ]; then
# no need to rerun scsidev if previously done on a writable fs by
# scsitools-pre.sh, otherwise...
echo "Setting up SCSI devices (second part)..."
# disable swap in case it is using a device under /dev/scsi
# (/dev/scsi/swapdev used to be living on a ramdisk that have to be
# destroyed)
if grep -q '^/dev/scsi/' /proc/swaps; then
swapoff -a
swapdev=1
fi
# if using a ramdisk, free it first
# (test is always true except when no support for ramdisk in kernel)
if grep -q "/dev/ram3 .*/dev/scsi" /proc/mounts; then
umount -n /dev/scsi
blockdev --flushbufs /dev/ram3
fi
/sbin/scsidev -r -q
# execute swapon again, in case we want to swap to another device
# residing out of the boot disk.
if [ $swapdev = 1 ]; then
swapon -a
fi
fi
;;
restart | force-reload)
if [ -x /sbin/scsidev -a "$needscsidev" = 1 ]; then
echo "Setting up SCSI devices..."
# rescan the SCSI bus first
/sbin/rescan-scsi-bus.sh -r -w
# then fills /dev/scsi again according to detected devices
/sbin/scsidev -r -q
fi
;;
reload)
if [ -x /sbin/scsidev -a "$needscsidev" = 1 ]; then
echo "Setting up SCSI devices..."
# only sets up /dev/scsi contents again
/sbin/scsidev -r -q
fi
;;
stop)
# nothing to stop here.
;;
*)
echo "Usage: $0 {start|stop|restart|reload|force-reload}"
exit 1
;;
esac
unset needscsidev scsidevrw
|
#!/bin/sh
echo "[`date`] hello dropin test" >> /tmp/dropin.txt
echo "[`date`] arg1=$1, arg2=$2, env1=${env1}, env2=${env2}" >> /tmp/dropin.txt
|
#!/bin/sh
set -euf
stuffDir=$HOME/.local/share/thoughts
binDir=$HOME/.local/bin
###
### This script must handle *all* "update" steps
### because it reinstalls its own caller (thoughts itself)
###
cp "$stuffDir"/thoughts-temp/.foot.html "$stuffDir"
echo "copied footer"
cp "$stuffDir"/thoughts-temp/README.md "$stuffDir"
echo "copied readme"
cp "$stuffDir"/thoughts-temp/thoughts-gitignore "$stuffDir"/.gitignore
echo "copied gitignore"
cp "$stuffDir"/thoughts-temp/parse.awk "$stuffDir"/bin
echo "copied parse"
cp "$stuffDir"/thoughts-temp/thoughts "$binDir"
echo "copied thoughts itself"
chmod +x "$binDir"/thoughts
echo "chmod thoughts"
# Handle the possibility of overwriting user's custom CSS
echo
if ! diff "$stuffDir"/thoughts-temp/.head.html "$stuffDir"/.head.html; then
echo
echo "WARNING:"
echo "The CSS in this release is different than what you currently have."
echo "It could be upstream updates, or maybe you made some customizations."
echo "Check out the diff above."
echo
echo "If you haven't made custom CSS changes, you can safely overwrite and install."
echo "If you HAVE made CSS changes, just select 'n' and the new CSS will be written somewhere else."
echo
printf "DO YOU WANT TO OVERWRITE YOUR CSS? [y/n]:"
read -r reply
if [ "$reply" = "y" ]; then
cp "$stuffDir"/thoughts-temp/.head.html "$stuffDir"
echo
echo "CSS overwritten and installed. You're good to go!"
else
cp "$stuffDir"/thoughts-temp/.head.html "$stuffDir"/.head-new.html
echo
echo "New CSS is in $HOME/.local/share/thoughts/.head-new.html"
echo "If you want, you can update the CSS yourself with \"thoughts style\""
fi
fi
rm -rf "$stuffDir"/thoughts-temp
echo
echo "Pushing changes to remote"
cd "$stuffDir"
git add .
git commit -m "update thoughts"
git push
echo "Done updating!"
exit 0
|
from dataclasses import dataclass
from datetime import datetime as Datetime
from h5py import File
from stactools.goes.enums import ProductionEnvironment
from stactools.goes.errors import GOESRAttributeError
from stactools.goes.utils import get_nc_str_attr, get_nc_datetime_attr
@dataclass
class GlobalAttributes:
title: str
summary: str
production_environment: ProductionEnvironment
start_datetime: Datetime
end_datetime: Datetime
spatial_resolution_km: float
@classmethod
def from_nc(cls, nc: File) -> "GlobalAttributes":
title = get_nc_str_attr(nc, "title")
summary = get_nc_str_attr(nc, "summary")
start_datetime = get_nc_datetime_attr(nc, "time_coverage_start")
end_datetime = get_nc_datetime_attr(nc, "time_coverage_end")
production_environment = get_nc_str_attr(nc, "production_environment")
# All resolutions have the format
# "Xkm at nadir"
res_at_nadir = get_nc_str_attr(nc, "spatial_resolution")
try:
spatial_resolution_km = float(
res_at_nadir.replace("km at nadir", ""))
except ValueError as e:
raise GOESRAttributeError(
f"Cannot parse spatial_resolution {res_at_nadir}") from e
return GlobalAttributes(title=title,
summary=summary,
production_environment=ProductionEnvironment(
production_environment),
start_datetime=start_datetime,
end_datetime=end_datetime,
spatial_resolution_km=spatial_resolution_km)
|
#!/bin/bash
fecha=$(yad --calendar \
--center \
--width=200 \
--height=150 \
--show-weeks \
--title="https://www.atareao.es" \
--text="Elige una fecha")
ans=$?
if [ $ans -eq 0 ]
then
echo "Has elegido este fecha: ${fecha}"
else
echo "No has elegido ninguna fecha"
fi
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{ title }}</h1>
<button (click)="onButton1Click()">Button 1</button>
<button (click)="onButton2Click()">Button 2</button>
`,
styles: [`
body {
background-color: {{ backgroundColor }};
}
`]
})
export class AppComponent {
title = 'Hello World';
backgroundColor = '#fff';
onButton1Click() {
this.title = 'Button 1 was clicked';
}
onButton2Click() {
this.backgroundColor = '#000';
}
}
|
#!/bin/bash
if [ ! "$1" ]; then
echo "This script requires either amd64 of arm64 as an argument"
exit 1
elif [ "$1" = "amd64" ]; then
#PLATFORM="$1"
REDHAT_PLATFORM="x86_64"
DIR_NAME="beer-blockchain-linux-x64"
else
#PLATFORM="$1"
DIR_NAME="beer-blockchain-linux-arm64"
fi
pip install setuptools_scm
# The environment variable BEER_INSTALLER_VERSION needs to be defined
# If the env variable NOTARIZE and the username and password variables are
# set, this will attempt to Notarize the signed DMG
BEER_INSTALLER_VERSION=$(python installer-version.py)
if [ ! "$BEER_INSTALLER_VERSION" ]; then
echo "WARNING: No environment variable BEER_INSTALLER_VERSION set. Using 0.0.0."
BEER_INSTALLER_VERSION="0.0.0"
fi
echo "Beer Installer Version is: $BEER_INSTALLER_VERSION"
echo "Installing npm and electron packagers"
npm install electron-packager -g
npm install electron-installer-redhat -g
echo "Create dist/"
rm -rf dist
mkdir dist
echo "Create executables with pyinstaller"
pip install pyinstaller==4.4
SPEC_FILE=$(python -c 'import beer; print(beer.PYINSTALLER_SPEC_PATH)')
pyinstaller --log-level=INFO "$SPEC_FILE"
LAST_EXIT_CODE=$?
if [ "$LAST_EXIT_CODE" -ne 0 ]; then
echo >&2 "pyinstaller failed!"
exit $LAST_EXIT_CODE
fi
cp -r dist/daemon ../beer-blockchain-gui
cd .. || exit
cd beer-blockchain-gui || exit
echo "npm build"
npm install
npm audit fix
npm run build
LAST_EXIT_CODE=$?
if [ "$LAST_EXIT_CODE" -ne 0 ]; then
echo >&2 "npm run build failed!"
exit $LAST_EXIT_CODE
fi
electron-packager . beer-blockchain --asar.unpack="**/daemon/**" --platform=linux \
--icon=src/assets/img/Beer.icns --overwrite --app-bundle-id=org.beernetwork.blockchain \
--appVersion=$BEER_INSTALLER_VERSION
LAST_EXIT_CODE=$?
if [ "$LAST_EXIT_CODE" -ne 0 ]; then
echo >&2 "electron-packager failed!"
exit $LAST_EXIT_CODE
fi
mv $DIR_NAME ../build_scripts/dist/
cd ../build_scripts || exit
if [ "$REDHAT_PLATFORM" = "x86_64" ]; then
echo "Create beer-blockchain-$BEER_INSTALLER_VERSION.rpm"
# shellcheck disable=SC2046
NODE_ROOT="$(dirname $(dirname $(which node)))"
# Disables build links from the generated rpm so that we dont conflict with other packages. See https://github.com/Beer-Network/beer-blockchain/issues/3846
# shellcheck disable=SC2086
sed -i '1s/^/%define _build_id_links none\n%global _enable_debug_package 0\n%global debug_package %{nil}\n%global __os_install_post \/usr\/lib\/rpm\/brp-compress %{nil}\n/' "$NODE_ROOT/lib/node_modules/electron-installer-redhat/resources/spec.ejs"
# Updates the requirements for building an RPM on Centos 7 to allow older version of rpm-build and not use the boolean dependencies
# See https://github.com/electron-userland/electron-installer-redhat/issues/157
# shellcheck disable=SC2086
sed -i "s#throw new Error('Please upgrade to RPM 4.13.*#console.warn('You are using RPM < 4.13')\n return { requires: [ 'gtk3', 'libnotify', 'nss', 'libXScrnSaver', 'libXtst', 'xdg-utils', 'at-spi2-core', 'libdrm', 'mesa-libgbm', 'libxcb' ] }#g" sed -i "s#throw new Error('Please upgrade to RPM 4.13.*#console.warn('You are using RPM < 4.13')\n return { requires: [ 'gtk3', 'libnotify', 'nss', 'libXScrnSaver', 'libXtst', 'xdg-utils', 'at-spi2-core', 'libdrm', 'mesa-libgbm', 'libxcb' ] }#g" $NODE_ROOT/lib/node_modules/electron-installer-redhat/src/dependencies.js
electron-installer-redhat --src dist/$DIR_NAME/ --dest final_installer/ \
--arch "$REDHAT_PLATFORM" --options.version $BEER_INSTALLER_VERSION \
--license ../LICENSE
LAST_EXIT_CODE=$?
if [ "$LAST_EXIT_CODE" -ne 0 ]; then
echo >&2 "electron-installer-redhat failed!"
exit $LAST_EXIT_CODE
fi
fi
ls final_installer/
|
package ke.co.technovation.converter;
public class ConverterException extends Exception {
/**
*
*/
private static final long serialVersionUID = 2067113606317706726L;
private Throwable throwable;
private String message;
public Throwable getThrowable() {
return throwable;
}
public String getMessage() {
return message;
}
public ConverterException(String message) {
this.message = message;
}
public ConverterException(Throwable e) {
this.throwable = e;
}
public ConverterException(String message, Throwable e) {
this.message = message;
this.throwable = e;
}
}
|
/**
* Copyright (c) 2015, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences 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.
*/
/*
* Tables for whitelist & blacklist
*/
CREATE TABLE `optBlacklistmsisdn` (
`Index` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`MSISDN` varchar(45) NOT NULL,
`API_ID` varchar(45) NOT NULL,
`API_NAME` varchar(45) NOT NULL,
`USER_ID` varchar(45) NOT NULL,
UNIQUE KEY `UNQ_blacklistmsisdn` (`API_NAME`, `MSISDN`));
--
-- Table structure for table `operators`
--
CREATE TABLE IF NOT EXISTS `optoperators` (
`ID` int(20) NOT NULL AUTO_INCREMENT,
`operatorname` varchar(45) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`created` varchar(25) DEFAULT NULL,
`created_date` timestamp NULL DEFAULT NULL,
`lastupdated` varchar(25) DEFAULT NULL,
`lastupdated_date` timestamp NULL DEFAULT NULL,
`refreshtoken` varchar(255) DEFAULT NULL,
`tokenvalidity` double DEFAULT NULL,
`tokentime` double DEFAULT NULL,
`token` varchar(255) DEFAULT NULL,
`tokenurl` varchar(255) DEFAULT NULL,
`tokenauth` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `operatorname` (`operatorname`)
);
CREATE TABLE IF NOT EXISTS `optmerchantopco_blacklist` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`application_id` int(20) DEFAULT NULL,
`operator_id` int(20) DEFAULT NULL,
`subscriber` varchar(40) DEFAULT NULL,
`merchant` varchar(255) DEFAULT NULL,
`isactive` int(11) DEFAULT '1',
`note` varchar(255) DEFAULT NULL,
`created` varchar(25) DEFAULT NULL,
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lastupdated` varchar(25) DEFAULT NULL,
`lastupdated_date` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `constr_ID` (`application_id`,`operator_id`,`subscriber`,`merchant`)
);
CREATE TABLE IF NOT EXISTS`optsubscription_WhiteList` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`subscriptionID` varchar(45) NOT NULL,
`msisdn` varchar(45) NOT NULL ,
`api_id` varchar(45) NOT NULL,
`application_id` varchar(45) NOT NULL,
PRIMARY KEY (`index`),
UNIQUE white_label_unique_con(subscriptionID, msisdn, api_id, application_id)
);
|
<reponame>SamuelThulin/SensingSugar<filename>src/components/Footer.tsx<gh_stars>0
import { Box, Button } from '@mui/material';
import React, { FC } from 'react';
import { useTranslation } from 'react-i18next';
const Footer: FC = () => {
const { t } = useTranslation('common');
return (
<Box sx={{ marginTop: 'auto' }}>
<Button
href="https://samuelthulin.com"
target="_blank"
color="inherit"
size="small"
sx={{ borderRadius: 4 }}
>
{t('about')}
</Button>
</Box>
);
};
export default Footer;
|
<reponame>lauw70/Sparta<filename>s3site_awsbinary.go<gh_stars>100-1000
// +build lambdabinary
package sparta
// NewS3Site returns a new S3Site pointer initialized with the
// static resources at the supplied path. If resources is a directory,
// the contents will be recursively archived and used to populate
// the new S3 bucket.
func NewS3Site(resources string) (*S3Site, error) {
return &S3Site{}, nil
}
|
#!/bin/bash
###
# Setup script to be executed in a bpmn.io project root (some empty folder chosen by YOU). Use if you do not want to rely on npm link.
###
base=`pwd`
echo cloning repositories
git clone git@github.com:bpmn-io/diagram-js.git
git clone git@github.com:bpmn-io/bpmn-js.git
git clone git@github.com:bpmn-io/bpmn-moddle.git
echo done.
echo setup diagram-js
cd $base/diagram-js
npm install
echo setup bpmn-moddle
cd $base/bpmn-moddle
npm install
echo setup bpmn-js
cd $base/bpmn-js
mkdir node_modules
ln -s $base/bpmn-moddle node_modules/bpmn-moddle
ln -s $base/diagram-js node_modules/diagram-js
npm install
cd $base
echo all done.
|
export interface ReportHeaderCpu {
model: string;
speed: number;
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
}
export interface ReportHeader {
event: string;
trigger: string;
filename: string;
dumpEventTime: string;
dumpEventTimeStamp: string;
processId: number;
threadId: number | null;
cwd: string;
commandLine: string[];
nodejsVersion: string;
wordSize: number;
arch: string;
platform: string;
componentVersions: {
[key: string]: string;
};
release: {
name: string;
headersUrl: string;
sourceUrl: string;
};
osName: string;
osRelease: string;
osVersion: string;
osMachine: string;
cpus: ReportHeaderCpu[];
host: string;
}
export interface ReportJSStack {
message: string;
stack: string[];
}
export interface NativeStackFrame {
pc: string;
symbol: string;
}
export interface ReportHeapSpace {
memorySize: number;
committedMemory: number;
capacity: number;
used: number;
available: number;
}
export interface ReportJSHeap {
totalMemory: number;
totalCommittedMemory: number;
usedMemory: number;
availableMemory: number;
memoryLimit: number;
heapSpaces: {
[key: string]: ReportHeapSpace;
};
}
export interface ReportResourceUsage {
userCpuSeconds: number;
kernelCpuSeconds: number;
cpuConsumptionPercent: number;
maxRss: number;
pageFaults: {
IORequired: number;
IONotRequired: number;
};
fsActivity: {
reads: number;
writes: number;
};
}
// TODO: Multiple variants, CBA for PoC
type ReportUVItem = {};
export type ReportLimit = number | 'unlimited';
export interface ReportUserLimit {
hard: ReportLimit;
soft: ReportLimit;
}
export interface DiagnosticReport {
header: ReportHeader;
javascriptStack: ReportJSStack;
nativeStack: NativeStackFrame[];
javascriptHeap: ReportJSHeap;
resourceUsage: ReportResourceUsage;
libuv: ReportUVItem[];
environmentVariables: {
[key: string]: string;
};
// not present on reports generated on win32 systems
userLimits?: {
[key: string]: ReportUserLimit;
};
sharedObjects: string[];
workers: DiagnosticReport[];
}
|
#!/bin/bash
# this script checks for env variable HTTP_PROXY and add them to settings.xml
#
if [[ $HTTP_PROXY != "" ]]; then
mvn_proxy="<proxy><id>internal</id><active>true</active><protocol>http</protocol>"
proxy=$(echo $HTTP_PROXY | sed -e "s|https://||g" | sed -e "s|http://||g")
proxy_hostp=$(echo $proxy | cut -d "@" -f2)
proxy_host=$(echo $proxy_hostp | cut -d ":" -f1)
mvn_proxy=$mvn_proxy"<host>$proxy_host</host>"
proxy_port=$(echo $proxy_hostp | cut -d ":" -f2)
mvn_proxy=$mvn_proxy"<port>$proxy_port</port>"
proxy_userp=$(echo $proxy | cut -d "@" -f1)
if [[ $proxy_userp != $proxy_hostp ]];
then
proxy_user=$(echo $proxy_userp | cut -d ":" -f1)
mvn_proxy=$mvn_proxy"<username>$proxy_user</username>"
proxy_pw=$(echo $proxy_userp | sed -e "s|$proxy_user:||g")
mvn_proxy=$mvn_proxy"<password>$proxy_pw</password>"
fi
fi
if [[ $NO_PROXY != "" ]]; then
noproxy_host=$(echo $NO_PROXY | sed -e 's|\,\.|\,\*\.|g')
noproxy_host=$(echo $noproxy_host | sed -e "s/,/|/g")
mvn_proxy=$mvn_proxy"<nonProxyHosts>$noproxy_host</nonProxyHosts>"
fi
if [[ $HTTP_PROXY != "" ]]; then
mvn_proxy=$mvn_proxy"</proxy>"
fi
echo -e $mvn_proxy > /tmp/mvn_proxy
|
package com.github.sauilitired.loggbok;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.time.format.DateTimeFormatter;
@SuppressWarnings({"WeakerAccess", "unused"}) public abstract class SimpleLogger
implements Logger, AutoCloseable {
private final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
private final String logFormat;
private final LogLevels logLevels;
private String name;
private DateTimeFormatter dateTimeFormatter;
private LogFormatter logFormatter = new StandardFormatter();
public SimpleLogger(final String logFormat, final LogLevels logLevels) {
this(Thread.currentThread().getName(), logFormat, logLevels);
}
public SimpleLogger(final String name, final String logFormat, final LogLevels logLevels) {
this(name, logFormat, logLevels, DateTimeFormatter.ofPattern("HH:mm:ss"));
}
public SimpleLogger(final String name, final String logFormat, final LogLevels logLevels,
final DateTimeFormatter dateTimeFormatter) {
this.name = name;
this.logFormat = logFormat;
this.logLevels = logLevels;
this.dateTimeFormatter = dateTimeFormatter;
}
public String getLogFormatted(final LogEntry logEntry) {
return getLogFormat().replace("%level%", this.getLogLevels().getLevel(logEntry.getLevel()))
.replace("%name%", this.getName())
.replace("%time%", this.dateTimeFormatter.format(logEntry.getTimestamp()))
.replace("%thread%", this.threadMXBean.getThreadInfo(logEntry.getThreadId()).getThreadName())
.replace("%message%", this.logFormatter.format(logEntry));
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public DateTimeFormatter getDateTimeFormatter() {
return this.dateTimeFormatter;
}
public void setDateTimeFormatter(final DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
public String getLogFormat() {
return this.logFormat;
}
public LogLevels getLogLevels() {
return this.logLevels;
}
public LogFormatter getLogFormatter() {
return this.logFormatter;
}
public void setLogFormatter(final LogFormatter logFormatter) {
this.logFormatter = logFormatter;
}
@Override public final void close() {
try {
this.stop();
} catch (final Exception e) {
throw new IllegalStateException("Failed to close the logger.", e);
}
}
}
|
# LSTM example from https://machinelearningmastery.com/lstm-autoencoders/
import numpy as np
from math import pi
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import RepeatVector
from keras.layers import TimeDistributed
from keras.utils import plot_model
import matplotlib.pyplot as plt
import my_keras.input_manipulation as massage
def raw_data(n_cycles, n_points):
return np.sin(np.arange(n_points) * (n_cycles * 2 * pi / n_points))
def reshape(xs):
return xs.reshape((1, (len(xs)), 1))
def lstm_model(n_in):
# define model
model = Sequential()
model.add(LSTM(100, activation='relu', input_shape=(n_in, 1)))
model.add(RepeatVector(n_in))
model.add(LSTM(100, activation='relu', return_sequences=True))
model.add(TimeDistributed(Dense(1)))
model.compile(optimizer='adam', loss='mse')
# fit model
model.fit(cycles, cycles, epochs=300, verbose=0)
return model
# define input sequence
n_in = 50
n_samples = 10
cycles = raw_data(3, n_in)
for i in range (n_samples - 1):
data = raw_data((i / n_samples) + 1, n_in)
cycles = np.concatenate((cycles, data), axis=None)
# reshape input into [samples, timesteps, features]
cycles = cycles.reshape(n_samples, n_in, 1)
cycles_x1 = massage.rotate(raw_data(1, n_in), int(n_in / 5))
actual = reshape(np.copy(cycles_x1))
model = lstm_model(n_in)
plot_model(model, show_shapes=True, to_file='reconstruct_lstm_autoencoder.png')
# demonstrate recreation
yhat = model.predict(actual, verbose=0)
predictions = yhat[0, :, 0]
print(predictions)
plt.plot(cycles_x1)
plt.plot(predictions)
plt.show()
|
<reponame>zzz-s-2020/s-2020
package ru.zzz.demo.sber.shs.server.impl;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import org.springframework.lang.NonNull;
import ru.zzz.demo.sber.shs.config.ServerConfig;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.SECONDS;
public class NettyServerResources {
private static final AtomicInteger THREAD_NAMES_COUNTER = new AtomicInteger();
private final NioEventLoopGroup acceptorGroup;
private final NioEventLoopGroup selectorGroup;
private NettyServerResources(NioEventLoopGroup acceptorGroup, NioEventLoopGroup selectorGroup) {
this.acceptorGroup = acceptorGroup;
this.selectorGroup = selectorGroup;
}
@NonNull
public static NettyServerResources create(ServerConfig serverConfig) {
NioEventLoopGroup acceptorGroup = new NioEventLoopGroup(serverConfig.serverAcceptorThreads(),
createThreadFactory("acceptor"));
NioEventLoopGroup selectorGroup = new NioEventLoopGroup(serverConfig.serverSelectorThreads(),
createThreadFactory("selector"));
return new NettyServerResources(acceptorGroup, selectorGroup);
}
@NonNull
public NioEventLoopGroup getAcceptorGroup() {
return acceptorGroup;
}
@NonNull
public NioEventLoopGroup getSelectorGroup() {
return selectorGroup;
}
public void shutdown() {
Future<?> acc = null;
Future<?> sel = null;
if (acceptorGroup != null)
acc = acceptorGroup.shutdownGracefully(1, 1, SECONDS);
if (acceptorGroup != null)
sel = selectorGroup.shutdownGracefully(1, 1, SECONDS);
CompletableFuture.allOf(makeCompletableFuture(acc), makeCompletableFuture(sel))
.handle((aVoid, throwable) -> {
if (throwable != null)
throwable.printStackTrace();
return CompletableFuture.completedFuture(null);
})
.join();
}
private static <T> CompletableFuture<T> makeCompletableFuture(Future<T> future) {
return (future == null) ? CompletableFuture.completedFuture(null) : CompletableFuture.supplyAsync(() -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
}
@NonNull
private static ThreadFactory createThreadFactory(String type) {
return runnable -> new Thread(runnable, "webflux-" + type + "-" + THREAD_NAMES_COUNTER.incrementAndGet());
}
}
|
/*
* Copyright (c) 2010, <NAME>, <NAME>, Cryms sagl - Switzerland. All Rights Reserved.
*
* This file is part of goGPS Project (goGPS).
*
* goGPS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* goGPS 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 goGPS. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package com.galfins.gogpsextracts;
import org.ejml.simple.SimpleMatrix;
/**
* <p>
* Class for
* </p>
*
* @author <NAME>, Cryms.com
*/
public class TopocentricCoordinates {
private SimpleMatrix topocentric = new SimpleMatrix(3, 1); /* Azimuth (az), elevation (el), distance (d) */
public TopocentricCoordinates(){
}
public TopocentricCoordinates(Coordinates origin, Coordinates target){
computeTopocentric(origin, target);
}
/**
* @param origin
*/
public TopocentricCoordinates computeTopocentric(Coordinates origin, Coordinates target) {
// // Build rotation matrix from global to local reference systems
// SimpleMatrix R = globalToLocalMatrix(origin);
//
// // Compute local vector from origin to this object coordinates
// //SimpleMatrix enu = R.mult(target.ecef.minus(origin.ecef));
// SimpleMatrix enu = R.mult(target.minusXYZ(origin));
origin.computeLocalV2(target);
double E = origin.getE();//enu.get(0);
double N = origin.getN();//enu.get(1);
double U = origin.getU();//enu.get(2);
// Compute horizontal distance from origin to this object
double hDist = Math.sqrt(Math.pow(E, 2) + Math.pow(N, 2));
// If this object is at zenith ...
if (hDist < 1e-20) {
// ... set azimuth = 0 and elevation = 90, ...
topocentric.set(0, 0, 0);
topocentric.set(1, 0, 90);
} else {
// ... otherwise compute azimuth ...
topocentric.set(0, 0, Math.toDegrees(Math.atan2(E, N)));
// ... and elevation
topocentric.set(1, 0, Math.toDegrees(Math.atan2(U, hDist)));
if (topocentric.get(0) < 0)
topocentric.set(0, 0, topocentric.get(0) + 360);
}
// Compute distance
topocentric.set( 2, 0, Math.sqrt(Math.pow(E, 2) + Math.pow(N, 2) + Math.pow(U, 2)));
return this;
}
public double getAzimuth(){
return topocentric.get(0);
}
public double getElevation(){
return topocentric.get(1);
}
public double getDistance(){
return topocentric.get(2);
}
// /**
// * @param origin
// * @return Rotation matrix from global to local reference systems
// */
// private SimpleMatrix globalToLocalMatrix(Coordinates origin) {
//
// double lam = Math.toRadians(origin.getGeodeticLongitude());
// double phi = Math.toRadians(origin.getGeodeticLatitude());
//
// double cosLam = Math.cos(lam);
// double cosPhi = Math.cos(phi);
// double sinLam = Math.sin(lam);
// double sinPhi = Math.sin(phi);
//
// double[][] data = new double[3][3];
// data[0][0] = -sinLam;
// data[0][1] = cosLam;
// data[0][2] = 0;
// data[1][0] = -sinPhi * cosLam;
// data[1][1] = -sinPhi * sinLam;
// data[1][2] = cosPhi;
// data[2][0] = cosPhi * cosLam;
// data[2][1] = cosPhi * sinLam;
// data[2][2] = sinPhi;
//
// SimpleMatrix R = new SimpleMatrix(data);
//
// return R;
// }
}
|
#ifndef CONF_SPI_H_INCLUDED
# define CONF_SPI_H_INCLUDED
# define CONF_SPI_MASTER_ENABLE true
# define CONF_SPI_SLAVE_ENABLE false
# define CONF_SPI_TIMEOUT 10000
#endif /* CONF_SPI_H_INCLUDED */
|
//Declare package
package org.firstinspires.ftc.teamcode;
//Import Hardware
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.NormalizedColorSensor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.configuration.WebcamConfiguration;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
//import org.firstinspires.ftc.teamcode.sensors.REVColorSensor;
import com.qualcomm.robotcore.hardware.DigitalChannel;
/**
* @author <NAME>
* <p>
* <b>Summary:</b>
* <p>
* This is our Hardware Map that contains all the motors, servos, and sensors that we use on the
* robot. We pull this Hardware Map in all the programs we use a part of the robot. In this program
* we intialize the encoders on the motors we want to call the encoder for.
*/
public class HardwareBeep {
// Set Public OpMode Members
public DcMotor leftFront = null;
public DcMotor leftBack = null;
public DcMotor rightFront = null;
public DcMotor rightBack = null;
public BNO055IMU imuActual = null;
// Set local OpMode Members
public com.qualcomm.robotcore.hardware.HardwareMap hwMap = null;
private ElapsedTime period = new ElapsedTime();
/**
* Initializes standard hardware interfaces
*
* @param ahwMap A reference to Hardware Map
*/
public void init(com.qualcomm.robotcore.hardware.HardwareMap ahwMap) {
// Telemetry Switches
boolean GRID_NAV_TELEMETRY_ON = true;
// Save Reference To Hardware Map
hwMap = ahwMap;
// Define Motors, Servos, and Sensors
leftFront = hwMap.get(DcMotor.class, "left_front");
leftBack = hwMap.get(DcMotor.class, "left_back");
rightFront = hwMap.get(DcMotor.class, "right_front");
rightBack = hwMap.get(DcMotor.class, "right_back");
imuActual = hwMap.get(BNO055IMU.class, "imu_actual");
// Set Motor and Servo Direction
leftFront.setDirection(DcMotor.Direction.REVERSE);
leftBack.setDirection(DcMotor.Direction.REVERSE);
rightFront.setDirection(DcMotor.Direction.FORWARD);
rightBack.setDirection(DcMotor.Direction.FORWARD);
// Set Motor to Zero Power Behavior
rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
// Set Motors to Run Without Encoders
leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
leftFront.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
leftBack.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightFront.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightBack.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// Set IMU Parameters
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.mode = BNO055IMU.SensorMode.IMU;
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.loggingEnabled = false;
// Initialize IMU
imuActual.initialize(parameters);
}
}
|
#!/bin/bash
set -e
srcdir="$1"
dstdir="$2"
DJB2BIN=out/bin/djb2
[[ ! -f ${DJB2BIN} ]] && echo "error ** please build ${DJB2BIN} at first." && exit -1;
[[ "x$srcdir" = "x" ]] && echo "usage $0 srcdir dstdir" && exit -2;
[[ "x$dstdir" = "x" ]] && echo "usage $0 srcdir dstdir" && exit -2;
mkdir -p $dstdir
function djb2all() {
for f in $(find "$srcdir" -type f -printf "%P\n"); do
dst=$(${DJB2BIN} "$f" |awk '{print $srcdir}')
echo $dst
done
}
# check if any hash collisions:
# djb2all $srcdir |wc -l
# djb2all $srcdir |wc -l |sort|uniq
files=$(djb2all $srcdir |wc -l)
files_uniq=$(djb2all $srcdir |wc -l |sort|uniq)
[[ $files != $files_uniq ]] && echo "error *** hash collisions detected!!!" && exit -3;
# gzip content to save spiffs space and speed up http response.
for f in $(find $srcdir -type f -regextype posix-extended -iregex '.*\.(css|csv|html?|js|svg|txt|xml)'); do
echo $f;
zopfli -i500 $f;
mv ${f}.gz ${f}
done
for f in $(find "$srcdir" -type f -printf "%P\n"); do
# ${DJB2BIN} "$f"
dst=$(${DJB2BIN} "$f" |awk '{print $1}')
cp $srcdir/$f $dstdir/$dst
done
|
sudo singularity pull docker://quay.io/biocontainers/gatk4:4.0.1.2--0
sudo singularity pull docker://quay.io/biocontainers/bwa:0.7.16--pl5.22.0_0
|
class SessionNotFound(Exception):
def __init__(self, sessid):
self.sessid = sessid
def __str__(self):
return "Session %s not found!" % self.sessid
|
<reponame>imos/icfpc2017
#pragma once
#include "heap/heap.h"
// http://pgkiss.web.fc2.com/cxx/parameterize-code.html
namespace agl {
// TODO: specialize for |unweighted_graph|
template<typename GraphType>
class visitor_by_distance {
public:
using W = typename GraphType::W;
visitor_by_distance(const GraphType &g) : g_(g), h_(g.num_vertices()) {}
template<typename LambdaType>
void visit(V v_source, LambdaType lmd, D d = kFwd) {
h_.decrease(v_source, 0);
while (!h_.empty()) {
V v = h_.top_vertex();
W w = h_.top_weight();
h_.pop();
if (!lmd(v, w)) continue;
for (const auto &e : g_.edges(v, d)) {
h_.decrease(to(e), w + weight(e));
}
}
h_.clear();
}
private:
const GraphType &g_;
dijkstra_heap<GraphType> h_;
};
template<typename GraphType, typename LambdaType>
void visit_by_distance(const GraphType &g, V v_source, LambdaType lmd, D d = kFwd) {
visitor_by_distance<GraphType>(g).visit(v_source, lmd, d);
}
} // namespace agl
|
import pytest
from opentrons.drivers.smoothie_drivers.constants import SMOOTHIE_COMMAND_TERMINATOR
from smoothie_connection import SmoothieConnection # Assuming the class is defined in smoothie_connection module
@pytest.fixture
def mock_serial_connection() -> AsyncMock:
"""Mock serial connection."""
return AsyncMock(spec=AsyncSerial)
# Async because SmoothieConnection.__init__() needs an event loop,
# so this fixture needs to run in an event loop.
@pytest.fixture
async def subject(mock_serial_connection: AsyncMock) -> SmoothieConnection:
"""The test subject."""
return SmoothieConnection(mock_serial_connection)
@pytest.mark.asyncio
async def test_smoothie_connection_initialization(subject: SmoothieConnection, mock_serial_connection: AsyncMock):
"""Test initialization of SmoothieConnection."""
assert subject.serial_connection == mock_serial_connection
@pytest.mark.asyncio
async def test_smoothie_connection_send_command(subject: SmoothieConnection, mock_serial_connection: AsyncMock):
"""Test sending a command to SmoothieConnection."""
command = "G28.2"
expected_response = "ok\r\n"
mock_serial_connection.reset_mock() # Reset mock to clear previous calls
mock_serial_connection.read_until.return_value = expected_response.encode()
response = await subject.send_command(command)
mock_serial_connection.write.assert_called_once_with(f"{command}{SMOOTHIE_COMMAND_TERMINATOR}".encode())
assert response == expected_response
|
<reponame>trailofbits/spf-query
module SPF
module Query
#
# Represents an SPF string macro.
#
class Macro
# The macro letter.
#
# @return [Symbol]
attr_reader :letter
# Number of times the macro must be repeated.
#
# @return [Integer, nil]
attr_reader :digits
# Macro delimiter character.
#
# @return [Array<String>]
attr_reader :delimiters
#
# Initializes the macro.
#
# @param [Symbol] letter
# The macro letter.
#
# @param [Hash] options
# Additional options.
#
# @option options [Integer] :digits
# Number of times to repeat the macro.
#
# @option options [Boolean] :reverse
# Whether to reverse the value.
#
# @option options [Array<String>, String] :delimiters
# Delimiter characters.
#
def initialize(letter,options={})
@letter = letter
@digits = options[:digits]
@reverse = options[:reverse]
@delimiters = Array(options[:delimiters])
end
#
# Specifies if the macro should be reversed.
#
# @return [Boolean]
#
def reverse?
@reverse
end
#
# Converts the macro a String.
#
# @return [String]
#
def to_s
"%{#{@letter}#{@digits}#{@delimiters.join}}"
end
end
end
end
|
<reponame>diyerland/saveAll
package Test;
import auxiliary.DataSet;
import auxiliary.Evaluation;
import auxiliary.NaiveBayes;
/**
*
* @author daq
*/
public class Test {
public static void main(String[] args) {
// String[] dataPaths = new String[]{"breast-cancer.data", "segment.data"};
// for (String path : dataPaths) {
// DataSet dataset = new DataSet(path);
////
//// // conduct 10-cv
// Evaluation eva = new Evaluation(dataset, "NaiveBayes");
// eva.crossValidation();
////
//// // print mean and standard deviation of accuracy
// System.out.println("Dataset:" + path + ", mean and standard deviation of accuracy:" + eva.getAccMean() + "," + eva.getAccStd());
// }
//本例改为医院隐形眼镜的状况和患者之间的关系
//contactLensData[0]={1, 1, 1, 1}
//第一个1代表患者年龄:1:年轻 2:中年 3:老年
//第二个1代表使用眼镜:1:近视 2:远视
//第三个1代表散光:1:不是散光 2:散光
//第四个1代表影响流眼泪:1:流泪减少 2:流泪正常
double[][] contactLensData = {
{1, 1, 1, 1}, {1, 1, 1, 2}, {1, 1, 2, 1}, {1, 1, 2, 2},
{1, 2, 1, 1}, {1, 2, 1, 2}, {1, 2, 2, 1}, {1, 2, 2, 2},
{2, 1, 1, 1}, {2, 1, 1, 2}, {2, 1, 2, 1}, {2, 1, 2, 2},
{2, 2, 1, 1}, {2, 2, 1, 2}, {2, 2, 2, 1}, {2, 2, 2, 2},
{3, 1, 1, 1}, {3, 1, 1, 2}, {3, 1, 2, 1}, {3, 1, 2, 2},
{3, 2, 1, 1}, {3, 2, 1, 2}, {3, 2, 2, 1}, {3, 2, 2, 2}
};
//分类结果:1:应该使用硬性隐形眼镜 2:应该使用软性隐形眼镜 3:患者不适合带隐形眼镜
double[] classificationData = {
3, 2, 3, 1,
3, 2, 3, 1,
3, 2, 3, 1,
3, 2, 3, 3,
3, 3, 3, 1,
3, 2, 3, 3
};
DataSet dataset = new DataSet(null);
dataset.setIsCategory(new boolean[]{true,true,true,true});//四个属性都是离散型数据
dataset.setFeatures(contactLensData);
dataset.setLabels(classificationData);//标签或者分类
dataset.setNumAttributes(4);
dataset.setNumInstnaces(24);
// Evaluation eva = new Evaluation(dataset, "NaiveBayes");
// eva.crossValidation();
NaiveBayes naiveBayes = new NaiveBayes();
naiveBayes.train(dataset.getIsCategory(),dataset.getFeatures(),dataset.getLabels());
double result = naiveBayes.predict(new double[]{3, 2, 1, 1});
double r = result;
}
}
|
#!/bin/bash
set -ex
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
NAMESPACE=${NAMESPACE:-default}
WORKER_NS=${WORKER_NS:-test-pods}
# re-generate config
echo "#======================================
# This configuration is auto-generated.
# To update:
# Modify files in the config directory
# Run gen-config.sh to regenerate.
#======================================" > config.gen.yaml
for file in "${DIR}"/config/*; do
# shellcheck disable=SC2016 ## in case of sed expression first '' is not an actual variable to be expanded
sed -e 's@${NAMESPACE}@'"${NAMESPACE}"'@g' -e 's@${WORKER_NS}@'"${WORKER_NS}"'@g' "${file}" >> "${DIR}"/config.gen.yaml
done
|
/*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.github.blindpirate.gogradle.build;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Deal with environment related to a specific go build. For example, GOPATH/GOROOT to be used.
*/
public interface BuildManager {
/**
* Determine GOPATH to be used. If global GOPATH doesn't exist, a project-level GOPATH will be prepared.
*/
void prepareProjectGopathIfNecessary();
/**
* Get GOPATH in this build.
*
* @return the GOPATH to be used
*/
String getGopath();
/**
* Get GOPATH as a list.
*
* @return the list of GOPATHs
*/
List<Path> getGopaths();
/**
* Fork a go process and run commands specified by {@code args}, under the environments
* comprised by {@code env} + GOPATH/GOROOT/GOARCH/GOEXE, where {@code env} has higher priority.
*
* @param args the arguments to be passed to go
* @param env extra environment variables to be passed to go
* @return return code of go command
*/
int go(List<String> args, Map<String, String> env);
/**
* Fork a go process and run commands specified by {@code args}, under the environments
* comprised by {@code env} + GOPATH/GOROOT/GOARCH/GOEXE, where {@code env} has higher priority.
* <p>
* Stdout and stderr line of the forked process will be consumed by {@code stdoutLineConsumer} and
* {@code stderrLineConsumer} line by line, respectively.
* <p>
* Return code of the forked process will be consumed by {@code retcodeConsumer}.
*
* @param args the arguments to be passed to go
* @param env extra environment variables to be passed to go
* @param stdoutLineConsumer the consumer by which stdout line is consumed
* @param stderrLineConsumer the consumer by which stderr line is consumed
* @return return code of go command
*/
int go(List<String> args,
Map<String, String> env,
Consumer<String> stdoutLineConsumer,
Consumer<String> stderrLineConsumer);
int go(List<String> args,
Map<String, String> env,
Consumer<String> stdoutLineConsumer,
Consumer<String> stderrLineConsumer,
boolean continueOnFailure);
/**
* Fork a process and run commands specified by {@code args}, under the environments
* comprised by {@code env} + GOPATH/GOROOT/GOARCH/GOEXE, where {@code env} has higher priority.
* <p>
* Stdout and stderr line of the forked process will be consumed by {@code stdoutLineConsumer} and
* {@code stderrLineConsumer} line by line, respectively.
* <p>
* Return code of the forked process will be consumed by {@code retcodeConsumer}.
*
* @param args the arguments start a process
* @param env extra environment variables to be passed to go
* @param stdoutLineConsumer the consumer by which stdout line is consumed
* @param stderrLineConsumer the consumer by which stderr line is consumed
* @return return code of go command
*/
int run(List<String> args,
Map<String, String> env,
Consumer<String> stdoutLineConsumer,
Consumer<String> stderrLineConsumer);
int run(List<String> args,
Map<String, String> env,
Consumer<String> stdoutLineConsumer,
Consumer<String> stderrLineConsumer,
boolean continueOnFailure);
}
|
import random
def random_string():
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
random_string = ""
for i in range(40):
random_string += random.choice(chars)
return random_string
random_str = random_string()
print(random_str)
|
package ca.nova.gestion.controller;
import ca.nova.gestion.model.Task;
import ca.nova.gestion.services.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Map;
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class TaskController {
private final TaskService taskService;
@Autowired
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
/**
* GET /v1/task/{idWorkSheet/ -> retourne la liste des tasks
* @param idWorkSheet l'id de la work sheet voulu
* @return ArrayList {@link Task}
*
*/
@GetMapping("/v1/task/{idWorkSheet}")
public ArrayList<Task> getTasks(@PathVariable @Validated int idWorkSheet) {
return taskService.getTasks(idWorkSheet);
}
/**
* POST /v1/task
* Cree une task dans la base de donnee
* @param task
* @return idTask ajoutée
*/
@PostMapping("/v1/task")
public Map<String, Integer> insertTask(@RequestBody @Validated Task task) {
return Map.of("idTask", taskService.insertTask(task));
}
/**
* PUT /v1/task
* Mis à jour une task dans la BD
* @param task
*/
@PutMapping("/v1/task")
public void updateTask(@RequestBody @Validated Task task) {
taskService.updateTask(task);
}
/**
* DELETE /v1/task/{idTask}/
* Supprime un task de la BD avec l'id spécifié
* @param idTask
*/
@DeleteMapping("/v1/task/{idTask}")
public void deleteTask(@PathVariable @Validated int idTask) {
taskService.deleteTask(idTask);
}
}
|
#!/bin/bash
# Itilialize global variables.
APPNAME="backolo"
APPVERSION=0.0.1
RUNLOG="./$APPNAME-run.log" # Log file for script run creates in same folder as script is running from. resets on new run.
backupdest="/$APPNAME-backups"
backupname="backup"
excludes="$backupdest"
includes="/"
backuplog="$backupdest/$backupname-$(date "+%F-%H-%M-%S").log"
# Function for logging to scripts run log.
logger() {
echo "$(date "+%F-%H-%M-%S") : $1" >> $RUNLOG
}
# Reset and initialize run log file
echo "Initialize log">$RUNLOG
logger "Starting $APPNAME"
# Clearing terminal
clear
# Printing 'interface'
echo -e "\e[1;36m#\e[0m"
echo -e "\e[1;36m# $APPNAME v$APPVERSION\e[0m"
echo -e "\e[1;36m#\e[0m"
# Check if running with sudo or root priviliges.
if [ $UID != 0 ]; then
echo -e "\e[1;31mNeeds to be running with sudo or as root.\e[0m"
echo -e "Quiting"
logger "No sudo or root privileges"
exit 1
fi
# function for checking if a command got error if so print out custom error message and logg.
checkError() {
if [ $2 -gt 0 ]; then
echo -e "\e[1;31m$1\e[0m"
logger "$1"
exit $2
fi
}
# Checks if backup destination folder exists.
if [ ! -d $backupdest ]; then
echo -e "\e[1;33mBackup destination folder '$backupdest' does not exist. Creating it now.\e[0m"
logger "Backup destination folder '$backupdest' does not exist. Creating it now."
mkdir -p $backupdest 2>/dev/null
checkError "Could not create folder '$backupdest'" $?
fi
# print some information about the backup that is goind to start.
echo -e "\e[1;32mBackup destination folder is: '$backupdest'\e[0m"
logger "Backup destination folder is: '$backupdest'"
echo -e "\e[1;33mFollowing files and folders will be excluded from the backup: $excludes\e[0m"
logger "Following files and folders will be excluded from backup: $excludes"
echo -e "\e[1;33mFollowing files and folders will be included in the backup: $includes\e[0m"
logger "Following files and folders will be included in the backup: $includes"
# Ask user to start backup.
echo -e "\e[1;36mReady to start the backup? Y/n\e[0m"
read confirm
if [[ $confirm != "Y" ]]; then
checkError "Aborted by user, no backup created" 1
fi
# Start the backup.
echo "Backup starts in 10 seconds. Abort with CTRL+C"
sleep 10 &
PID=$!
i=1
sp="/-\|"
echo -n ' '
while [ -d /proc/$PID ]
do
sleep 1
echo -en "\b${sp:i++%${#sp}:1}"
done
echo -e "\n\e[1;36mBackup is running. Please hold!\e[0m"
logger "Backup started"
sleep 2
tar -cvpzf $backupdest/$backupname-$(date "+%F-%H-%M-%S").tar.gz --exclude=$excludes --one-file-system $includes 2>&1 | tee $backuplog
# Backup is complete.
echo -e "\n\e[1;32m#\e[0m"
echo -e "\e[1;32m# Backup is complete. Listing backup files below.\e[0m"
echo -e "\e[1;32m#\e[0m"
logger "Backup complete"
echo -e "\n\e[1;33mBackup destination folder is: '$backupdest'\e[0m"
ls -lh $backupdest
exit 0
|
python main.py --config-file configs/pretrain.yml \
DATASETS.DIR "Data" \
DATASETS.SOURCE "market1501" \
DATASETS.TARGET "msmt17" \
OUTPUT_DIR "log/market2msmt/pretrain" \
GPU_Device [0,1,2,3] \
MODE 'pretrain' \
MODEL.ARCH "resnet50"
|
#!/bin/sh
if [ -z "$1" ]
then
echo "Usage: fixnet.sh [ssh alias]"
fi
ssh $1 "rm /Library/Preferences/com.apple.networkextension*.plist; killall CommCenter"
|
<reponame>ACsBlack/Tkinter-GUI-Application-Development-Blueprints-Second-Edition<gh_stars>100-1000
"""
Code illustration: 8.09
Vornoi Diagrams
*** Warnig - this code takes up to a few minutes to compute ***
Tkinter GUI Application Development Blueprints
"""
from tkinter import Tk, Canvas
import random
import math
width = 800
height = 500
number_of_attractor_points = 125
def create_voronoi_diagram(canvas, w, h, number_of_attractor_points):
attractor_points = []
colors = []
for i in range(number_of_attractor_points):
attractor_points.append((random.randrange(w), random.randrange(h)))
colors.append('#%02x%02x%02x' % (random.randrange(256),
random.randrange(256),
random.randrange(256)))
for y in range(h):
for x in range(w):
minimum_distance = math.hypot(w , h )
index_of_nearest_attractor_point = -1
for i in range(number_of_attractor_points):
distance = math.hypot(attractor_points[i][0] - x, attractor_points[i][1] - y)
if distance < minimum_distance:
minimum_distance = distance
index_of_nearest_attractor_point = i
canvas.create_rectangle([x, y, x, y],
fill=colors[index_of_nearest_attractor_point], width=0)
for point in attractor_points:
x, y = point
dot = [x - 1, y - 1, x + 1, y + 1]
canvas.create_rectangle(dot, fill='blue', width=1)
root = Tk()
canvas = Canvas(root, height=height, width=width)
canvas.pack()
create_voronoi_diagram(canvas, width, height, number_of_attractor_points)
root.mainloop()
|
from typing import List
from ..mapper.types import Timestamp, AnyType, ApiInterfaceBase
class UserPresence(UserPresenceInterface):
def __init__(self):
self.presence_data = {}
def update_activity(self, user_id: int, last_activity_at_ms: str, is_active: bool, in_threads: List[str]):
self.presence_data[user_id] = {
'last_activity_at_ms': last_activity_at_ms,
'is_active': is_active,
'in_threads': in_threads
}
def is_user_active(self, user_id: int) -> bool:
if user_id in self.presence_data:
return self.presence_data[user_id]['is_active']
return False
def get_user_threads(self, user_id: int) -> List[str]:
if user_id in self.presence_data:
return self.presence_data[user_id]['in_threads']
return []
|
func animateObject(fromX: CGFloat, toX: CGFloat, duration: TimeInterval) {
// Assuming the use of UIView for iOS platform
UIView.animate(withDuration: duration, animations: {
// Update the object's frame to move it to the final X position
object.frame.origin.x = toX
})
}
|
<gh_stars>0
package com.infinities.skyport.proxy.network;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlTransient;
import org.dasein.cloud.VisibleScope;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.VLAN;
import org.dasein.cloud.network.VLANState;
import com.infinities.skyport.distributed.DistributedAtomicLong;
public class VLANProxy extends VLAN implements Serializable{
private static final long serialVersionUID = 1L;
@XmlTransient
private volatile VLAN vlan;
private String configName;
private String configId;
private final DistributedAtomicLong isLocked;
public VLANProxy(VLAN vlan, String configName, String configId, DistributedAtomicLong isLocked) {
super();
this.vlan = vlan;
this.configName = configName;
this.configId = configId;
this.isLocked = isLocked;
}
public VLAN getVlan() {
return vlan;
}
public void setVlan(VLAN vlan) {
this.vlan = vlan;
}
@Override
public String getCidr() {
return getVlan().getCidr();
}
@Override
public void setCidr(String cidr) {
getVlan().setCidr(cidr);
}
@Override
public void setCidr(@Nonnull String netmask, @Nonnull String anAddress) {
getVlan().setCidr(netmask, anAddress);
}
@Override
public String getDescription() {
return getVlan().getDescription();
}
@Override
public void setDescription(String description) {
getVlan().setDescription(description);
}
@Override
public String getName() {
return getVlan().getName();
}
@Override
public void setName(String name) {
getVlan().setName(name);
}
@Override
public String getProviderDataCenterId() {
return getVlan().getProviderDataCenterId();
}
@Override
public void setProviderDataCenterId(String providerDataCenterId) {
getVlan().setProviderDataCenterId(providerDataCenterId);
}
@Override
public String getProviderOwnerId() {
return getVlan().getProviderOwnerId();
}
@Override
public void setProviderOwnerId(String providerOwnerId) {
getVlan().setProviderOwnerId(providerOwnerId);
}
@Override
public String getProviderRegionId() {
return getVlan().getProviderRegionId();
}
@Override
public void setProviderRegionId(String providerRegionId) {
getVlan().setProviderRegionId(providerRegionId);
}
@Override
public String getProviderVlanId() {
return getVlan().getProviderVlanId();
}
@Override
public void setProviderVlanId(String providerVlanId) {
getVlan().setProviderVlanId(providerVlanId);
}
@Override
public void setDnsServers(String[] dnsServers) {
getVlan().setDnsServers(dnsServers);
}
@Override
public String[] getDnsServers() {
return getVlan().getDnsServers();
}
@Override
public void setTags(Map<String,String> tags) {
getVlan().setTags(tags);
}
@Override
public @Nonnull Map<String,String> getTags() {
return getVlan().getTags();
}
@Override
public void setVisibleScope(VisibleScope visibleScope){
getVlan().setVisibleScope(visibleScope);
}
@Override
public VisibleScope getVisibleScope(){
return getVlan().getVisibleScope();
}
@Override
public void setDomainName(String domainName) {
getVlan().setDomainName(domainName);
}
@Override
public String getDomainName() {
return getVlan().getDomainName();
}
@Override
public void setNtpServers(String[] ntpServers) {
getVlan().setNtpServers(ntpServers);
}
@Override
public String[] getNtpServers() {
return getVlan().getNtpServers();
}
@Override
public void setCurrentState(VLANState currentState) {
getVlan().setCurrentState(currentState);
}
@Override
public VLANState getCurrentState() {
return getVlan().getCurrentState();
}
@Override
public IPVersion[] getSupportedTraffic() {
return getVlan().getSupportedTraffic();
}
@Override
public void setSupportedTraffic(IPVersion ... supportedTraffic) {
getVlan().setSupportedTraffic(supportedTraffic);
}
@Override
public @Nullable String getNetworkType() {
return getVlan().getNetworkType();
}
@Override
public void setNetworkType(@Nonnull String t) {
getVlan().setNetworkType(t);
}
@Override
public void setTag(@Nonnull String key, @Nonnull String value) {
getVlan().setTag(key, value);
}
@Override
public @Nullable String getTag(@Nonnull String key) {
return getVlan().getTag(key);
}
public String getConfigName() {
return configName;
}
public void setConfigName(String configName) {
this.configName = configName;
}
public String getConfigId() {
return configId;
}
public void setConfigId(String configId) {
this.configId = configId;
}
@XmlTransient
@Transient
public boolean lock() {
return isLocked.compareAndSet(0, 1);
}
@XmlTransient
@Transient
public boolean unlock() {
return isLocked.compareAndSet(1, 0);
}
@XmlTransient
@Transient
public boolean isLocked() {
return isLocked.compareAndSet(1, 1);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((configId == null) ? 0 : configId.hashCode());
result = prime * result + ((configName == null) ? 0 : configName.hashCode());
result = prime * result + ((vlan == null) ? 0 : vlan.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
VLANProxy other = (VLANProxy) obj;
if (configId == null) {
if (other.configId != null)
return false;
} else if (!configId.equals(other.configId))
return false;
if (configName == null) {
if (other.configName != null)
return false;
} else if (!configName.equals(other.configName))
return false;
if (vlan == null) {
if (other.vlan != null)
return false;
} else if (!vlan.equals(other.vlan))
return false;
return true;
}
}
|
#!/bin/bash
set -e
BUILD_DIR=${1:?}
export GOOGLE_APPLICATION_CREDENTIALS=$BUILD_DIR/client_secrets.json
echo $GCLOUD_KEY > $GOOGLE_APPLICATION_CREDENTIALS
if [ ! -d $HOME/gcloud/google-cloud-sdk ]; then
mkdir -p $HOME/gcloud &&
wget -q https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-187.0.0-linux-x86_64.tar.gz --directory-prefix=$HOME/gcloud &&
cd $HOME/gcloud &&
tar xzf google-cloud-sdk-187.0.0-linux-x86_64.tar.gz &&
printf '\ny\n\ny\ny\n' | ./google-cloud-sdk/install.sh &&
sudo ln -s $HOME/gcloud/google-cloud-sdk/bin/gcloud /usr/local/bin/gcloud
cd $BUILD_DIR;
fi
gcloud -q config set project $GKE_PROJECT
if [ -a $GOOGLE_APPLICATION_CREDENTIALS ]; then
gcloud -q auth activate-service-account --key-file $GOOGLE_APPLICATION_CREDENTIALS;
fi
|
<reponame>fujunwei/dldt
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include <ie_preprocess.hpp>
using namespace std;
class PreProcessTests : public ::testing::Test {
protected:
virtual void TearDown() {
}
virtual void SetUp() {
}
public:
};
TEST_F(PreProcessTests, throwsOnSettingNullMeanImage) {
InferenceEngine::PreProcessInfo info;
info.init(1);
ASSERT_THROW(info.setMeanImage(InferenceEngine::Blob::Ptr(nullptr)),
InferenceEngine::details::InferenceEngineException);
}
TEST_F(PreProcessTests, throwsOnSetting2DMeanImage) {
InferenceEngine::PreProcessInfo info;
info.init(1);
InferenceEngine::Blob::Ptr blob(new InferenceEngine::TBlob<float>({ InferenceEngine::Precision::FP32,
{1, 1}, InferenceEngine::Layout::HW}));
ASSERT_THROW(info.setMeanImage(blob), InferenceEngine::details::InferenceEngineException);
}
TEST_F(PreProcessTests, throwsOnSettingWrongSizeMeanImage) {
InferenceEngine::PreProcessInfo info;
info.init(1);
InferenceEngine::TBlob<float>::Ptr blob(new InferenceEngine::TBlob<float>({ InferenceEngine::Precision::FP32,
{ 2, 1, 1 }, InferenceEngine::Layout::CHW }));
blob->allocate();
ASSERT_THROW(info.setMeanImage(blob), InferenceEngine::details::InferenceEngineException);
}
TEST_F(PreProcessTests, noThrowWithCorrectSizeMeanImage) {
InferenceEngine::PreProcessInfo info;
info.init(2);
InferenceEngine::TBlob<float>::Ptr blob(new InferenceEngine::TBlob<float>({ InferenceEngine::Precision::FP32,
{ 2, 1, 1 }, InferenceEngine::Layout::CHW }));
blob->allocate();
ASSERT_NO_THROW(info.setMeanImage(blob));
}
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-STG/model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-STG/512+0+512-rare-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_rare_words_first_half_quarter --eval_function last_quarter_eval
|
#!/bin/bash
set -e
# ====== Log helpers ======
info()
{
echo '[INFO] ' "$@"
}
warn()
{
echo '[WARN] ' "$@" >&2
}
fatal()
{
echo '[ERROR] ' "$@" >&2
exit 1
}
|
function QueueHandler(delay) {
this.delay = delay || 0;
this.tasks = [];
}
QueueHandler.prototype.submit = function (task) {
this.tasks.push(task);
if (this.tasks.length == 1) this.start();
};
QueueHandler.prototype.start = function () {
var thiz = this;
var next = function() {
if (thiz.tasks.length <= 0) return;
let task = thiz.tasks[0];
task(function () {
thiz.tasks.shift();
if (thiz.delay) {
setTimeout(next, thiz.delay)
} else {
next();
}
});
};
next();
};
module.exports = QueueHandler;
|
#!/bin/bash
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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.
pushd $(dirname "$0") > /dev/null
/bin/bash node-label.sh || exit $?
# Zookeeper
kubectl apply --overwrite=true -f zookeeper.yaml || exit $?
PYTHONPATH="../.." python -m k8sPaiLibrary.monitorTool.check_node_label_exist -k zookeeper -v "true"
ret=$?
if [ $ret -ne 0 ]; then
echo "No Zookeeper Pod in your cluster"
else
# wait until all zookeeper are ready.
PYTHONPATH="../.." python -m k8sPaiLibrary.monitorTool.check_pod_ready_status -w -k app -v zookeeper || exit $?
fi
popd > /dev/null
|
/etc/init.d/ssh start
rm -rf /tmp/hadoop-root/dfs/name
hdfs namenode -format
bash /opt/hadoop/sbin/start-dfs.sh
bash start-yarn.sh
hdfs dfs -mkdir /tmp
hdfs dfs -chmod 777 /tmp
hdfs dfs -mkdir /user
hdfs dfs -mkdir /user/root
echo
echo ======================================
echo
echo Hadoop NameNode at:
echo
echo " http://127.0.0.1:50070/"
echo
echo Yarn ResourceManager at:
echo
echo " http://127.0.0.1:8088/"
echo
echo ======================================
echo
|
##Documentation
#This program automatically performs all alignments. Nucleotide and Amino acids alingments need to be performed.
rm -f alignments/*
rm -f alignments_translated/*
mkdir alignments
mkdir alignments_translated
cd fasta_resultaten
fa=$( ls | wc -l ) #Determine how many files are present in the file.
for ((i=1;i<=${fa};i=i+1)) #Loop over all files.
do
{
file=$(ls | head -n ${i} | tail -n 1) #Fetching filename
file2=${file%.*} #Remove the original extension.
muscle -in ${file} -clwout ../alignments/$file2.aln #Performing the actual alignment. Creating .aln files.
}
done
cd ../translated_fasta #Switch to correct directory
fa=$( ls | wc -l )
for ((i=1;i<=${fa};i=i+1))
do
{
file=$(ls | head -n ${i} | tail -n 1)
file2=${file%.*}
muscle -in ${file} -clwout ../alignments_translated/$file2.aln
}
done
cd ..
|
<reponame>weltam/idylfin<filename>src/de/erichseifert/gral/plots/colors/ContinuousColorMapper.java
package de.erichseifert.gral.plots.colors;
import java.awt.Paint;
import de.erichseifert.gral.util.MathUtils;
/**
* Class that maps floating point numbers to Paint objects. This can be used to
* generate colors or gradients for various elements in a plot, e.g. lines,
* areas, etc.
*/
public abstract class ContinuousColorMapper extends AbstractColorMapper<Double> {
/** Version id for serialization. */
private static final long serialVersionUID = 4616781244057993699L;
/**
* Returns the Paint object according to the specified value.
* @param value Numeric value.
* @return Paint object.
*/
public abstract Paint get(double value);
/**
* Returns the Paint object according to the specified value. The specified
* value will be handled like a double value.
* @param value Numeric value object.
* @return Paint object.
*/
public Paint get(Number value) {
return get(value.doubleValue());
}
@Override
protected Double applyMode(Double value, Double rangeMin, Double rangeMax) {
if (value.doubleValue() >= rangeMin.doubleValue() &&
value.doubleValue() <= rangeMax.doubleValue()) {
return value;
}
Mode mode = getMode();
if (mode == Mode.REPEAT) {
return MathUtils.limit(value, rangeMin, rangeMax);
} else if (mode == Mode.CIRCULAR) {
double range = rangeMax.doubleValue() - rangeMin.doubleValue();
double i = value.doubleValue()%range;
if (i < 0.0) {
i += range;
}
return i + rangeMin.doubleValue();
}
return null;
}
}
|
#!/bin/bash
# This script builds a container image to inject the Thales Luna HSM
# PKCS11 driver and related utilties into a specified target directory.
# See thales-injector/README.md for background.
set -euxo pipefail
script_dir="$(dirname $(readlink -f "$0"))"
fatal() {
>&2 echo "fatal: $*"
exit 1
}
verify_checksum() {
calc_sum="$(sha256sum "$1"|cut -d' ' -f1)"
expected_sum="${2}"
if [ "$calc_sum" != "$expected_sum" ]
then
fatal "checksum mismatch for ${1}"
fi
return 0
}
###
### Obtain package tarball.
###
#Contents of cvclient-bin.tar.gz
cvclient_payload="gs://hsm-cvclient-bin/cvclient-min-10.1-sha256sum@1b2faa327c32a674e395e697d2e7f65c447847ce393b12354a3d82962a76ee87.tar.gz"
cvclient_version="10.1"
cvclient_sha256sum="1b2faa327c32a674e395e697d2e7f65c447847ce393b12354a3d82962a76ee87"
cvclient_path="${script_dir}/cvclient-min.tar.gz"
rm -v -f "${cvclient_path}"
gsutil cp "${cvclient_payload}" "${cvclient_path}"
verify_checksum "${cvclient_path}" "${cvclient_sha256sum}"
###
### Build Image.
###
image_repo="gcr.io/thales-hsm-driver-injector"
image_name="thaleslunahsm-plugin-injector"
image_tag="${cvclient_version}-1" # append local version.
# fully qualified image reference
image_fullname="${image_repo}/${image_name}:${image_tag}"
docker build -t "${image_fullname}" "${script_dir}"
docker push "${image_fullname}"
|
Create an AIChatbot using existing NLP frameworks and training the Chatbot with customer service related intents and questions. Provide the AIChatbot with the existing customer service data such as FAQs, customer interactions, and user feedback. Train the Chatbot using this data to enable it to generate appropriate responses to customer inquiries and requests.
|
SELECT c.id, c.name
FROM customer c
INNER JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING COUNT(o.id) >= 4;
|
from .skybet import skybet
from .teams import teams
from .games import games
|
#!/bin/bash
set -euxo pipefail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
SHORT_GIT_HASH=$(git rev-parse --short HEAD)
DOCKER_TAG=modern_cmake:$SHORT_GIT_HASH
docker build $SCRIPT_DIR/docker --tag $DOCKER_TAG --network host
docker run --volume /tmp/conan_download_cache:/tmp/conan_download_cache:rw --network host $DOCKER_TAG bash -c "git clone https://github.com/blackliner/modern_cmake /tmp/modern_cmake && cd /tmp/modern_cmake && ./pipeline.sh"
|
<html>
<head>
<title>Login</title>
<script>
function validateUsername(username) {
return username.length >= 5;
}
function validatePassword(password) {
return password.length >= 8;
}
function validateForm() {
let username = document.forms['loginForm']['username'].value;
let password = document.forms['loginForm']['password'].value;
if (!validateUsername(username) || !validatePassword(password)) {
alert('Invalid username or password!');
return false;
}
return true;
}
</script>
</head>
<body>
<form name="loginForm" onsubmit="return validateForm()">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
|
CREATE TABLE Names (
ID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
Age INT NOT NULL
);
|
<filename>fallen/Source/EngWind.cpp
// EngWind.cpp
// <NAME>, 27th July 1998.
#include <MFStdLib.h>
#include <windows.h>
#include <windowsx.h>
#include <ddlib.h>
#include <commctrl.h>
#include "resource.h"
#include "fmatrix.h"
#include "inline.h"
#include "gi.h"
#include "MapView.h"
#include "Mission.h"
#include "WayWind.h"
//---------------------------------------------------------------
extern int waypoint_colour,
waypoint_group;
extern volatile BOOL ShellActive;
extern CBYTE *GEDIT_engine_name;
extern UBYTE button_colours[][3];
extern HCURSOR GEDIT_arrow;
extern HICON GEDIT_app_icon;
extern HINSTANCE GEDIT_hinstance;
extern HMENU GEDIT_main_menu;
extern HWND GEDIT_client_wnd,
GEDIT_edit_wnd,
GEDIT_engine_wnd,
GEDIT_frame_wnd;
extern WNDCLASSEX GEDIT_class_engine;
//void GI_init();
//SLONG GI_load_map(CBYTE *name);
//---------------------------------------------------------------
void calc_camera_pos(void)
{
FMATRIX_calc(
cam_matrix,
cam_yaw,
cam_pitch,
0
);
cam_x = cam_focus_x;
cam_y = 0x100; // PAP_calc_height_at(LEDIT_cam_focus_x, LEDIT_cam_focus_z) + 0x100;
cam_z = cam_focus_z;
cam_x -= MUL64(cam_matrix[6], cam_focus_dist);
cam_y -= MUL64(cam_matrix[7], cam_focus_dist);
cam_z -= MUL64(cam_matrix[8], cam_focus_dist);
FMATRIX_vector (
cam_forward,
cam_yaw,
0
);
FMATRIX_vector (
cam_left,
(cam_yaw + 512) & 2047,
0
);
}
/*
//---------------------------------------------------------------
// WindProc for engine window.
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK engine_proc (
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
SLONG colour;
EventPoint *new_event;
HDC hdc;
HRESULT result;
PAINTSTRUCT ps;
POINT client_pos;
RECT dst,
src;
static HWND hclient_wnd,
hframe_wnd;
switch(message)
{
case WM_CREATE:
// Default setup for map view.
cam_focus_x = 64 << 8;
cam_focus_z = 64 << 8;
cam_focus_dist = 14 << 8;
cam_pitch = 1700;
cam_yaw = 0;
calc_camera_pos();
GI_render_view_into_backbuffer (
cam_x,
cam_y,
cam_z,
cam_yaw,
cam_pitch,
0
);
// Save important window handles.
hclient_wnd = GetParent(hWnd);
hframe_wnd = GetParent(hclient_wnd);
return 0;
case WM_KEYDOWN:
case WM_KEYUP:
KeyboardProc(message,wParam,lParam);
return 0;
case WM_PAINT:
hdc = BeginPaint(hWnd,&ps);
client_pos.x = 0;
client_pos.y = 0;
ClientToScreen(hWnd,&client_pos);
GetClientRect(hWnd,&src);
dst = src;
OffsetRect(&dst,client_pos.x,client_pos.y);
// Set the clipper.
result = the_display.lp_DD_Clipper->SetHWnd(0,hWnd);
// Blit the engine.
result = the_display.lp_DD_FrontSurface->Blt(&dst,the_display.lp_DD_BackSurface,&src,DDBLT_WAIT,0);
EndPaint(hWnd,&ps);
return 0;
case WM_LBUTTONDOWN:
if(map_valid && mouse_valid)
{
colour = (button_colours[waypoint_colour][0]<<16) |
(button_colours[waypoint_colour][1]<<8) |
(button_colours[waypoint_colour][2]);
new_event = MISSION_create_eventpoint();
if(new_event)
{
new_event->X = mouse_world_x;
new_event->Y = mouse_world_y;
new_event->Z = mouse_world_z;
new_event->Colour = waypoint_colour;
new_event->Group = waypoint_group;
}
}
return 0;
}
return DefMDIChildProc(hWnd,message,wParam,lParam);
}
//---------------------------------------------------------------
BOOL init_ewind(void)
{
DWORD style,
style_ex;
RECT engine_rect;
// Sneakily pretend that this was the window created by SetupHost!
// hDDLibWindow = GEDIT_frame_wnd;
hDDLibWindow = GEDIT_edit_wnd;
ShellActive = TRUE;
// Open this display using our engine window.
if(OpenDisplay(640,480,16,FLAGS_USE_3D) != 0)
return FALSE; // Couldn't open the display.
// Create engine window class.
GEDIT_class_engine.cbSize = sizeof(WNDCLASSEX);
GEDIT_class_engine.style = CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW;
GEDIT_class_engine.lpfnWndProc = engine_proc;
GEDIT_class_engine.cbClsExtra = 0;
GEDIT_class_engine.cbWndExtra = sizeof(HANDLE);
GEDIT_class_engine.hInstance = GEDIT_hinstance;
GEDIT_class_engine.hIcon = GEDIT_app_icon;
GEDIT_class_engine.hCursor = GEDIT_arrow;
GEDIT_class_engine.hbrBackground = GetStockObject(LTGRAY_BRUSH);
GEDIT_class_engine.lpszMenuName = NULL;
GEDIT_class_engine.lpszClassName = GEDIT_engine_name;
GEDIT_class_engine.hIconSm = GEDIT_app_icon;
if(!RegisterClassEx(&GEDIT_class_engine))
return FALSE; // Couldn't register the class.
return TRUE;
}
//---------------------------------------------------------------
void fini_ewind(void)
{
GI_fini();
// CloseDisplay();
DestroyWindow(GEDIT_engine_wnd);
UnregisterClass(GEDIT_engine_name, GEDIT_hinstance);
}
//---------------------------------------------------------------
BOOL open_map(MDICREATESTRUCT *mdi_create)
{
CBYTE w_name[_MAX_PATH];
DWORD style;
RECT engine_rect;
// Do a bodge load of the map.
GI_init();
map_valid = GI_load_map(map_name);
if(map_valid)
{
// The standard styles for an MDI child window.
style = WS_CHILD |WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
WS_SYSMENU | WS_CAPTION | WS_THICKFRAME |
WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
// Set the client rect size.
SetRect(&engine_rect,0,0,640,480);
AdjustWindowRect(
&engine_rect,
style,
FALSE
);
// The window name.
sprintf(w_name,"Map - %s",map_name);
// Set up the MDI Create structure.
mdi_create->szClass = GEDIT_engine_name;
mdi_create->szTitle = map_name;
mdi_create->hOwner = GEDIT_hinstance;
mdi_create->x = CW_DEFAULT;
mdi_create->y = CW_DEFAULT;
mdi_create->cx = engine_rect.right - engine_rect.left;
mdi_create->cy = engine_rect.bottom - engine_rect.top;
mdi_create->style = 0;
mdi_create->lParam = 0;
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------
#define SCROLL_RATE 4
#define ZOOM_RATE 4
#define YAW_RATE 1
#define PITCH_RATE 1
void process_ewind(void)
{
ULONG colour;
SLONG df,dl,dy,dp,dd,
dist,dx,dz;
EventPoint *current_epoint;
POINT mouse;
RECT client_rect;
if(map_valid)
{
calc_camera_pos();
df = 0;
dl = 0;
dd = 0;
dy = 0;
dp = 0;
if(Keys[KB_LEFT ]) {dl += SCROLL_RATE; }
if(Keys[KB_RIGHT]) {dl -= SCROLL_RATE; }
if(Keys[KB_UP ]) {df += SCROLL_RATE; }
if(Keys[KB_DOWN ]) {df -= SCROLL_RATE; }
if(Keys[KB_HOME ]) {dd -= ZOOM_RATE; }
if(Keys[KB_END ]) {dd += ZOOM_RATE; }
if(Keys[KB_DEL ]) {dy -= YAW_RATE; }
if(Keys[KB_PGDN ]) {dy += YAW_RATE; }
if(Keys[KB_INS ]) {dp -= PITCH_RATE; }
if(Keys[KB_PGUP ]) {dp += PITCH_RATE; }
// Are we moving?
if(ShiftFlag)
{
dl <<= 2;
df <<= 2;
dd <<= 2;
dy <<= 2;
dp <<= 2;
}
// Update position.
cam_focus_x += df * cam_forward[0] >> 12;
cam_focus_z += df * cam_forward[2] >> 12;
cam_focus_x += dl * cam_left[0] >> 12;
cam_focus_z += dl * cam_left[2] >> 12;
cam_focus_dist += dd * 16;
cam_yaw += dy * 16;
cam_pitch += dp * 16;
cam_yaw &= 2047;
cam_pitch &= 2047;
calc_camera_pos();
// Draw the engine.
GI_render_view_into_backbuffer (
cam_x,
cam_y,
cam_z,
cam_yaw,
cam_pitch,
0
);
// Get mouse position relative to engine window.
GetCursorPos(&mouse);
ScreenToClient(GEDIT_engine_wnd,&mouse);
GetClientRect(GEDIT_engine_wnd,&client_rect);
// Draw all waypoints within a certain distance of the camera.
current_epoint = used_epoints;
while(current_epoint)
{
dx = current_epoint->X - cam_x;
dz = current_epoint->Z - cam_z;
dist = QDIST2(abs(dx),abs(dz));
if(dist < (20 << 8))
{
// Draw it.
colour = (button_colours[current_epoint->Colour][0]<<16) |
(button_colours[current_epoint->Colour][1]<<8) |
(button_colours[current_epoint->Colour][2]);
GI_waypoint_draw (
mouse.x,
mouse.y,
current_epoint->X,
current_epoint->Y + 0x100,
current_epoint->Z,
colour,
0
);
}
current_epoint = current_epoint->Next;
}
// Is the mouse in the engine window?
if(PtInRect(&client_rect,mouse))
{
mouse_over = 0;
mouse_valid = GI_get_pixel_world_pos (
mouse.x,
mouse.y,
&mouse_world_x,
&mouse_world_y,
&mouse_world_z
);
}
else
{
mouse_valid = 0;
}
if(mouse_valid)
{
colour = (button_colours[waypoint_colour][0]<<16) |
(button_colours[waypoint_colour][1]<<8) |
(button_colours[waypoint_colour][2]);
GI_waypoint_draw (
mouse.x,
mouse.y,
mouse_world_x,
mouse_world_y + 0x100,
mouse_world_z,
colour,
0
);
}
InvalidateRect(GEDIT_engine_wnd, NULL, FALSE);
}
}
//---------------------------------------------------------------
*/
|
docker build -f ./Dockerfile -t backend:1.0 .
|
#!/bin/bash
function deploy
{
echo "Try to deploy to docker: " $1
docker build -t codeabovelab/$1:$2 target
docker push codeabovelab/$1:$2
}
docker login -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD"
deploy $1 $2
exit
|
def get_cavg(pairs, lang_num, min_score, max_score, bins=20, p_target=0.5):
''' Compute Cavg, using several threshold bins in [min_score, max_score].
'''
cavgs = [0.0] * (bins + 1)
precision = (max_score - min_score) / bins
for section in range(bins + 1):
threshold = min_score + section * precision
# Cavg for each lang: p_target * p_miss + sum(p_nontarget*p_fa)
target_cavg = [0.0] * lang_num
for lang in range(lang_num):
p_miss = sum(p for p, l in pairs if l == lang and p < threshold) / sum(1 for p, l in pairs if l == lang)
p_fa = sum(1 for p, l in pairs if l != lang and p < threshold) / sum(1 for p, l in pairs if l != lang)
p_nontarget = 1 - p_miss
target_cavg[lang] = p_target * p_miss + p_nontarget * p_fa
cavgs[section] = sum(target_cavg) / lang_num
return cavgs
|
# Exception CompilationError
class CompilationError(object):
pass
|
const tap = require("tap");
const test = tap.test;
const { getDom, getBooon, getAdapt } = require("./dom");
const dom = getDom();
const booon = getBooon(dom);
const adapt = getAdapt(booon);
test("model", t => {
t.plan(13);
setTimeout(() => {
const c1Node = booon("#main>.model>.c1")[0];
t.equal(c1Node.checked, true);
const c2Node = booon("#main>.model>.c2")[0];
t.equal(c2Node.checked, false);
const r1Node = booon("#main>.model>.r1")[0];
t.equal(r1Node.checked, true);
const r2Node = booon("#main>.model>.r2")[0];
t.equal(r2Node.checked, false);
const taNode = booon("#main>.model>.ta")[0];
t.equal(taNode.value, "green");
const t1Node = booon("#main>.model>.t1")[0];
t.equal(t1Node.value, "pingu");
const t2Node = booon("#main>.model>.t2")[0];
c1Node.checked = false;
submitEvent(c1Node, "input");
adapt.rad = "r2";
t1Node.value = "sok";
submitEvent(t1Node, "input");
setTimeout(() => {
t.equal(c1Node.checked, false);
t.equal(r1Node.checked, false);
t.equal(r2Node.checked, true);
t.equal(adapt.text, "sok");
t.equal(t2Node.value, "sok");
t2Node.value = "sok2";
submitEvent(t2Node, "input");
setTimeout(() => {
t.equal(adapt.text, "sok");
submitEvent(t2Node, "change");
setTimeout(() => {
t.equal(adapt.text, "sok2");
}, 300);
}, 300);
}, 300);
}, 300);
});
function submitEvent(node, event) {
const ev = dom.window.document.createEvent("HTMLEvents");
ev.initEvent(event, false, true);
node.dispatchEvent(ev);
}
|
public class Rounding {
public static void main(String[] args) {
double n = 3.403497;
// Format and round n to two decimal places
DecimalFormat df = new DecimalFormat("#.##");
double rounded = Double.valueOf(df.format(n));
System.out.println(rounded); // Output: 3.4
}
}
|
<filename>util/time.go
package util
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
const (
Hours = 1
Day = 24
Week = 24 * 7
)
// used for duration parsing for h, d, w instead of
// compiling all of them on the fly
var regexpTokens = []*regexp.Regexp{
regexp.MustCompile("([0-9]+?)h"),
regexp.MustCompile("([0-9]+?)d"),
regexp.MustCompile("([0-9]+?)w"),
}
func ParseDuration(input string) (time.Duration, error) {
durations := []int{
Hours,
Day,
Week,
}
// hours count
hours := 0
for idx, tokenRegexp := range regexpTokens {
tokenMatches := tokenRegexp.FindStringSubmatch(input)
if len(tokenMatches) > 0 {
value, err := strconv.Atoi(tokenMatches[1])
if err == nil {
hours += value * durations[idx]
input = strings.Replace(input, tokenMatches[0], "", 1)
}
}
}
// prepend hours
if hours > 0 {
input = fmt.Sprintf("%dh%s", hours, input)
}
return time.ParseDuration(input)
}
|
# Copyright 2012, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from mod_pywebsocket import common
from mod_pywebsocket import util
from mod_pywebsocket.http_header_util import quote_if_necessary
# The list of available server side extension processor classes.
_available_processors = {}
_compression_extension_names = []
class ExtensionProcessorInterface(object):
def __init__(self, request):
self._logger = util.get_class_logger(self)
self._request = request
self._active = True
def request(self):
return self._request
def name(self):
return None
def check_consistency_with_other_processors(self, processors):
pass
def set_active(self, active):
self._active = active
def is_active(self):
return self._active
def _get_extension_response_internal(self):
return None
def get_extension_response(self):
if not self._active:
self._logger.debug('Extension %s is deactivated', self.name())
return None
response = self._get_extension_response_internal()
if response is None:
self._active = False
return response
def _setup_stream_options_internal(self, stream_options):
pass
def setup_stream_options(self, stream_options):
if self._active:
self._setup_stream_options_internal(stream_options)
def _log_outgoing_compression_ratio(
logger, original_bytes, filtered_bytes, average_ratio):
# Print inf when ratio is not available.
ratio = float('inf')
if original_bytes != 0:
ratio = float(filtered_bytes) / original_bytes
logger.debug('Outgoing compression ratio: %f (average: %f)' %
(ratio, average_ratio))
def _log_incoming_compression_ratio(
logger, received_bytes, filtered_bytes, average_ratio):
# Print inf when ratio is not available.
ratio = float('inf')
if filtered_bytes != 0:
ratio = float(received_bytes) / filtered_bytes
logger.debug('Incoming compression ratio: %f (average: %f)' %
(ratio, average_ratio))
def _parse_window_bits(bits):
"""Return parsed integer value iff the given string conforms to the
grammar of the window bits extension parameters.
"""
if bits is None:
raise ValueError('Value is required')
# For non integer values such as "10.0", ValueError will be raised.
int_bits = int(bits)
# First condition is to drop leading zero case e.g. "08".
if bits != str(int_bits) or int_bits < 8 or int_bits > 15:
raise ValueError('Invalid value: %r' % bits)
return int_bits
class _AverageRatioCalculator(object):
"""Stores total bytes of original and result data, and calculates average
result / original ratio.
"""
def __init__(self):
self._total_original_bytes = 0
self._total_result_bytes = 0
def add_original_bytes(self, value):
self._total_original_bytes += value
def add_result_bytes(self, value):
self._total_result_bytes += value
def get_average_ratio(self):
if self._total_original_bytes != 0:
return (float(self._total_result_bytes) /
self._total_original_bytes)
else:
return float('inf')
class DeflateFrameExtensionProcessor(ExtensionProcessorInterface):
"""deflate-frame extension processor.
Specification:
http://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate
"""
_WINDOW_BITS_PARAM = 'max_window_bits'
_NO_CONTEXT_TAKEOVER_PARAM = 'no_context_takeover'
def __init__(self, request):
ExtensionProcessorInterface.__init__(self, request)
self._logger = util.get_class_logger(self)
self._response_window_bits = None
self._response_no_context_takeover = False
self._bfinal = False
# Calculates
# (Total outgoing bytes supplied to this filter) /
# (Total bytes sent to the network after applying this filter)
self._outgoing_average_ratio_calculator = _AverageRatioCalculator()
# Calculates
# (Total bytes received from the network) /
# (Total incoming bytes obtained after applying this filter)
self._incoming_average_ratio_calculator = _AverageRatioCalculator()
def name(self):
return common.DEFLATE_FRAME_EXTENSION
def _get_extension_response_internal(self):
# Any unknown parameter will be just ignored.
window_bits = None
if self._request.has_parameter(self._WINDOW_BITS_PARAM):
window_bits = self._request.get_parameter_value(
self._WINDOW_BITS_PARAM)
try:
window_bits = _parse_window_bits(window_bits)
except ValueError, e:
return None
no_context_takeover = self._request.has_parameter(
self._NO_CONTEXT_TAKEOVER_PARAM)
if (no_context_takeover and
self._request.get_parameter_value(
self._NO_CONTEXT_TAKEOVER_PARAM) is not None):
return None
self._rfc1979_deflater = util._RFC1979Deflater(
window_bits, no_context_takeover)
self._rfc1979_inflater = util._RFC1979Inflater()
self._compress_outgoing = True
response = common.ExtensionParameter(self._request.name())
if self._response_window_bits is not None:
response.add_parameter(
self._WINDOW_BITS_PARAM, str(self._response_window_bits))
if self._response_no_context_takeover:
response.add_parameter(
self._NO_CONTEXT_TAKEOVER_PARAM, None)
self._logger.debug(
'Enable %s extension ('
'request: window_bits=%s; no_context_takeover=%r, '
'response: window_wbits=%s; no_context_takeover=%r)' %
(self._request.name(),
window_bits,
no_context_takeover,
self._response_window_bits,
self._response_no_context_takeover))
return response
def _setup_stream_options_internal(self, stream_options):
class _OutgoingFilter(object):
def __init__(self, parent):
self._parent = parent
def filter(self, frame):
self._parent._outgoing_filter(frame)
class _IncomingFilter(object):
def __init__(self, parent):
self._parent = parent
def filter(self, frame):
self._parent._incoming_filter(frame)
stream_options.outgoing_frame_filters.append(
_OutgoingFilter(self))
stream_options.incoming_frame_filters.insert(
0, _IncomingFilter(self))
def set_response_window_bits(self, value):
self._response_window_bits = value
def set_response_no_context_takeover(self, value):
self._response_no_context_takeover = value
def set_bfinal(self, value):
self._bfinal = value
def enable_outgoing_compression(self):
self._compress_outgoing = True
def disable_outgoing_compression(self):
self._compress_outgoing = False
def _outgoing_filter(self, frame):
"""Transform outgoing frames. This method is called only by
an _OutgoingFilter instance.
"""
original_payload_size = len(frame.payload)
self._outgoing_average_ratio_calculator.add_original_bytes(
original_payload_size)
if (not self._compress_outgoing or
common.is_control_opcode(frame.opcode)):
self._outgoing_average_ratio_calculator.add_result_bytes(
original_payload_size)
return
frame.payload = self._rfc1979_deflater.filter(
frame.payload, bfinal=self._bfinal)
frame.rsv1 = 1
filtered_payload_size = len(frame.payload)
self._outgoing_average_ratio_calculator.add_result_bytes(
filtered_payload_size)
_log_outgoing_compression_ratio(
self._logger,
original_payload_size,
filtered_payload_size,
self._outgoing_average_ratio_calculator.get_average_ratio())
def _incoming_filter(self, frame):
"""Transform incoming frames. This method is called only by
an _IncomingFilter instance.
"""
received_payload_size = len(frame.payload)
self._incoming_average_ratio_calculator.add_result_bytes(
received_payload_size)
if frame.rsv1 != 1 or common.is_control_opcode(frame.opcode):
self._incoming_average_ratio_calculator.add_original_bytes(
received_payload_size)
return
frame.payload = self._rfc1979_inflater.filter(frame.payload)
frame.rsv1 = 0
filtered_payload_size = len(frame.payload)
self._incoming_average_ratio_calculator.add_original_bytes(
filtered_payload_size)
_log_incoming_compression_ratio(
self._logger,
received_payload_size,
filtered_payload_size,
self._incoming_average_ratio_calculator.get_average_ratio())
_available_processors[common.DEFLATE_FRAME_EXTENSION] = (
DeflateFrameExtensionProcessor)
_compression_extension_names.append(common.DEFLATE_FRAME_EXTENSION)
_available_processors[common.X_WEBKIT_DEFLATE_FRAME_EXTENSION] = (
DeflateFrameExtensionProcessor)
_compression_extension_names.append(common.X_WEBKIT_DEFLATE_FRAME_EXTENSION)
def _parse_compression_method(data):
"""Parses the value of "method" extension parameter."""
return common.parse_extensions(data)
def _create_accepted_method_desc(method_name, method_params):
"""Creates accepted-method-desc from given method name and parameters"""
extension = common.ExtensionParameter(method_name)
for name, value in method_params:
extension.add_parameter(name, value)
return common.format_extension(extension)
class CompressionExtensionProcessorBase(ExtensionProcessorInterface):
"""Base class for perframe-compress and permessage-compress extension."""
_METHOD_PARAM = 'method'
def __init__(self, request):
ExtensionProcessorInterface.__init__(self, request)
self._logger = util.get_class_logger(self)
self._compression_method_name = None
self._compression_processor = None
self._compression_processor_hook = None
def name(self):
return ''
def _lookup_compression_processor(self, method_desc):
return None
def _get_compression_processor_response(self):
"""Looks up the compression processor based on the self._request and
returns the compression processor's response.
"""
method_list = self._request.get_parameter_value(self._METHOD_PARAM)
if method_list is None:
return None
methods = _parse_compression_method(method_list)
if methods is None:
return None
comression_processor = None
# The current implementation tries only the first method that matches
# supported algorithm. Following methods aren't tried even if the
# first one is rejected.
# TODO(bashi): Need to clarify this behavior.
for method_desc in methods:
compression_processor = self._lookup_compression_processor(
method_desc)
if compression_processor is not None:
self._compression_method_name = method_desc.name()
break
if compression_processor is None:
return None
if self._compression_processor_hook:
self._compression_processor_hook(compression_processor)
processor_response = compression_processor.get_extension_response()
if processor_response is None:
return None
self._compression_processor = compression_processor
return processor_response
def _get_extension_response_internal(self):
processor_response = self._get_compression_processor_response()
if processor_response is None:
return None
response = common.ExtensionParameter(self._request.name())
accepted_method_desc = _create_accepted_method_desc(
self._compression_method_name,
processor_response.get_parameters())
response.add_parameter(self._METHOD_PARAM, accepted_method_desc)
self._logger.debug(
'Enable %s extension (method: %s)' %
(self._request.name(), self._compression_method_name))
return response
def _setup_stream_options_internal(self, stream_options):
if self._compression_processor is None:
return
self._compression_processor.setup_stream_options(stream_options)
def set_compression_processor_hook(self, hook):
self._compression_processor_hook = hook
def get_compression_processor(self):
return self._compression_processor
class PerMessageDeflateExtensionProcessor(ExtensionProcessorInterface):
"""permessage-deflate extension processor. It's also used for
permessage-compress extension when the deflate method is chosen.
Specification:
http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression-08
"""
_SERVER_MAX_WINDOW_BITS_PARAM = 'server_max_window_bits'
_SERVER_NO_CONTEXT_TAKEOVER_PARAM = 'server_no_context_takeover'
_CLIENT_MAX_WINDOW_BITS_PARAM = 'client_max_window_bits'
_CLIENT_NO_CONTEXT_TAKEOVER_PARAM = 'client_no_context_takeover'
def __init__(self, request, draft08=True):
"""Construct PerMessageDeflateExtensionProcessor
Args:
draft08: Follow the constraints on the parameters that were not
specified for permessage-compress but are specified for
permessage-deflate as on
draft-ietf-hybi-permessage-compression-08.
"""
ExtensionProcessorInterface.__init__(self, request)
self._logger = util.get_class_logger(self)
self._preferred_client_max_window_bits = None
self._client_no_context_takeover = False
self._draft08 = draft08
def name(self):
return 'deflate'
def _get_extension_response_internal(self):
if self._draft08:
for name in self._request.get_parameter_names():
if name not in [self._SERVER_MAX_WINDOW_BITS_PARAM,
self._SERVER_NO_CONTEXT_TAKEOVER_PARAM,
self._CLIENT_MAX_WINDOW_BITS_PARAM]:
self._logger.debug('Unknown parameter: %r', name)
return None
else:
# Any unknown parameter will be just ignored.
pass
server_max_window_bits = None
if self._request.has_parameter(self._SERVER_MAX_WINDOW_BITS_PARAM):
server_max_window_bits = self._request.get_parameter_value(
self._SERVER_MAX_WINDOW_BITS_PARAM)
try:
server_max_window_bits = _parse_window_bits(
server_max_window_bits)
except ValueError, e:
self._logger.debug('Bad %s parameter: %r',
self._SERVER_MAX_WINDOW_BITS_PARAM,
e)
return None
server_no_context_takeover = self._request.has_parameter(
self._SERVER_NO_CONTEXT_TAKEOVER_PARAM)
if (server_no_context_takeover and
self._request.get_parameter_value(
self._SERVER_NO_CONTEXT_TAKEOVER_PARAM) is not None):
self._logger.debug('%s parameter must not have a value: %r',
self._SERVER_NO_CONTEXT_TAKEOVER_PARAM,
server_no_context_takeover)
return None
# client_max_window_bits from a client indicates whether the client can
# accept client_max_window_bits from a server or not.
client_client_max_window_bits = self._request.has_parameter(
self._CLIENT_MAX_WINDOW_BITS_PARAM)
if (self._draft08 and
client_client_max_window_bits and
self._request.get_parameter_value(
self._CLIENT_MAX_WINDOW_BITS_PARAM) is not None):
self._logger.debug('%s parameter must not have a value in a '
'client\'s opening handshake: %r',
self._CLIENT_MAX_WINDOW_BITS_PARAM,
client_client_max_window_bits)
return None
self._rfc1979_deflater = util._RFC1979Deflater(
server_max_window_bits, server_no_context_takeover)
# Note that we prepare for incoming messages compressed with window
# bits upto 15 regardless of the client_max_window_bits value to be
# sent to the client.
self._rfc1979_inflater = util._RFC1979Inflater()
self._framer = _PerMessageDeflateFramer(
server_max_window_bits, server_no_context_takeover)
self._framer.set_bfinal(False)
self._framer.set_compress_outgoing_enabled(True)
response = common.ExtensionParameter(self._request.name())
if server_max_window_bits is not None:
response.add_parameter(
self._SERVER_MAX_WINDOW_BITS_PARAM,
str(server_max_window_bits))
if server_no_context_takeover:
response.add_parameter(
self._SERVER_NO_CONTEXT_TAKEOVER_PARAM, None)
if self._preferred_client_max_window_bits is not None:
if self._draft08 and not client_client_max_window_bits:
self._logger.debug('Processor is configured to use %s but '
'the client cannot accept it',
self._CLIENT_MAX_WINDOW_BITS_PARAM)
return None
response.add_parameter(
self._CLIENT_MAX_WINDOW_BITS_PARAM,
str(self._preferred_client_max_window_bits))
if self._client_no_context_takeover:
response.add_parameter(
self._CLIENT_NO_CONTEXT_TAKEOVER_PARAM, None)
self._logger.debug(
'Enable %s extension ('
'request: server_max_window_bits=%s; '
'server_no_context_takeover=%r, '
'response: client_max_window_bits=%s; '
'client_no_context_takeover=%r)' %
(self._request.name(),
server_max_window_bits,
server_no_context_takeover,
self._preferred_client_max_window_bits,
self._client_no_context_takeover))
return response
def _setup_stream_options_internal(self, stream_options):
self._framer.setup_stream_options(stream_options)
def set_client_max_window_bits(self, value):
"""If this option is specified, this class adds the
client_max_window_bits extension parameter to the handshake response,
but doesn't reduce the LZ77 sliding window size of its inflater.
I.e., you can use this for testing client implementation but cannot
reduce memory usage of this class.
If this method has been called with True and an offer without the
client_max_window_bits extension parameter is received,
- (When processing the permessage-deflate extension) this processor
declines the request.
- (When processing the permessage-compress extension) this processor
accepts the request.
"""
self._preferred_client_max_window_bits = value
def set_client_no_context_takeover(self, value):
"""If this option is specified, this class adds the
client_no_context_takeover extension parameter to the handshake
response, but doesn't reset inflater for each message. I.e., you can
use this for testing client implementation but cannot reduce memory
usage of this class.
"""
self._client_no_context_takeover = value
def set_bfinal(self, value):
self._framer.set_bfinal(value)
def enable_outgoing_compression(self):
self._framer.set_compress_outgoing_enabled(True)
def disable_outgoing_compression(self):
self._framer.set_compress_outgoing_enabled(False)
class _PerMessageDeflateFramer(object):
"""A framer for extensions with per-message DEFLATE feature."""
def __init__(self, deflate_max_window_bits, deflate_no_context_takeover):
self._logger = util.get_class_logger(self)
self._rfc1979_deflater = util._RFC1979Deflater(
deflate_max_window_bits, deflate_no_context_takeover)
self._rfc1979_inflater = util._RFC1979Inflater()
self._bfinal = False
self._compress_outgoing_enabled = False
# True if a message is fragmented and compression is ongoing.
self._compress_ongoing = False
# Calculates
# (Total outgoing bytes supplied to this filter) /
# (Total bytes sent to the network after applying this filter)
self._outgoing_average_ratio_calculator = _AverageRatioCalculator()
# Calculates
# (Total bytes received from the network) /
# (Total incoming bytes obtained after applying this filter)
self._incoming_average_ratio_calculator = _AverageRatioCalculator()
def set_bfinal(self, value):
self._bfinal = value
def set_compress_outgoing_enabled(self, value):
self._compress_outgoing_enabled = value
def _process_incoming_message(self, message, decompress):
if not decompress:
return message
received_payload_size = len(message)
self._incoming_average_ratio_calculator.add_result_bytes(
received_payload_size)
message = self._rfc1979_inflater.filter(message)
filtered_payload_size = len(message)
self._incoming_average_ratio_calculator.add_original_bytes(
filtered_payload_size)
_log_incoming_compression_ratio(
self._logger,
received_payload_size,
filtered_payload_size,
self._incoming_average_ratio_calculator.get_average_ratio())
return message
def _process_outgoing_message(self, message, end, binary):
if not binary:
message = message.encode('utf-8')
if not self._compress_outgoing_enabled:
return message
original_payload_size = len(message)
self._outgoing_average_ratio_calculator.add_original_bytes(
original_payload_size)
message = self._rfc1979_deflater.filter(
message, end=end, bfinal=self._bfinal)
filtered_payload_size = len(message)
self._outgoing_average_ratio_calculator.add_result_bytes(
filtered_payload_size)
_log_outgoing_compression_ratio(
self._logger,
original_payload_size,
filtered_payload_size,
self._outgoing_average_ratio_calculator.get_average_ratio())
if not self._compress_ongoing:
self._outgoing_frame_filter.set_compression_bit()
self._compress_ongoing = not end
return message
def _process_incoming_frame(self, frame):
if frame.rsv1 == 1 and not common.is_control_opcode(frame.opcode):
self._incoming_message_filter.decompress_next_message()
frame.rsv1 = 0
def _process_outgoing_frame(self, frame, compression_bit):
if (not compression_bit or
common.is_control_opcode(frame.opcode)):
return
frame.rsv1 = 1
def setup_stream_options(self, stream_options):
"""Creates filters and sets them to the StreamOptions."""
class _OutgoingMessageFilter(object):
def __init__(self, parent):
self._parent = parent
def filter(self, message, end=True, binary=False):
return self._parent._process_outgoing_message(
message, end, binary)
class _IncomingMessageFilter(object):
def __init__(self, parent):
self._parent = parent
self._decompress_next_message = False
def decompress_next_message(self):
self._decompress_next_message = True
def filter(self, message):
message = self._parent._process_incoming_message(
message, self._decompress_next_message)
self._decompress_next_message = False
return message
self._outgoing_message_filter = _OutgoingMessageFilter(self)
self._incoming_message_filter = _IncomingMessageFilter(self)
stream_options.outgoing_message_filters.append(
self._outgoing_message_filter)
stream_options.incoming_message_filters.append(
self._incoming_message_filter)
class _OutgoingFrameFilter(object):
def __init__(self, parent):
self._parent = parent
self._set_compression_bit = False
def set_compression_bit(self):
self._set_compression_bit = True
def filter(self, frame):
self._parent._process_outgoing_frame(
frame, self._set_compression_bit)
self._set_compression_bit = False
class _IncomingFrameFilter(object):
def __init__(self, parent):
self._parent = parent
def filter(self, frame):
self._parent._process_incoming_frame(frame)
self._outgoing_frame_filter = _OutgoingFrameFilter(self)
self._incoming_frame_filter = _IncomingFrameFilter(self)
stream_options.outgoing_frame_filters.append(
self._outgoing_frame_filter)
stream_options.incoming_frame_filters.append(
self._incoming_frame_filter)
stream_options.encode_text_message_to_utf8 = False
_available_processors[common.PERMESSAGE_DEFLATE_EXTENSION] = (
PerMessageDeflateExtensionProcessor)
# TODO(tyoshino): Reorganize class names.
_compression_extension_names.append('deflate')
class PerMessageCompressExtensionProcessor(
CompressionExtensionProcessorBase):
"""permessage-compress extension processor.
Specification:
http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression
"""
_DEFLATE_METHOD = 'deflate'
def __init__(self, request):
CompressionExtensionProcessorBase.__init__(self, request)
def name(self):
return common.PERMESSAGE_COMPRESSION_EXTENSION
def _lookup_compression_processor(self, method_desc):
if method_desc.name() == self._DEFLATE_METHOD:
return PerMessageDeflateExtensionProcessor(method_desc, False)
return None
_available_processors[common.PERMESSAGE_COMPRESSION_EXTENSION] = (
PerMessageCompressExtensionProcessor)
_compression_extension_names.append(common.PERMESSAGE_COMPRESSION_EXTENSION)
class MuxExtensionProcessor(ExtensionProcessorInterface):
"""WebSocket multiplexing extension processor."""
_QUOTA_PARAM = 'quota'
def __init__(self, request):
ExtensionProcessorInterface.__init__(self, request)
self._quota = 0
self._extensions = []
def name(self):
return common.MUX_EXTENSION
def check_consistency_with_other_processors(self, processors):
before_mux = True
for processor in processors:
name = processor.name()
if name == self.name():
before_mux = False
continue
if not processor.is_active():
continue
if before_mux:
# Mux extension cannot be used after extensions
# that depend on frame boundary, extension data field, or any
# reserved bits which are attributed to each frame.
if (name == common.DEFLATE_FRAME_EXTENSION or
name == common.X_WEBKIT_DEFLATE_FRAME_EXTENSION):
self.set_active(False)
return
else:
# Mux extension should not be applied before any history-based
# compression extension.
if (name == common.DEFLATE_FRAME_EXTENSION or
name == common.X_WEBKIT_DEFLATE_FRAME_EXTENSION or
name == common.PERMESSAGE_COMPRESSION_EXTENSION or
name == common.X_WEBKIT_PERMESSAGE_COMPRESSION_EXTENSION):
self.set_active(False)
return
def _get_extension_response_internal(self):
self._active = False
quota = self._request.get_parameter_value(self._QUOTA_PARAM)
if quota is not None:
try:
quota = int(quota)
except ValueError, e:
return None
if quota < 0 or quota >= 2 ** 32:
return None
self._quota = quota
self._active = True
return common.ExtensionParameter(common.MUX_EXTENSION)
def _setup_stream_options_internal(self, stream_options):
pass
def set_quota(self, quota):
self._quota = quota
def quota(self):
return self._quota
def set_extensions(self, extensions):
self._extensions = extensions
def extensions(self):
return self._extensions
_available_processors[common.MUX_EXTENSION] = MuxExtensionProcessor
def get_extension_processor(extension_request):
"""Given an ExtensionParameter representing an extension offer received
from a client, configures and returns an instance of the corresponding
extension processor class.
"""
processor_class = _available_processors.get(extension_request.name())
if processor_class is None:
return None
return processor_class(extension_request)
def is_compression_extension(extension_name):
return extension_name in _compression_extension_names
# vi:sts=4 sw=4 et
|
import requests.compat
def encode_unix_socket_url(url):
encoded_url = requests.compat.quote_plus(url)
return f"http+unix://{encoded_url}"
|
model.add(layers.Conv2D(filters=4, kernel_size=(3, 3), strides=(2, 2), padding='same', input_shape=(32, 128, 128, 3)))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Conv2D(filters=8, kernel_size=(3, 3), strides=(2, 2), padding='same'))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(64))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.Dense(32, activation='softmax'))
|
// Jest file stub
module.exports = 'test-file-stub'
|
def print_numbers(n):
for i in range(1, n + 1):
print(i)
|
def generate_collapsible_list(item_categories):
html_code = '<div>\n'
html_code += ' <li class="collapsable startCollapsed"><strong>Items</strong> <a href="/item/add">+</a></li>\n'
for category in item_categories:
html_code += ' <div>\n'
html_code += f' <li class="section"><a href="#{category["title"]}Items">{category["title"]} Items</a></li>\n'
for item in category["items"]:
html_code += f' <li class="subsection"><a href="#item{item["id"]}">{item["title"]}</a></li>\n'
html_code += ' </div>\n'
html_code += '</div>'
return html_code
|
package es.upm.etsisi.cf4j.data;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class TestUserTest {
private static TestUser testUser;
private static User wiredUser;
private static Item item;
private static Item wiredItem;
private static TestItem testItem;
@BeforeAll
static void initAll() {
testUser = new TestUser("202", 202, 202);
wiredUser = new TestUser("303", 303, 303);
item = new Item("010", 10);
testItem = new TestItem("020", 20, 20);
wiredItem = new TestItem("030", 30, 30);
}
@Test
void testUserInsertion() {
testUser.addTestRating(111, 1.3);
testUser.addTestRating(item.getItemIndex(), 1.0);
testUser.addTestRating(222, 2.4);
testUser.addTestRating(testItem.getTestItemIndex(), 2.0);
testUser.addTestRating(333, 3.5);
testUser.addTestRating(wiredItem.getItemIndex(), 3.0);
testUser.addRating(111, 1.3);
testUser.addRating(item.getItemIndex(), 1.0);
testUser.addRating(222, 2.4);
testUser.addRating(testItem.getTestItemIndex(), 2.0);
testUser.addRating(333, 3.5);
testUser.addRating(wiredItem.getItemIndex(), 3.0);
assertEquals(0, testUser.findItem(item.getItemIndex()));
assertEquals(item.getItemIndex(), testUser.getTestItemAt(0));
assertEquals(1.0, testUser.getTestRatingAt(0));
assertEquals(1, testUser.findItem(testItem.getTestItemIndex()));
assertEquals(testItem.getTestItemIndex(), testUser.getTestItemAt(1));
assertEquals(2.0, testUser.getTestRatingAt(1));
assertEquals(2, testUser.findItem(wiredItem.getItemIndex()));
assertEquals(wiredItem.getItemIndex(), testUser.getTestItemAt(2));
assertEquals(3.0, testUser.getTestRatingAt(2));
assertEquals(111, testUser.getTestItemAt(3));
assertEquals(1.3, testUser.getTestRatingAt(3));
assertEquals(222, testUser.getTestItemAt(4));
assertEquals(2.4, testUser.getTestRatingAt(4));
assertEquals(333, testUser.getTestItemAt(5));
assertEquals(3.5, testUser.getTestRatingAt(5));
assertEquals(0, testUser.findItem(item.getItemIndex()));
assertEquals(item.getItemIndex(), testUser.getItemAt(0));
assertEquals(1.0, testUser.getRatingAt(0));
assertEquals(1, testUser.findItem(testItem.getTestItemIndex()));
assertEquals(testItem.getTestItemIndex(), testUser.getItemAt(1));
assertEquals(2.0, testUser.getRatingAt(1));
assertEquals(2, testUser.findItem(wiredItem.getItemIndex()));
assertEquals(wiredItem.getItemIndex(), testUser.getItemAt(2));
assertEquals(3.0, testUser.getRatingAt(2));
assertEquals(111, testUser.getItemAt(3));
assertEquals(1.3, testUser.getRatingAt(3));
assertEquals(222, testUser.getItemAt(4));
assertEquals(2.4, testUser.getRatingAt(4));
assertEquals(333, testUser.getItemAt(5));
assertEquals(3.5, testUser.getRatingAt(5));
assertEquals(1, testUser.findTestItem(testItem.getTestItemIndex()));
assertEquals("202", testUser.getId());
assertEquals(202, testUser.getUserIndex());
assertEquals(6, testUser.getNumberOfRatings());
assertEquals(1, testUser.getMinRating());
assertEquals(3.5, testUser.getMaxRating());
assertTrue(Math.abs(testUser.getRatingAverage() - 2.2) <= Math.ulp(2.2));
assertEquals(202, testUser.getTestUserIndex());
assertEquals(6, testUser.getNumberOfTestRatings());
assertEquals(1, testUser.getMinTestRating());
assertEquals(3.5, testUser.getMaxTestRating());
assertTrue(Math.abs(testUser.getTestRatingAverage() - 2.2) <= Math.ulp(2.2));
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
testUser.addTestRating(111, 1.3);
});
String expectedMessage = "Provided rating already exist in user: 202";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
@Test
void testUserCastedToUserInsertion() {
wiredUser.addRating(111, 1.3);
wiredUser.addRating(item.getItemIndex(), 1.0);
wiredUser.addRating(222, 2.4);
wiredUser.addRating(testItem.getTestItemIndex(), 2.0);
wiredUser.addRating(333, 3.5);
wiredUser.addRating(wiredItem.getItemIndex(), 3.0);
assertEquals(0, wiredUser.findItem(item.getItemIndex()));
assertEquals(item.getItemIndex(), wiredUser.getItemAt(0));
assertEquals(1.0, wiredUser.getRatingAt(0));
assertEquals(1, wiredUser.findItem(testItem.getTestItemIndex()));
assertEquals(testItem.getTestItemIndex(), wiredUser.getItemAt(1));
assertEquals(2.0, wiredUser.getRatingAt(1));
assertEquals(2, wiredUser.findItem(wiredItem.getItemIndex()));
assertEquals(wiredItem.getItemIndex(), wiredUser.getItemAt(2));
assertEquals(111, wiredUser.getItemAt(3));
assertEquals(1.3, wiredUser.getRatingAt(3));
assertEquals(3.0, wiredUser.getRatingAt(2));
assertEquals(222, wiredUser.getItemAt(4));
assertEquals(2.4, wiredUser.getRatingAt(4));
assertEquals(333, wiredUser.getItemAt(5));
assertEquals(3.5, wiredUser.getRatingAt(5));
assertEquals("303", wiredUser.getId());
assertEquals(303, wiredUser.getUserIndex());
assertEquals(6, wiredUser.getNumberOfRatings());
assertEquals(1, wiredUser.getMinRating());
assertEquals(3.5, wiredUser.getMaxRating());
assertTrue(Math.abs(wiredUser.getRatingAverage() - 2.2) <= Math.ulp(2.2));
}
}
|
from typing import List
class Transaction:
def __init__(self, amount: float, type: str):
self.amount = amount
self.type = type
def calculate_total_profit(transactions: List[Transaction]) -> float:
total_income = sum(transaction.amount for transaction in transactions if transaction.type == "income")
total_expense = sum(transaction.amount for transaction in transactions if transaction.type == "expense")
return total_income - total_expense
# Example usage
transactions = [
Transaction(amount=1000.0, type="income"),
Transaction(amount=500.0, type="expense"),
Transaction(amount=800.0, type="income"),
Transaction(amount=300.0, type="expense")
]
print(calculate_total_profit(transactions)) # Output: 1200.0
|
package org.glamey.training.codes.leetcode;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
/**
* https://leetcode.com/problems/replace-words/description/
*
* @author zhouyang.zhou. 2017.09.04.15.
*/
public class ReplaceWordsDemo {
public static void main(String[] args) {
List<String> dict = Lists.newArrayList("cat", "bat", "rat");
String sentence = "the cattle was rattled by the battery";
String result = replaceWords(dict, sentence);
System.out.println(result);
}
private static String replaceWords(List<String> dict, String sentence) {
if (dict == null || dict.size() == 0) {
return sentence;
}
if (sentence == null || "".equals(sentence)) {
return sentence;
}
StringBuilder builder = new StringBuilder(sentence.length());
Set<String> dictSet = new HashSet<>(dict);
String[] strings = sentence.split("\\s+");
for (String string : strings) {
String prefix = "";
for (int i = 1; i <= string.length(); i++) {
prefix = string.substring(0, i);
if (dictSet.contains(prefix)) {
break;
}
}
builder.append(" ").append(prefix);
}
return builder.deleteCharAt(0).toString();
}
}
|
// Copyright 2016 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
package archivist
import (
"bytes"
"errors"
"io"
"io/ioutil"
"strings"
"sync"
)
type MockArchiveBackend struct {
mutex sync.Mutex
files map[string][]byte
}
func (b *MockArchiveBackend) Exists(pth string) bool {
b.mutex.Lock()
defer b.mutex.Unlock()
_, ok := b.files[pth]
return ok
}
func (b *MockArchiveBackend) GetFile(pth string) (io.ReadCloser, error) {
b.mutex.Lock()
defer b.mutex.Unlock()
var buf []byte
buf, ok := b.files[pth]
if !ok {
return nil, errors.New("no such file: " + pth)
}
return ioutil.NopCloser(bytes.NewReader(buf)), nil
}
func (b *MockArchiveBackend) PutFile(pth string, in io.ReadCloser) error {
b.mutex.Lock()
defer b.mutex.Unlock()
buf, e := ioutil.ReadAll(in)
if e != nil {
return e
}
b.files[pth] = buf
return nil
}
func (b *MockArchiveBackend) ListFiles(pth string) (chan string, chan error) {
b.mutex.Lock()
defer b.mutex.Unlock()
ch := make(chan string)
errs := make(chan error)
files := make([]string, 0, len(b.files))
for k, _ := range b.files {
files = append(files, k)
}
go func() {
for _, f := range files {
if strings.HasPrefix(f, pth) {
ch <- f
}
}
close(ch)
close(errs)
}()
return ch, errs
}
func (b *MockArchiveBackend) CanListFiles() bool {
return true
}
func MakeMockBackend(opts ConnectOptions) ArchiveBackend {
b := new(MockArchiveBackend)
b.files = make(map[string][]byte)
return b
}
|
import Service from '@ember/service';
let parseItem = function (item) {
let value;
if (item) {
value = JSON.parse(item)
}
return value;
}
export default Service.extend({
getLocalStorageItem: function (key) {
let value = window.localStorage.getItem(key);
return parseItem(value);
},
getSessionStorageItem: function (key) {
let value = window.sessionStorage.getItem(key);
return parseItem(value);
},
setLocalStorageItem: function (key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
},
setSessionStorageItem: function (key, value) {
window.sessionStorage.setItem(key, JSON.stringify(value));
},
removeLocalStorageItem: function (key) {
window.localStorage.removeItem(key);
},
removeSessionStorageItem: function (key) {
window.sessionStorage.removeItem(key);
}
});
|
python wait_postgres.py
python manage.py makemigrations storages things
python manage.py migrate
python manage.py loaddata test_data
gunicorn korobasy.wsgi:application --bind 0.0.0.0:8000
|
export * from './storage';
export * from './http-status';
export * from './header';
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.batteryEmpty = void 0;
var batteryEmpty = {
"viewBox": "0 0 512 512",
"children": [{
"name": "path",
"attribs": {
"d": "M469.9,192H433v-54c0-5.5-4.3-10-9.9-10H42.1c-5.6,0-10.1,4.5-10.1,10v236c0,5.5,4.5,10,10.1,10h381.1c5.5,0,9.9-4.5,9.9-10\r\n\tv-54h36.9c5.6,0,10.1-4.5,10.1-10V202C480,196.5,475.5,192,469.9,192z M448,288h-14.8H401v32v32H64V160h337v32v32h32.2H448V288z"
},
"children": []
}]
};
exports.batteryEmpty = batteryEmpty;
|
import React, { useEffect, useState } from 'react';
import { Button, Grid, Input, Row, Spacer, Text } from '@nextui-org/react';
import useDesignContext, { EDesignAction } from '../../context/DesignContext';
import Dropdown from '../atoms/Dropdown';
import {
GOOGLE_FONTS_URL,
SCALE_OPTIONS,
TABLE_HEADERS,
WEIGHT_QUERY,
} from '../../utils/constants';
import Table from '../molecules/Table';
import { handleFontRatio } from '../../utils/scaleFactor';
import FontContainer from '../atoms/FontContainer';
const FontSection = () => {
const { designData, setDesignState } = useDesignContext();
const [heading, setHeading] = useState('');
const [paragraph, setParagraph] = useState('');
const [baseSize, setBaseSize] = useState(designData.font.baseSize);
const [scaleFactor, setScaleFactor] = useState(designData.font.scaleFactor);
const { headingFontName, parragraphFontName } = designData.font;
useEffect(() => {
setHeading(headingFontName);
setParagraph(parragraphFontName);
}, []);
useEffect(() => {
const newHeading = headingFontName.replace(/\s/g, '+');
const newParagraph = parragraphFontName.replace(/\s/g, '+');
const headingLink = `${GOOGLE_FONTS_URL}${newHeading}${WEIGHT_QUERY}`;
const paragraphLink = `${GOOGLE_FONTS_URL}${newParagraph}${WEIGHT_QUERY}`;
const link1 = document.createElement('link');
const link2 = document.createElement('link');
const links = document.getElementsByTagName('link');
let headingLinkExists = false;
let paragraphLinkExists = false;
for (let item of Array.from(links)) {
if (item.href === headingLink) headingLinkExists = true;
}
link1.rel = 'stylesheet';
if (!headingLinkExists) {
link1.href = headingLink;
document.head.appendChild(link1);
}
link2.rel = 'stylesheet';
if (!paragraphLinkExists) {
link2.href = paragraphLink;
document.head.appendChild(link2);
}
}, [headingFontName, parragraphFontName]);
useEffect(() => {
setDesignState({
type: EDesignAction.SET_FONTS,
payload: {
...designData.font,
baseSize,
scaleFactor,
},
});
}, [baseSize, scaleFactor, setDesignState]);
const spacings = handleFontRatio(scaleFactor, baseSize, 'Lorem ipsum dolor sit amet');
const TABLE_ROWS = [...spacings];
const handleFonts = () => {
setDesignState({
type: EDesignAction.SET_FONTS,
payload: {
...designData.font,
headingFontName: heading,
parragraphFontName: paragraph,
},
});
};
const handleBaseSize = (e) => {
const value = Number(e.target.value);
if (value < 1) return;
setBaseSize(value);
};
return (
<Row wrap="wrap" justify="space-between">
<Grid.Container direction="column" gap={2} css={{ maxWidth: 'fit-content' }}>
<Grid>
<Row align="flex-end">
<Input
label="Heading Font"
placeholder="Open Sans"
bordered
value={heading}
onChange={(e) => setHeading(e.target.value)}
helperText="Input a font from google fonts"
/>
<Spacer />
<Input
label="Paragraph Font"
placeholder="Open Sans"
bordered
value={paragraph}
onChange={(e) => setParagraph(e.target.value)}
helperText="Input a font from google fonts"
/>
<Spacer />
<Button onClick={handleFonts} css={{ minWidth: 'auto' }}>
Submit fonts
</Button>
</Row>
</Grid>
<Grid>
<Spacer y={2} />
<Text>Headings</Text>
<FontContainer headingFontName={headingFontName} fontWeight="700">
<Text>AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz</Text>
<Spacer />
<Text>1234567890!@£$%^&*()</Text>
</FontContainer>
</Grid>
<Grid>
<Text>Paragraphs</Text>
<FontContainer headingFontName={parragraphFontName} fontWeight="400">
<Text>AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz</Text>
<Spacer />
<Text>1234567890!@£$%^&*()</Text>
</FontContainer>
</Grid>
</Grid.Container>
<Grid.Container direction="column" gap={2} css={{ maxWidth: '650px' }}>
<Grid>
<Row>
<Input
label="Base size"
placeholder="14"
bordered
type="number"
value={`${baseSize}`}
onChange={handleBaseSize}
/>
<Spacer />
<Dropdown
label="Scale Factor"
placeholder="Select Factor"
options={SCALE_OPTIONS}
value={scaleFactor}
onChange={(e) => setScaleFactor(e.target.value)}
/>
</Row>
</Grid>
<Grid>
<Spacer y={2} />
<Table
tableHeaders={TABLE_HEADERS}
tableRows={TABLE_ROWS}
lastItemStyles={{ p: '0' }}
/>
</Grid>
</Grid.Container>
</Row>
);
};
export default FontSection;
|
import { dispatch } from 'd3-dispatch';
import { scaleTime } from 'd3-scale';
import { select, event } from 'd3-selection';
import apiStart from './apiStart';
import apiStop from './apiStop';
import apiOn from './apiOn';
import apiFocus from './apiFocus';
import apiClientDelay from './apiClientDelay';
import apiServerDelay from './apiServerDelay';
import apiSize from './apiSize';
import apiStep from './apiStep';
import update from './update';
import apiMetric from '../metric';
import apiCube from './apiCube';
import apiAxis from './apiAxis';
import apiRule from './apiRule';
import apiHorizon from '../horizon';
import apiGangliaWeb from './apiGangliaWeb';
import apiLibrato from '../librato';
import apiGraphite from './apiGraphite';
import apiComparison from '../comparison';
const config = {
id: 1,
step: 1e4, // ten seconds, in milliseconds
size: 1440, // ten seconds, in milliseconds
serverDelay: 5e3,
clientDelay: 5e3,
event: dispatch('prepare', 'beforechange', 'change', 'focus'),
start0: null,
stop0: null, // the start and stop for the previous change event
start1: null,
stop1: null, // the start and stop for the next prepare event
timeout: null,
focus: null,
scale: scaleTime().range([0, 1440]),
};
const context = () => {
const state = {
_id: 1,
_step: 1e4, // ten seconds, in milliseconds
_size: 1440, // ten seconds, in milliseconds
_serverDelay: 5e3,
_clientDelay: 5e3,
_event: dispatch('prepare', 'beforechange', 'change', 'focus'),
_start0: null,
_stop0: null, // the start and stop for the previous change event
_start1: null,
_stop1: null, // the start and stop for the next prepare event
_timeout: null,
_focus: null,
_scale: scaleTime().range([0, 1440]),
};
const _context = Object.assign(
state,
apiAxis(state),
apiComparison(state),
apiCube(state),
apiClientDelay(state),
apiFocus(state),
apiMetric(state),
apiOn(state),
apiRule(state),
apiServerDelay(state),
apiSize(state),
apiStart(state),
apiStop(state),
apiStep(state)
);
state._timeout = setTimeout(_context.start, 10);
const { focus } = _context;
select(window).on('keydown.context-' + ++_context._id, function() {
switch (!event.metaKey && event.keyCode) {
case 37: // left
if (focus == null) _context.focus = size - 1;
if (focus > 0) _context.focus(--_context.focus);
break;
case 39: // right
if (focus == null) _context.focus = size - 2;
if (focus < size - 1) _context.focus(++_context.focus);
break;
default:
return;
}
event.preventDefault();
});
const cubismContext = update(_context);
return Object.assign(
cubismContext,
apiHorizon(cubismContext),
apiGangliaWeb(cubismContext),
apiLibrato(cubismContext),
apiGraphite(cubismContext)
);
};
export default context;
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store";
const Home = ()=> import('../views/home/Home')
const Car = ()=> import('../views/car/Car')
const Category = ()=> import('../views/category/Category')
const Info = ()=> import('../views/info/Info')
const Detail = ()=> import('../views/detail/Detail')
const Login = ()=> import('../views/info/Info')
const Profile = ()=> import('../views/info/Profile')
const UserLogin = ()=> import('../views/login/UserLogin')
const Register = ()=> import('../views/login/Register')
Vue.use(VueRouter)
const routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/info',
component: Profile
},
{
path: '/car',
component: Car,
meta: {
requiresAuth: true
}
},
{
path: '/category',
component: Category
},
{
path: '/detail/:id',
component: Detail
},
{
path: '/login',
component:UserLogin
},
{
path: '/register',
component: Register
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
router.beforeEach((to,from,next)=>{
if(to.matched.some(m=>m.meta.requiresAuth)){
if(store.state.Authorization!= ''){
next();
}else if(to.path != '/login'){
let token = store.state.Authorization;
if(token === 'null' || token === '' || token === undefined){
next('/login');
}
}else {
next();
}
}else {
next();
}
})
export default router
|
// Copyright (c) Yugabyte, Inc.
package com.yugabyte.yw.forms;
import com.yugabyte.yw.common.alerts.SmtpData;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Map;
import play.data.validation.Constraints;
/** This class will be used by the API and UI Form Elements to validate constraints are met */
@ApiModel(value = "CustomerAlertData", description = "Alerts associated with customers")
public class AlertingFormData {
@Constraints.MaxLength(15)
@ApiModelProperty(value = "Alert code")
public String code;
@ApiModelProperty(value = "Alert email", example = "<EMAIL>")
public String email;
@ApiModelProperty(value = "Email password", example = "<PASSWORD>")
public String password;
@ApiModelProperty(value = "Email password", example = "<PASSWORD>")
public String confirmPassword;
@ApiModelProperty(value = "Alert name", example = "Test alert")
public String name;
@ApiModelProperty(value = "Feature")
public Map features;
@ApiModel(description = "Alerts associated with customers")
public static class AlertingData {
@Constraints.Email
@Constraints.MinLength(5)
@ApiModelProperty(value = "Alert email id", example = "<EMAIL>")
public String alertingEmail;
@ApiModelProperty(value = "Is alert has sent to YB")
public boolean sendAlertsToYb = false;
@ApiModelProperty(value = "Alert interval")
public long checkIntervalMs = 0;
@ApiModelProperty(value = "Status update of alert interval")
public long statusUpdateIntervalMs = 0;
@ApiModelProperty(value = "Is alert is just for error")
public Boolean reportOnlyErrors = false;
@ApiModelProperty(value = "Is alert needed for backup failure")
public Boolean reportBackupFailures = false;
// TODO: Remove after implementation of a separate window for all definitions
// configuration.
@ApiModelProperty(value = "Is Clock skew is enabled")
public boolean enableClockSkew = true;
}
public AlertingData alertingData;
public SmtpData smtpData;
@Constraints.Pattern(
message = "Must be one of NONE, LOW, MEDIUM, HIGH",
value = "\\b(?:NONE|LOW|MEDIUM|HIGH)\\b")
public String callhomeLevel = "MEDIUM";
}
|
<reponame>TerracottaMC/Terracotta
package org.terracottamc.logging;
import lombok.extern.log4j.Log4j2;
/**
* @author Kaooot
* @version 1.0
*/
@Log4j2
public class Logger {
/**
* Prints an information message on the terminal
*
* @param message which should be printed
*/
public void info(final String message) {
Logger.log.info(message);
}
/**
* Prints a warning message on the terminal
*
* @param message which should be printed
*/
public void warn(final String message) {
Logger.log.warn(message);
}
/**
* Prints a debug message on the terminal
*
* @param message which should be printed
*/
public void debug(final String message) {
Logger.log.debug(message);
}
/**
* Prints an error message on the terminal
*
* @param message which should be printed
*/
public void error(final String message) {
Logger.log.error(message);
}
}
|
<reponame>kjg531/react-bluekit<filename>src/libraries/__test__/parseHighlightedMenu.js
import parseHighlightedMenu from '../parseHighlightedMenu';
import test from 'ava';
test('parse highlighted', t => {
const result = parseHighlightedMenu('<bstyle=\"color:red\">Text</b>')
t.true(result === '<b style=\"color:red\">Text</b>')
});
|
#!/bin/bash
set -e
if [ -z ${DF_HOME+x} ]; then
echo "[INFO] \$DF_HOME is unset, exit"
exit
else
echo "[INFO] \$DF_HOME Not Found, use DF_HOME=$DF_HOME ";
fi
if [ -z ${DF_APP_MNT+x} ]; then
DF_APP_MNT=/mnt
fi
if [ -z ${DF_APP_DEP+x} ]; then
DF_APP_DEP=/opt
fi
if [ -z ${DF_CONFIG+x} ]; then
DF_CONFIG=$DF_HOME/conf
fi
if [ -z ${DF_LIB+x} ]; then
DF_LIB=$DF_HOME/lib
fi
if [ -z ${DF_REP+x} ]; then
DF_REP=$DF_HOME/repo
fi
mv ${DF_APP_DEP}/flink/conf/flink-conf.yaml ${DF_APP_DEP}/flink/conf/flink-conf.yaml.bk
cp ${DF_REP}/df_demo/df-environment/df-env-vagrant/etc/flink/flink-conf.yaml ${DF_APP_DEP}/flink/conf/
echo "[INFO] Post update script is applied to map Flink rest port to 8001 from 8030."
|
<gh_stars>0
'use strict';
let Mdns;
let dns;
const methodName = 'mdns';
function browse(self) {
try {
Mdns = Mdns || require('mdns-discovery');
dns = dns || require('dns');
} catch (e) {
if (typeof self !== 'object') {
self.log.warn('skipping mdns method, because no binary package...');
}
setTimeout(self.done.bind(self, 'binary package not installed'));
return;
}
this.close = () => {
mdns.close();
self.done();
};
const mdns = new Mdns({
timeout: parseInt(self.timeout, 10) / 1000 || 10,
name: [
'_services._dns-sd._udp.local',
'_raop._tcp.local',
'_sleep-proxy.-udp',
'_homekit._tcp',
'_amzn-wplay._tcp.local',
'_http._tcp.local',
'_mieleathome._tcp',
'_services._dns-sd._udp.local',
'_touch-able._udp',
'_coap._udp.local' // used to discover tradfri devices
],
find: '*',
broadcast: false
});
mdns.noQuestions = true;
self.setTimeout(self.timeout, {timeout: false});
this.log.info('Discovering mDNS devices...');
mdns.on('entry', entry => {
const device = {
//_data: {address: entry.ip}, // is it used?
_addr: entry.ip,
_name: entry.name,
_mdns: {}
};
Object.keys(entry).forEach(n => device._mdns[n] = entry[n]);
//self.log.debug('Discovered mDNS device: ' + JSON.stringify(device));
if (self.addDevice(device) === 'halt') {
self.done();
}
});
mdns.run(result => self.done());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// can be removed in the future
function oldBrowse(options, log, updateProgress, addDevice) {
try {
Mdns = Mdns || require('mdns-discovery');
dns = dns || require('dns');
} catch (e) {
log.warn('skipping mdns method, because no binary package...');
if (typeof addDevice === 'function') {
setTimeout(cb => cb(null, 'binary package not installed'), 1, addDevice);
addDevice = null;
}
return;
}
const mdns = new Mdns({
timeout: parseInt(options.mdnsTimeout, 10) / 1000 || 10,
name: ['_services._dns-sd._udp.local', '_raop._tcp.local', '_sleep-proxy.-udp', '_homekit._tcp', '_amzn-wplay._tcp.local', '_http._tcp.local', '_mieleathome._tcp', '_services._dns-sd._udp.local', '_touch-able._udp'],
find: '*',
broadcast: false
});
mdns.noQuestions = true;
const interval = setInterval(() => { // should be done in main.js for all methods
if (exports.progress >= 95) {
clearInterval(interval);
return;
}
exports.progress += 5;
updateProgress();
}, mdns.options.timeout * 1000 / 20);
log.info('Discovering mDNS devices...');
mdns.on('entry', entry => {
const device = {
//_data: {address: entry.ip}, // is it used?
_addr: entry.ip,
_name: entry.name,
_mdns: {}
};
Object.keys(entry).forEach(n => device._mdns[n] = entry[n]);
if (addDevice && addDevice(device) === 'halt') {
mdns.close();
addDevice && addDevice(null);
addDevice = null;
}
});
mdns.run(result => {
addDevice && addDevice(null);
addDevice = null;
});
}
exports.foundCount = 0; // if needed, do only read
exports.progress = 0;
// end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
exports.browse = browse;
exports.oldBrowse = oldBrowse;
exports.type = 'mdns';
//exports.subType = 'mdns';
exports.source = methodName;
exports.timeout = 15000;
exports.options = {};
// exports.options = {
// mdnsTimeout: {
// min: 15000,
// max: 60000,
// type: 'number'
// }
// };
|
<filename>movies/view/hot/View.js
import React, {Component} from 'react';
import {FlatList, View, Text, Image, TouchableOpacity} from 'react-native';
import styles from './style';
import {connect} from 'react-redux';
import {getSetHostListAction, getSetRefreshingAction} from './actionCreator';
class Hot extends Component {
constructor(props) {
super(props);
this.handleListRefresh = this.handleListRefresh.bind(this);
}
render() {
return (
<FlatList
data={this.props.list}
keyExtractor={(item, index) => item.id}
refreshing={this.props.refreshing}
onRefresh={this.handleListRefresh}
renderItem={({item}) => {
return (
<View style={styles.item}>
<Image
source={require('../../resource/images/3.jpg')}
style={styles.itemImage}
/>
<TouchableOpacity
onPress={() => {
alert(item.desc);
}}>
<View style={styles.info}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.desc}>{item.desc}</Text>
</View>
</TouchableOpacity>
</View>
);
}}
/>
);
}
componentDidMount() {
this.getList();
}
getList() {
let arr = [];
for (let i = this.props.list.length; i < this.props.list.length + 20; i++) {
arr.push({
id: i,
title: '我是最帅的标题' + i,
desc:
'我是最棒的描述我是最棒的描述我是最棒的描述我是最棒的描述我是最棒的描述' +
i,
});
}
this.props.setHostList(arr);
}
handleListRefresh() {
this.getList();
}
}
const manState = state => {
return {
list: state.hot.list,
refreshing: state.hot.refreshing,
};
};
const mapDispath = dispath => {
return {
setHostList(data) {
const action = getSetHostListAction(data);
dispath(action);
},
setRefreshing(data) {
const action = getSetRefreshingAction(data);
dispath(action);
},
};
};
export default connect(manState, mapDispath)(Hot);
|
The Internet of Things (IoT) is a rapidly advancing technology making physical objects more connected to each other through the internet, revolutionizing the way people interact with their environment and do business. It will have a great impact on the healthcare, manufacturing and automotive industries. IoT will empower people with real-time access to data and enable companies to create smarter solutions. It will enable businesses to increase efficiency, cost savings, and innovation.
|
<reponame>r-woo/elfai
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from elf.options import import_options, PyOptionSpec
class EvalCount(object):
''' Eval Count. Run games and record required stats.'''
def __init__(self):
# All previous ids.
self.ids = {}
# id for old models.
# If this variable is set, then do not count win_rate of ids_exclude.
self.ids_exclude = set()
self.summary_count = 0
self.num_terminal = 0
def reset(self):
pass
def _on_terminal(self, id, record):
pass
def reset_on_new_model(self):
self.reset()
self.ids_exclude.update(self.ids.keys())
self.ids = dict()
def feed(self, id, *args, **kwargs):
# Game is running, not reaching terminal yet.
# Register a game id.
if id not in self.ids:
self.ids[id] = 0
self.ids[id] = self._on_game(id, self.ids[id], *args, **kwargs)
def count_completed(self):
return self.num_terminal
def terminal(self, id):
# If this game id ended and is in the exclude list, skip
# It is not counted as the number of games completed.
if id in self.ids_exclude:
self.ids_exclude.remove(id)
if id in self.ids:
del self.ids[id]
return
if id in self.ids:
self._on_terminal(id, self.ids[id])
# This game is over, remove game id if it is already in ids
del self.ids[id]
self.num_terminal += 1
# else:
# This should only happen when seq=0
# print("id=%s seq=%d, winner=%d" % (id, seq, winner))
def summary(self):
ret = self._summary()
self.reset()
self.num_terminal = 0
self.summary_count += 1
return ret
def print_summary(self):
summary = self.summary()
for k, v in summary.items():
print("%s: %s" % (str(k), str(v)))
def feed_batch(self, batch, hist_idx=0):
ids = batch["id"][hist_idx]
last_terminals = batch["last_terminal"][hist_idx]
last_r = batch["last_r"][hist_idx]
for batch_idx, (id, last_terminal) in enumerate(
zip(ids, last_terminals)):
self.feed(id, last_r[batch_idx])
if last_terminal:
self.terminal(id)
class RewardCount(EvalCount):
''' Class to accumulate rewards achieved'''
def __init__(self):
super(RewardCount, self).__init__()
self.reset()
def reset(self):
self.n = 0
self.sum_reward = 0
def _on_terminal(self, id, record):
self.sum_reward += record
self.n += 1
def _on_game(self, id, record, reward, seq=None):
return record + reward
def _summary(self):
str_reward = "[%d] Reward: %.2f/%d" % (
self.summary_count,
float(self.sum_reward) / (self.n + 1e-10),
self.n
)
return dict(str_reward=str_reward)
class WinRate(EvalCount):
''' Class to accumulate game results to win rate'''
def __init__(self):
super(WinRate, self).__init__()
self.total_win_count = 0
self.total_lose_count = 0
self.summary_count = 0
self.highest_win_rate = -1.0
self.highest_win_rate_idx = -1
def reset(self):
self.win_count = 0
self.lose_count = 0
def _on_game(self, id, record, final_reward, seq=None):
if final_reward > 0.5:
self.win_count += 1
self.total_win_count += 1
elif final_reward < -0.5:
self.lose_count += 1
self.total_lose_count += 1
def _summary(self):
total = self.win_count + self.lose_count
win_rate = self.win_count / (total + 1e-10)
new_record = False
if win_rate > self.highest_win_rate:
self.highest_win_rate = win_rate
self.highest_win_rate_idx = self.summary_count
new_record = True
str_win_rate = (
f'[{self.summary_count}] Win rate: {win_rate:.3f} '
f'[{self.win_count}/{self.lose_count}/{total}], '
f'Best win rate: {self.highest_win_rate:.3f} '
f'[{self.highest_win_rate_idx}]'
)
total = self.total_win_count + self.total_lose_count
str_acc_win_rate = "Accumulated win rate: %.3f [%d/%d/%d]" % (
self.total_win_count / (total + 1e-10),
self.total_win_count, self.total_lose_count, total
)
return dict(
new_record=new_record,
count=self.summary_count,
best_win_rate=self.highest_win_rate,
str_win_rate=str_win_rate,
str_acc_win_rate=str_acc_win_rate,
)
def win_count(self): return self.total_win_count
def lose_count(self): return self.total_lose_count
def total_winlose_count(
self): return self.total_win_count + self.total_lose_count
def winlose_count(self): return self.win_count + self.lose_count
class Stats(EvalCount):
@classmethod
def get_option_spec(cls, stats_name=''):
spec = PyOptionSpec()
spec.addStrOption(
stats_name + '_stats',
'type of stat to report (rewards or winrate)',
'')
return spec
def __init__(self, option_map, stats_name=''):
"""Initialization for Stats."""
import_options(self, option_map, self.get_option_spec(stats_name))
self.name = stats_name + "_stats"
self.collector = None
self.stats_name = getattr(self.options, self.name)
if self.stats_name == "rewards":
self.collector = RewardCount()
elif self.stats_name == "winrate":
self.collector = WinRate()
else:
self.collector = None
print("Stats: Name " + str(self.stats_name) + " is not known!")
# raise ValueError(
# "Name " + str(self.stats_name) + " is not known!")
def is_valid(self):
return self.collector is not None
def feed(self, id, *args, **kwargs):
self.collector.feed(id, *args, **kwargs)
def count_completed(self):
return self.collector.count_completed()
def reset_on_new_model(self):
self.collector.reset_on_new_model()
def terminal(self, id):
return self.collector.terminal(id)
def reset(self):
self.collector.reset()
def summary(self):
return self.collector.summary()
def print_summary(self):
self.collector.print_summary()
def feed_batch(self, batch, hist_idx=0):
return self.collector.feed_batch(batch, hist_idx=hist_idx)
|
#!/bin/sh
echo " Welcome to deehuck's dotfiles for linux. big ups to mharington for the legwork"
echo " - -- --- ----- --- -- - -- --- ----- --- -- -"
echo " "
echo " .___.__ __ /\ "
echo " __| _/| |__ __ __ ____ | | _)/ ______ "
echo " / __ | | | \| | \_/ ___\| |/ / / ___/ "
echo " / /_/ | | Y \ | /\ \___| < \___ \ "
echo " \____ | |___| /____/ \___ >__|_ \/____ > "
echo " \/ \/ \/ \/ \/ "
echo " .___ __ _____.__.__ "
echo " __| _/_____/ |__/ ____\__| | ____ ______ "
echo " / __ |/ _ \ __\ __\| | | _/ __ \ / ___/ "
echo " / /_/ ( <_> ) | | | | | |_\ ___/ \___ \ "
echo " \____ |\____/|__| |__| |__|____/\___ >____ > "
echo " \/ \/ \/ "
echo " - -- --- ----- --- -- - -- --- ----- --- -- -"
echo " "
brew="/usr/local/bin/brew"
if [ -f "$brew" ]
then
echo "Homebrew is installed, nothing to do here"
else
echo "Homebrew is not installed, installing now"
echo "This may take a while"
echo "Homebrew requires osx command lines tools, please download xcode first"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
fi
# lua is required with hammerspoon
packages=(
"git"
"node"
"htop"
"tmux"
"neovim"
"mosh"
"python"
"ruby"
"go"
"fortune"
)
for i in "${packages[@]}"
do
brew install $i
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
done
echo "installing RCM, for dotfiles management"
brew tap thoughtbot/formulae
brew install rcm
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
localGit="/usr/local/bin/git"
if [ -f "$localGit" ]
then
echo "git is all good"
else
echo "git is not installed"
fi
# Okay so everything should be good
# Fingers cross at least
# Now lets clone my dotfiles repo into .dotfiles/
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
echo "Cloning dhucks's dotfiles into .dotfiles"
git clone https://gitlab.com/dhuck/dotfiles.git ~/.dotfiles
cd .dotfiles
# git submodule update --init --recursive
cd $HOME
echo "running RCM's rcup command"
echo "This is symlink the rc files in .dofiles"
echo "with the rc files in $HOME"
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
rcup
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
echo "Changing to zsh"
chsh -s $(which zsh)
echo "You'll need to log out for this to take effect"
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
echo 'done'
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
echo "All done!"
echo "and change your terminal font to source code pro"
echo "Cheers"
echo " - -- --- ----- --- -- - -- --- ----- --- -- - "
exit 0
|
<reponame>MagedMilad/knowledge-base<gh_stars>0
// Sum Lists: You have two numbers represented by a linked list, where each node contains a single
// digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a
// function that adds the two numbers and returns the sum as a linked list.
// EXAMPLE
// Input: (7-> 1 -> 6) + (5 -> 9 -> 2).That is,617 + 295.
// Output: 2 -> 1 -> 9. That is, 912.
// FOLLOW UP
// Suppose the digits are stored in forward order. Repeat the above problem.
// Input: (6 -> 1 -> 7) + (2 -> 9 -> 5).That is,617 + 295.
// Output: 9 -> 1 -> 2. That is, 912.
LinkedlistNode addLists(LinkedListNode l1, LinkedListNode l2){
return addListsHelper(l1, l2, 0);
}
LinkedlistNode addListsHelper(LinkedListNode l1, LinkedListNode l2, int carry){
if(l1 == null && l2 == null) return null;
int value = carry;
if(l1 != null) value += l1.data;
if(l2 != null) value += l2.data;
LinkedListNode root = new LinkedlistNode(value%10);
root.next = addListsHelper(
l1 == null ? null : l1.next,
l2 == null ? null : l2.next,
value > 10 ? 1 : 0
)
return root;
}
////////////////////////////////////////////////////////////
class PartialSum{
LinkedListNode node = null;
int carry = 0;
}
LinkedlListNode addLists(LinkedListNode l1, LinkedListNode l2){
int len1 = getLength(l1);
int len2 = getLength(l2);
if(len1 > len2){
l2 = appendZeroToList(l2, len1 - len2);
}else{
l1 = appendZeroToList(l1, len2 - len1);
}
PartialSum res = addListsHelper(l1, l2);
if(res.carry == 0) return res.node;
return insertBefore(res.node, res.carry);
}
int getLength(LinkedListNode head){
int len=0;
while(head != null){
len++;
head = head.next;
}
return len;
}
LinkedListNode addListsHelper(LinkedListNode l1, LinkedListNode l2){
if(l1 == null){
PartialSum res = new Partia1Sum();
return res;
}
PartialSum res = addListsHelper(l1.next, l2.next);
int val = l1.data + l2.data + res.carry;
LinkedListNode head = insertBefore(res.node, val%10);
res.node = head;
res.carry = val/10;
return res;
}
LinkedListNode appendZeroToList(LinkedListNode head, int len){
while(len-- > 0){
head = insertBefore(head, 0);
}
return head;
}
LinkedListNode insertBefore(LinkedlListNode head, int data){
LinkedListNode new_head = new LinkedlListNode(data);
new_head.next = head;
return new_head;
}
|
if [ -f "/var/lib/u2up-images/u2up-pc-installer.tgz" ]; then
if [ ! -f "/var/lib/u2up-images/u2up-pc-installer_ready" ]; then
tar xzvf /var/lib/u2up-images/u2up-pc-installer.tgz -C /
if [ $? -eq 0 ]; then
touch /var/lib/u2up-images/u2up-pc-installer_ready
else
rm -f /var/lib/u2up-images/u2up-pc-installer_ready
fi
fi
if [ -f "/var/lib/u2up-images/u2up-pc-installer_ready" ]; then
if [ $(basename $(tty)) = "tty1" ]; then
/usr/bin/u2up-pc-installer.sh
fi
fi
fi
|
#!/bin/bash
# Input from user
read -p "Enter Project Name : " playground
# Check if the project aleady exists?
PLAYGROUND_PATH="./src/$playground"
if [ -d $PLAYGROUND_PATH ]; then
echo "Project Already Exists!!!"
exit 1;
fi
# Create Project Folder
mkdir $PLAYGROUND_PATH
# Copy Sample Files to Project Folder
cp ./src/sample/* $PLAYGROUND_PATH
# Success Message
echo 'Project Created Successfully !!!'
echo "To run project : parcel src/$playground/index.html"
echo -e "Append your package.json scritp section :\` \"$playground\": \"parcel src/$playground/index.html\"\`"
|
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex('projects').del()
.then(function () {
// Inserts seed entries
return knex('projects').insert([
{
title: 'To-do List',
description: "It's a to-do list",
is_approved: true,
front_end_spots: 10,
back_end_spots: 3,
ios_spots: 3,
android_spots: 1,
data_science_spots: 2,
ux_spots: 1,
creator_id: 1,
hackathon_id: 1,
is_solo: false
},
{
title: 'Guidr',
description: "It's an app",
is_approved: true,
front_end_spots: 10,
back_end_spots: 3,
ios_spots: 3,
android_spots: 1,
data_science_spots: 2,
ux_spots: 1,
creator_id: 5,
hackathon_id: 1,
is_solo: false
},
{
title: 'Community Calendar',
description: "It's a calendar",
front_end_spots: 15,
back_end_spots: 6,
ios_spots: 3,
android_spots: 6,
data_science_spots: 3,
ux_spots: 2,
creator_id: 2,
hackathon_id: 2,
is_approved: false,
is_solo: false
},
{
title: 'Expat Journal',
description: "It's a project",
is_approved: true,
front_end_spots: 0,
back_end_spots: 0,
ios_spots: 0,
android_spots: 0,
data_science_spots: 0,
ux_spots: 0,
creator_id: 0,
hackathon_id: 3,
is_solo: true,
is_solo_and_taken: false
},
]);
});
};
|
<gh_stars>0
import pandas as pd
# Function to add date variables to DataFrame.
def add_date_info(df):
df['Timestamp'] = pd.to_datetime(df['millis'], unit='ms')
df['Year'] = pd.DatetimeIndex(df['Timestamp']).year
df['Month'] = pd.DatetimeIndex(df['Timestamp']).month
df['Day'] = pd.DatetimeIndex(df['Timestamp']).day
df['DOY'] = pd.DatetimeIndex(df['Timestamp']).dayofyear
return df
|
#!/bin/sh
set -e
if [ "$1" = configure ]; then
/bin/systemctl daemon-reload
/bin/systemctl enable proton-server
fi
|
#!/bin/bash -eu
cmd="$1"
function running_as_root
{
test "$(id -u)" = "0"
}
function secure_mode_enabled
{
test "${SECURE_FILE_PERMISSIONS:=no}" = "yes"
}
function containsElement
{
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 0; done
return 1
}
function is_readable
{
# this code is fairly ugly but works no matter who this script is running as.
# It would be nice if the writability tests could use this logic somehow.
local _file=${1}
perm=$(stat -c %a "${_file}")
# everyone permission
if [[ ${perm:2:1} -ge 4 ]]; then
return 0
fi
# owner permissions
if [[ ${perm:0:1} -ge 4 ]]; then
if [[ "$(stat -c %U ${_file})" = "${userid}" ]] || [[ "$(stat -c %u ${_file})" = "${userid}" ]]; then
return 0
fi
fi
# group permissions
if [[ ${perm:1:1} -ge 4 ]]; then
if containsElement "$(stat -c %g ${_file})" "${groups[@]}" || containsElement "$(stat -c %G ${_file})" "${groups[@]}" ; then
return 0
fi
fi
return 1
}
function is_writable
{
# It would be nice if this and the is_readable function could combine somehow
local _file=${1}
perm=$(stat -c %a "${_file}")
# everyone permission
if containsElement ${perm:2:1} 2 3 6 7; then
return 0
fi
# owner permissions
if containsElement ${perm:0:1} 2 3 6 7; then
if [[ "$(stat -c %U ${_file})" = "${userid}" ]] || [[ "$(stat -c %u ${_file})" = "${userid}" ]]; then
return 0
fi
fi
# group permissions
if containsElement ${perm:1:1} 2 3 6 7; then
if containsElement "$(stat -c %g ${_file})" "${groups[@]}" || containsElement "$(stat -c %G ${_file})" "${groups[@]}" ; then
return 0
fi
fi
return 1
}
function print_permissions_advice_and_fail
{
_directory=${1}
echo >&2 "
Folder ${_directory} is not accessible for user: ${userid} or group ${groupid} or groups ${groups[@]}, this is commonly a file permissions issue on the mounted folder.
Hints to solve the issue:
1) Make sure the folder exists before mounting it. Docker will create the folder using root permissions before starting the ONgDB container. The root permissions disallow ONgDB from writing to the mounted folder.
2) Pass the folder owner's user ID and group ID to docker run, so that docker runs as that user.
If the folder is owned by the current user, this can be done by adding this flag to your docker run command:
--user=\$(id -u):\$(id -g)
"
exit 1
}
function check_mounted_folder_readable
{
local _directory=${1}
if ! is_readable "${_directory}"; then
print_permissions_advice_and_fail "${_directory}"
fi
}
function check_mounted_folder_with_chown
{
# The /data and /log directory are a bit different because they are very likely to be mounted by the user but not
# necessarily writable.
# This depends on whether a user ID is passed to the container and which folders are mounted.
#
# No user ID passed to container:
# 1) No folders are mounted.
# The /data and /log folder are owned by ongdb by default, so should be writable already.
# 2) Both /log and /data are mounted.
# This means on start up, /data and /logs are owned by an unknown user and we should chown them to ongdb for
# backwards compatibility.
#
# User ID passed to container:
# 1) Both /data and /logs are mounted
# The /data and /logs folders are owned by an unknown user but we *should* have rw permission to them.
# That should be verified and error (helpfully) if not.
# 2) User mounts /data or /logs *but not both*
# The unmounted folder is still owned by ongdb, which should already be writable. The mounted folder should
# have rw permissions through user id. This should be verified.
# 3) No folders are mounted.
# The /data and /log folder are owned by ongdb by default, and these are already writable by the user.
# (This is a very unlikely use case).
local mountFolder=${1}
if running_as_root; then
if ! is_writable "${mountFolder}" && ! secure_mode_enabled; then
# warn that we're about to chown the folder and then chown it
echo "Warning: Folder mounted to \"${mountFolder}\" is not writable from inside container. Changing folder owner to ${userid}."
chown -R "${userid}":"${groupid}" "${mountFolder}"
fi
else
if [[ ! -w "${mountFolder}" ]] && [[ "$(stat -c %U ${mountFolder})" != "ongdb" ]]; then
print_permissions_advice_and_fail "${mountFolder}"
fi
fi
}
function load_plugin_from_github
{
# Load a plugin at runtime. The provided github repository must have a versions.json on the master branch with the
# correct format.
local _plugin_name="${1}" #e.g. apoc, graph-algorithms, graph-ql
local _plugins_dir="${ONGDB_HOME}/plugins"
if [ -d /plugins ]; then
local _plugins_dir="/plugins"
fi
local _versions_json_url="$(jq --raw-output "with_entries( select(.key==\"${_plugin_name}\") ) | to_entries[] | .value.versions" /ongdb-plugins.json )"
# Using the same name for the plugin irrespective of version ensures we don't end up with different versions of the same plugin
local _destination="${_plugins_dir}/${_plugin_name}.jar"
local _ongdb_version="$(ongdb --version | cut -d' ' -f2)"
# Now we call out to github to get the versions.json for this plugin and we parse that to find the url for the correct plugin jar for our ongdb version
echo "Fetching versions.json for Plugin '${_plugin_name}' from ${_versions_json_url}"
local _versions_json="$(wget -q --timeout 300 --tries 30 -O - "${_versions_json_url}")"
local _plugin_jar_url="$(echo "${_versions_json}" | jq --raw-output ".[] | select(.ongdb==\"${_ongdb_version}\") | .jar")"
if [[ -z "${_plugin_jar_url}" ]]; then
echo >&2 "Error: No jar URL found for version '${_ongdb_version}' in versions.json from '${_versions_json_url}'"
echo >&2 "${_versions_json}"
exit 1
fi
echo "Installing Plugin '${_plugin_name}' from ${_plugin_jar_url} to ${_destination} "
wget -q --timeout 300 --tries 30 --output-document="${_destination}" "${_plugin_jar_url}"
if ! is_readable "${_destination}"; then
echo >&2 "Plugin at '${_destination}' is not readable"
exit 1
fi
}
function apply_plugin_default_configuration
{
# Set the correct Load a plugin at runtime. The provided github repository must have a versions.json on the master branch with the
# correct format.
local _plugin_name="${1}" #e.g. apoc, graph-algorithms, graph-ql
local _reference_conf="${2}" # used to determine if we can override properties
local _ongdb_conf="${ONGDB_HOME}/conf/ongdb.conf"
local _property _value
echo "Applying default values for plugin ${_plugin_name} to ongdb.conf"
for _entry in $(jq --compact-output --raw-output "with_entries( select(.key==\"${_plugin_name}\") ) | to_entries[] | .value.properties | to_entries[]" /ongdb-plugins.json); do
_property="$(jq --raw-output '.key' <<< "${_entry}")"
_value="$(jq --raw-output '.value' <<< "${_entry}")"
# the first grep strips out comments
if grep -o "^[^#]*" "${_reference_conf}" | grep -q --fixed-strings "${_property}=" ; then
# property is already set in the user provided config. In this case we don't override what has been set explicitly by the user.
echo "Skipping ${_property} for plugin ${_plugin_name} because it is already set"
else
if grep -o "^[^#]*" "${_ongdb_conf}" | grep -q --fixed-strings "${_property}=" ; then
sed --in-place "s/${_property}=/&${_value},/" "${_ongdb_conf}"
else
echo "${_property}=${_value}" >> "${_ongdb_conf}"
fi
fi
done
}
function install_ongdb_plugins
{
# We store a copy of the config before we modify it for the plugins to allow us to see if there are user-set values in the input config that we shouldn't override
local _old_config="$(mktemp)"
cp "${ONGDB_HOME}"/conf/ongdb.conf "${_old_config}"
for plugin_name in $(echo "${ONGDB_PLUGINS}" | jq --raw-output '.[]'); do
load_plugin_from_github "${plugin_name}"
apply_plugin_default_configuration "${plugin_name}" "${_old_config}"
done
rm "${_old_config}"
}
# If we're running as root, then run as the ongdb user. Otherwise
# docker is running with --user and we simply use that user. Note
# that su-exec, despite its name, does not replicate the functionality
# of exec, so we need to use both
if running_as_root; then
userid="ongdb"
groupid="ongdb"
groups=($(id -G ongdb))
exec_cmd="exec gosu ongdb:ongdb"
else
userid="$(id -u)"
groupid="$(id -g)"
groups=($(id -G))
exec_cmd="exec"
fi
readonly userid
readonly groupid
readonly groups
readonly exec_cmd
# Need to chown the home directory - but a user might have mounted a
# volume here (notably a conf volume). So take care not to chown
# volumes (stuff not owned by ongdb)
if running_as_root; then
# Non-recursive chown for the base directory
chown "${userid}":"${groupid}" "${ONGDB_HOME}"
chmod 700 "${ONGDB_HOME}"
find "${ONGDB_HOME}" -mindepth 1 -maxdepth 1 -user root -type d -exec chown -R ${userid}:${groupid} {} \;
find "${ONGDB_HOME}" -mindepth 1 -maxdepth 1 -user root -type d -exec chmod -R 700 {} \;
fi
# Env variable naming convention:
# - prefix ONGDB_
# - double underscore char '__' instead of single underscore '_' char in the setting name
# - underscore char '_' instead of dot '.' char in the setting name
# Example:
# ONGDB_dbms_tx__log_rotation_retention__policy env variable to set
# dbms.tx_log.rotation.retention_policy setting
# Backward compatibility - map old hardcoded env variables into new naming convention (if they aren't set already)
# Set some to default values if unset
: ${ONGDB_dbms_tx__log_rotation_retention__policy:=${ONGDB_dbms_txLog_rotation_retentionPolicy:-"100M size"}}
: ${ONGDB_wrapper_java_additional:=${ONGDB_UDC_SOURCE:-"-Dongdb.ext.udc.source=docker"}}
: ${ONGDB_dbms_unmanaged__extension__classes:=${ONGDB_dbms_unmanagedExtensionClasses:-}}
: ${ONGDB_dbms_allow__format__migration:=${ONGDB_dbms_allowFormatMigration:-}}
: ${ONGDB_dbms_connectors_default__advertised__address:=${ONGDB_dbms_connectors_defaultAdvertisedAddress:-}}
: ${ONGDB_ha_server__id:=${ONGDB_ha_serverId:-}}
: ${ONGDB_ha_initial__hosts:=${ONGDB_ha_initialHosts:-}}
if [ "${ONGDB_EDITION}" == "enterprise" ];
then
: ${ONGDB_causal__clustering_expected__core__cluster__size:=${ONGDB_causalClustering_expectedCoreClusterSize:-}}
: ${ONGDB_causal__clustering_initial__discovery__members:=${ONGDB_causalClustering_initialDiscoveryMembers:-}}
: ${ONGDB_causal__clustering_discovery__advertised__address:=${ONGDB_causalClustering_discoveryAdvertisedAddress:-"$(hostname):5000"}}
: ${ONGDB_causal__clustering_transaction__advertised__address:=${ONGDB_causalClustering_transactionAdvertisedAddress:-"$(hostname):6000"}}
: ${ONGDB_causal__clustering_raft__advertised__address:=${ONGDB_causalClustering_raftAdvertisedAddress:-"$(hostname):7000"}}
# Custom settings for dockerized ongdb
: ${ONGDB_ha_host_coordination:=$(hostname):5001}
: ${ONGDB_ha_host_data:=$(hostname):6001}
: ${ONGDB_causal__clustering_discovery__advertised__address:=$(hostname):5000}
: ${ONGDB_causal__clustering_transaction__advertised__address:=$(hostname):6000}
: ${ONGDB_causal__clustering_raft__advertised__address:=$(hostname):7000}
fi
# unset old hardcoded unsupported env variables
unset ONGDB_dbms_txLog_rotation_retentionPolicy ONGDB_UDC_SOURCE \
ONGDB_dbms_unmanagedExtensionClasses ONGDB_dbms_allowFormatMigration \
ONGDB_dbms_connectors_defaultAdvertisedAddress ONGDB_ha_serverId \
ONGDB_ha_initialHosts ONGDB_causalClustering_expectedCoreClusterSize \
ONGDB_causalClustering_initialDiscoveryMembers \
ONGDB_causalClustering_discoveryListenAddress \
ONGDB_causalClustering_discoveryAdvertisedAddress \
ONGDB_causalClustering_transactionListenAddress \
ONGDB_causalClustering_transactionAdvertisedAddress \
ONGDB_causalClustering_raftListenAddress \
ONGDB_causalClustering_raftAdvertisedAddress
if [ -d /conf ]; then
if secure_mode_enabled; then
check_mounted_folder_readable "/conf"
fi
find /conf -type f -exec cp {} "${ONGDB_HOME}"/conf \;
fi
if [ -d /ssl ]; then
if secure_mode_enabled; then
check_mounted_folder_readable "/ssl"
fi
: ${ONGDB_dbms_directories_certificates:="/ssl"}
fi
if [ -d /plugins ]; then
if secure_mode_enabled; then
if [[ ! -z "${ONGDB_PLUGINS:-}" ]]; then
# We need write permissions
check_mounted_folder_with_chown "/plugins"
fi
check_mounted_folder_readable "/plugins"
fi
: ${ONGDB_dbms_directories_plugins:="/plugins"}
fi
if [ -d /import ]; then
if secure_mode_enabled; then
check_mounted_folder_readable "/import"
fi
: ${ONGDB_dbms_directories_import:="/import"}
fi
if [ -d /metrics ]; then
if secure_mode_enabled; then
check_mounted_folder_readable "/metrics"
fi
: ${ONGDB_dbms_directories_metrics:="/metrics"}
fi
if [ -d /logs ]; then
check_mounted_folder_with_chown "/logs"
: ${ONGDB_dbms_directories_logs:="/logs"}
fi
if [ -d /data ]; then
check_mounted_folder_with_chown "/data"
if [ -d /data/databases ]; then
check_mounted_folder_with_chown "/data/databases"
fi
if [ -d /data/dbms ]; then
check_mounted_folder_with_chown "/data/dbms"
fi
fi
if [ -d /data ]; then
check_mounted_folder_with_chown "/data"
fi
# set the ongdb initial password only if you run the database server
if [ "${cmd}" == "ongdb" ]; then
if [ "${ONGDB_AUTH:-}" == "none" ]; then
ONGDB_dbms_security_auth__enabled=false
elif [[ "${ONGDB_AUTH:-}" == ongdb/* ]]; then
password="${ONGDB_AUTH#ongdb/}"
if [ "${password}" == "ongdb" ]; then
echo >&2 "Invalid value for password. It cannot be 'ongdb', which is the default."
exit 1
fi
if running_as_root; then
# running set-initial-password as root will create subfolders to /data as root, causing startup fail when ongdb can't read or write the /data/dbms folder
# creating the folder first will avoid that
mkdir -p /data/dbms
chown "${userid}":"${groupid}" /data/dbms
fi
# Will exit with error if users already exist (and print a message explaining that)
# we probably don't want the message though, since it throws an error message on restarting the container.
ongdb-admin set-initial-password "${password}" 2>/dev/null || true
elif [ -n "${ONGDB_AUTH:-}" ]; then
echo >&2 "Invalid value for ONGDB_AUTH: '${ONGDB_AUTH}'"
exit 1
fi
fi
declare -A COMMUNITY
declare -A ENTERPRISE
COMMUNITY=(
[dbms.tx_log.rotation.retention_policy]="100M size"
[dbms.memory.pagecache.size]="512M"
[dbms.connectors.default_listen_address]="0.0.0.0"
[dbms.connector.https.listen_address]="0.0.0.0:7473"
[dbms.connector.http.listen_address]="0.0.0.0:7474"
[dbms.connector.bolt.listen_address]="0.0.0.0:7687"
[dbms.udc.enabled]="false"
)
ENTERPRISE=(
)
for conf in ${!COMMUNITY[@]} ; do
if ! grep -q "^$conf" "${ONGDB_HOME}"/conf/ongdb.conf
then
echo -e "\n"$conf=${COMMUNITY[$conf]} >> "${ONGDB_HOME}"/conf/ongdb.conf
fi
done
for conf in ${!ENTERPRISE[@]} ; do
if [ "${ONGDB_EDITION}" == "enterprise" ];
then
if ! grep -q "^$conf" "${ONGDB_HOME}"/conf/ongdb.conf
then
echo -e "\n"$conf=${ENTERPRISE[$conf]} >> "${ONGDB_HOME}"/conf/ongdb.conf
fi
fi
done
#The udc.source=tarball should be replaced by udc.source=docker in both dbms.jvm.additional and wrapper.java.additional
#Using sed to replace only this part will allow the custom configs to be added after, separated by a ,.
if grep -q "udc.source=tarball" "${ONGDB_HOME}"/conf/ongdb.conf; then
sed -i -e 's/udc.source=tarball/udc.source=docker/g' "${ONGDB_HOME}"/conf/ongdb.conf
fi
#The udc.source should always be set to docker by default and we have to allow also custom configs to be added after that.
#In this case, this piece of code helps to add the default value and a , to support custom configs after.
if ! grep -q "dbms.jvm.additional=-Dunsupported.dbms.udc.source=docker" "${ONGDB_HOME}"/conf/ongdb.conf; then
sed -i -e 's/dbms.jvm.additional=/dbms.jvm.additional=-Dunsupported.dbms.udc.source=docker,/g' "${ONGDB_HOME}"/conf/ongdb.conf
fi
# list env variables with prefix ONGDB_ and create settings from them
unset ONGDB_AUTH ONGDB_SHA256 ONGDB_TARBALL
for i in $( set | grep ^ONGDB_ | awk -F'=' '{print $1}' | sort -rn ); do
setting=$(echo ${i} | sed 's|^ONGDB_||' | sed 's|_|.|g' | sed 's|\.\.|_|g')
value=$(echo ${!i})
# Don't allow settings with no value or settings that start with a number (ongdb converts settings to env variables and you cannot have an env variable that starts with a number)
if [[ -n ${value} ]]; then
if [[ ! "${setting}" =~ ^[0-9]+.*$ ]]; then
if grep -q -F "${setting}=" "${ONGDB_HOME}"/conf/ongdb.conf; then
# Remove any lines containing the setting already
sed --in-place "/^${setting}=.*/d" "${ONGDB_HOME}"/conf/ongdb.conf
fi
# Then always append setting to file
echo "${setting}=${value}" >> "${ONGDB_HOME}"/conf/ongdb.conf
else
echo >&2 "WARNING: ${setting} not written to conf file because settings that start with a number are not permitted"
fi
fi
done
if [[ ! -z "${ONGDB_PLUGINS:-}" ]]; then
# ONGDB_PLUGINS should be a json array of plugins like '["graph-algorithms", "apoc", "streams", "graphql"]'
install_ongdb_plugins
fi
[ -f "${EXTENSION_SCRIPT:-}" ] && . ${EXTENSION_SCRIPT}
if [ "${cmd}" == "dump-config" ]; then
if ! is_writable "/conf"; then
print_permissions_advice_and_fail "/conf"
fi
cp --recursive "${ONGDB_HOME}"/conf/* /conf
echo "Config Dumped"
exit 0
fi
# Use su-exec to drop privileges to ongdb user
# Note that su-exec, despite its name, does not replicate the
# functionality of exec, so we need to use both
if [ "${cmd}" == "ongdb" ]; then
${exec_cmd} ongdb console
else
${exec_cmd} "$@"
fi
|
package org.datacontract.schemas._2004._07.EEN_Merlin_Backend_Core_BO_PODService;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for profileCustomprops complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="profileCustomprops">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="item" type="{http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService}ArrayOfprofileCustompropsItem" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "profileCustomprops", propOrder = {
"item"
})
public class ProfileCustompropsType {
@XmlElementRef(name = "item", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false)
protected JAXBElement<ArrayOfprofileCustompropsItemType> item;
/**
* Gets the value of the item property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link ArrayOfprofileCustompropsItemType }{@code >}
*
*/
public JAXBElement<ArrayOfprofileCustompropsItemType> getItem() {
return item;
}
/**
* Sets the value of the item property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link ArrayOfprofileCustompropsItemType }{@code >}
*
*/
public void setItem(JAXBElement<ArrayOfprofileCustompropsItemType> value) {
this.item = value;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.