code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
create function get_person(person_id integer)
returns integer as
$$
begin
return person_id;
end;
$$ language plpgsql;
|
endeavourhealth/DBPatcher
|
src/test/resources/testdb/functions/get_person.sql
|
SQL
|
apache-2.0
| 119
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.ehcache;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.support.DefaultConsumer;
import org.ehcache.Cache;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
public class EhcacheConsumer extends DefaultConsumer implements CacheEventListener<Object, Object> {
private final EhcacheConfiguration configuration;
private final EhcacheManager manager;
private final Cache cache;
public EhcacheConsumer(EhcacheEndpoint endpoint, String cacheName, EhcacheConfiguration configuration, Processor processor) throws Exception {
super(endpoint, processor);
this.configuration = configuration;
this.manager = endpoint.getManager();
Class<?> kt = null;
if (configuration.getKeyType() != null) {
kt = getEndpoint().getCamelContext().getClassResolver().resolveClass(configuration.getKeyType());
}
Class<?> vt = null;
if (configuration.getValueType() != null) {
vt = getEndpoint().getCamelContext().getClassResolver().resolveClass(configuration.getValueType());
}
this.cache = manager.getCache(cacheName, kt, vt);
}
@Override
protected void doStart() throws Exception {
super.doStart();
this.cache.getRuntimeConfiguration().registerCacheEventListener(
this,
configuration.getEventOrdering(),
configuration.getEventFiring(),
configuration.getEventTypes()
);
}
@Override
protected void doStop() throws Exception {
cache.getRuntimeConfiguration().deregisterCacheEventListener(this);
super.doStop();
}
@Override
public void onEvent(CacheEvent<?, ?> event) {
if (isRunAllowed()) {
final Exchange exchange = getEndpoint().createExchange();
final Message message = exchange.getIn();
message.setHeader(EhcacheConstants.KEY, event.getKey());
message.setHeader(EhcacheConstants.EVENT_TYPE, event.getType());
message.setHeader(EhcacheConstants.OLD_VALUE, event.getOldValue());
message.setBody(event.getNewValue());
try {
getProcessor().process(exchange);
} catch (Exception e) {
getExceptionHandler().handleException("Error processing exchange", exchange, e);
}
}
}
}
|
objectiser/camel
|
components/camel-ehcache/src/main/java/org/apache/camel/component/ehcache/EhcacheConsumer.java
|
Java
|
apache-2.0
| 3,304
|
package com.BISPL.config;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import com.BISPL.libraries.ExcelLibrary;
import com.BISPL.libraries.ProjectSpecificLibrary;
public class Config {
public WebDriver driver;
public ProjectSpecificLibrary plib;
@BeforeMethod
public void launchApplication(){
//Create object of ExcelLibrary
ExcelLibrary lib = new ExcelLibrary();
//Get browser on which application has to be launched
String browser = lib.getExcelData("settings",1,0);
//Get url of the application
String url = lib.getExcelData("settings",1,1);
System.out.println("Starting scenario");
//Compare the browser string and launch the respective browser
if(browser.equals("firefox")){
driver = new FirefoxDriver();
}
else if(browser.equals("ie")){
// File file = new File("D:/SeAutomation/hybridframework/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver","browserdrivers/IEDriverServer.exe");
// System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
driver = new InternetExplorerDriver();
}
else if(browser.equals("chrome")){
System.setProperty("webdriver.chrome.driver","browserdrivers/chromedriver.exe");
driver = new ChromeDriver();
}
driver.get(url);
// driver.get("http://localhost:8080/StellarBolas/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
plib = new ProjectSpecificLibrary(driver);
}
/* @AfterMethod
public void quiteApplication(){
driver.quit();
System.out.println("Ending scenario");
} */
}
|
SeleniumAutomation/SeleniumFramework
|
src/com/BISPL/config/Config.java
|
Java
|
apache-2.0
| 1,819
|
<!-- Intro Header -->
<header class="intro">
<div class="intro-body">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="brand-heading">{{ site.title }}</h1>
<p class="intro-text">{{ site.description }}<br>
<a href="#cv" class="btn btn-circle page-scroll">
<i class="fa fa-angle-double-down animated"></i>
</a>
</div>
</div>
</div>
</div>
</header>
|
stephen-mitchell/stephen-mitchell.github.io
|
_includes/header.html
|
HTML
|
apache-2.0
| 638
|
# Resinicium praeteritum (H.S. Jacks. & Dearden) Ginns & M.N.L. Lefebvre SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycol. Mem. 19: 138 (1993)
#### Original name
Corticium praeteritum H.S. Jacks. & Dearden
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Meruliaceae/Resinicium/Resinicium praeteritum/README.md
|
Markdown
|
apache-2.0
| 264
|
package org.ripple.power.blockchain.list;
import java.io.Serializable;
import org.ripple.bouncycastle.util.encoders.Hex;
public class DecodeResult implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int pos;
private Object decoded;
public DecodeResult(int pos, Object decoded) {
this.pos = pos;
this.decoded = decoded;
}
public int getPos() {
return pos;
}
public Object getDecoded() {
return decoded;
}
public String toString() {
return asString(this.decoded);
}
private String asString(Object decoded) {
if (decoded instanceof String) {
return (String) decoded;
} else if (decoded instanceof byte[]) {
return Hex.toHexString((byte[]) decoded);
} else if (decoded instanceof Object[]) {
String result = "";
for (Object item : (Object[]) decoded) {
result += asString(item);
}
return result;
}
throw new RuntimeException("Not a valid type. Should not occur");
}
}
|
cping/RipplePower
|
eclipse/RipplePower/src/org/ripple/power/blockchain/list/DecodeResult.java
|
Java
|
apache-2.0
| 974
|
### Installing Ruby
Mac install be default, has a ruby install. This is installed in a folder that is root/admin owned. Need to install a ruby manager to install a client/user copy
* Install ruby version manager `brew install rbenv`
* Install Ruby `rbenv install 2.3.0`
* Initialize the Ruby Version `rbenv init`
* init may tell you to add something to .bash_profile
* `sudo vi .bash_profile`
* add the `eval "$(rbenv init -)"` command
* save and exit (esc wq enter)
* May have to restart console at this point
* Check the ruby manager to make sure proper version is running `rbenv local`
* If needed, change the version 'rbenv local 2.3.0`
* Check ruby version `ruby -v`. double check you are pointing at the correct ruby. `which ruby` can be useful as well
* Check path to where ruby gems are stored `gem env home`. This can be useful if you are having permission issues installing gems. by using rbenv, the directory is most likely in the users home folder
### Rails Console Cheatsheet
Rails console allows you to interact with the ActiveRecord models
Start rails console
```
rails c
```
View contract of the model
```
Article
```
Retrieve First record
```
Article.first
```
Retrieve first 5 records
```
Article.first 5
```
Create a new Record
```
myArticle = Article.new
myArticle.title = 'Hello World'
myArticle.save!
```
Find by Index Key
```
Article.find 123
```
Find
```
Article.where( title: 'Hello World' )
```
Run last command
```
_
```
### Gems
*awesome_print* - Allows you to call `ap <command>` to print the output in a formatted way.
example
```
Article.find 123
ap _
```
### Resources and Links
https://guides.rubyonrails.org/active_record_basics.html
|
swhalley/KnowledgeBase
|
Ruby.md
|
Markdown
|
apache-2.0
| 1,725
|
package edu.umass.ciir.kbbridge
import java.io.{PrintWriter, File}
import edu.umass.ciir.kbbridge.tac.TacQueryUtil
/**
* Created with IntelliJ IDEA.
* User: jdalton
* Date: 7/22/13
* Time: 1:27 PM
*/
object TacMentionLinkerScript extends App {
val allqueries = TacQueryUtil.queriesByYear()("2012")._2
//val queries2013 = allqueries("2009")._2 ++ allqueries("2010eval")._2 ++ allqueries("2011")._2 ++ allqueries("2012")._2++ allqueries("2013")._2
//val queries2013 = (allqueries.map(_._2)).flatten
val querySet = allqueries.map(q => q.mentionId).toSet
val docSet = allqueries.map(q => q.docId).toSet
println("queries: " + querySet.size + " docs: " + docSet.size)
writeAnnotationScript(querySet)
def writeAnnotationScript(docsRequiringAnnotation: Iterable[String]) = {
val outputFile = new File("./scripts/annotate-singleMentions-2012-qvm_local")
val n = 100000
var curBatch = 0
var p = new PrintWriter(outputFile.getAbsolutePath() + curBatch.toString + ".sh", "UTF-8")
for ((docSet, idx) <- (docsRequiringAnnotation grouped 1).zipWithIndex) {
val sb = new StringBuilder
if (idx % n == 0 && idx > 0) {
p.close
curBatch += 1
p = new PrintWriter(outputFile.getAbsolutePath() + curBatch.toString + ".sh", "UTF-8")
}
sb append "qsub -b y " + "-l mem_free=6G -l mem_token=6G" + " -cwd -o ./out/"
sb append docSet.head
sb append " -e ./err/"
sb append docSet.head
sb append " java -server -Xmx6G -Dfile.encoding=utf-8 -cp /work1/allan/jdalton/factorie-kbbridge-plugin/target/factorie-kbbridge-1.0-SNAPSHOT-jar-with-dependencies.jar cc.factorie.app.nlp.el.TacLinkingMain "
// sb append " /work1/allan/jdalton/tacco/scripts/runEntityLinker.sh "
// input query
sb append docSet.mkString(",")
sb append " /work1/allan/jdalton/entity-linking/tac-source2013-g34"
sb append " ./tac-singleMention-annotations-2012-qvm_local"
// println(sb.toString)
p.println(sb.toString)
}
p.close()
}
}
|
daltonj/KbBridge
|
src/main/scala/edu/umass/ciir/kbbridge/TacMentionLinkerScript.scala
|
Scala
|
apache-2.0
| 2,048
|
#!/usr/bin/env bash
# Copyright 2016 The Kubernetes 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.
# This script is for configuring kubernetes master and node instances. It is
# uploaded in the manifests tar ball.
# TODO: this script duplicates templating logic from cluster/saltbase/salt
# using sed. It should use an actual template parser on the manifest
# files.
set -o errexit
set -o nounset
set -o pipefail
### Hardcoded constants
METADATA_SERVER_IP="${METADATA_SERVER_IP:-169.254.169.254}"
function convert-manifest-params {
# A helper function to convert the manifest args from a string to a list of
# flag arguments.
# Old format:
# command=["/bin/sh", "-c", "exec KUBE_EXEC_BINARY --param1=val1 --param2-val2"].
# New format:
# command=["KUBE_EXEC_BINARY"] # No shell dependencies.
# args=["--param1=val1", "--param2-val2"]
IFS=' ' read -ra FLAGS <<< "$1"
params=""
for flag in "${FLAGS[@]}"; do
params+="\n\"$flag\","
done
if [ -n "$params" ]; then
echo "${params::-1}" # drop trailing comma
fi
}
function append-param-if-not-present {
# A helper function to add flag to an arguments string
# if no such flag is present already
local params="$1"
local -r flag="$2"
local -r value="$3"
if [[ ! "${params}" =~ "--${flag}"[=\ ] ]]; then
params+=" --${flag}=${value}"
fi
echo "${params}"
}
function setup-os-params {
# Reset core_pattern. On GCI, the default core_pattern pipes the core dumps to
# /sbin/crash_reporter which is more restrictive in saving crash dumps. So for
# now, set a generic core_pattern that users can work with.
echo "/core.%e.%p.%t" > /proc/sys/kernel/core_pattern
}
# secure_random generates a secure random string of bytes. This function accepts
# a number of secure bytes desired and returns a base64 encoded string with at
# least the requested entropy. Rather than directly reading from /dev/urandom,
# we use uuidgen which calls getrandom(2). getrandom(2) verifies that the
# entropy pool has been initialized sufficiently for the desired operation
# before reading from /dev/urandom.
#
# ARGS:
# #1: number of secure bytes to generate. We round up to the nearest factor of 32.
function secure_random {
local infobytes="${1}"
if ((infobytes <= 0)); then
echo "Invalid argument to secure_random: infobytes='${infobytes}'" 1>&2
return 1
fi
local out=""
for (( i = 0; i < "${infobytes}"; i += 32 )); do
# uuids have 122 random bits, sha256 sums have 256 bits, so concatenate
# three uuids and take their sum. The sum is encoded in ASCII hex, hence the
# 64 character cut.
out+="$(
(
uuidgen --random;
uuidgen --random;
uuidgen --random;
) | sha256sum \
| head -c 64
)";
done
# Finally, convert the ASCII hex to base64 to increase the density.
echo -n "${out}" | xxd -r -p | base64 -w 0
}
# Helper for configuring iptables rules for metadata server.
#
# $1 is the command flag (-I or -D).
# $2 is the firewall action (LOG or REJECT).
# $3 is the prefix for log output.
# $4 is "!" to optionally invert the uid range.
function gce-metadata-fw-helper {
local -r command="$1"
local action="$2"
local -r prefix="$3"
local -r invert="${4:-}"
# Expand rule action to include relevant option flags.
case "${action}" in
LOG)
action="LOG --log-prefix "${prefix}:" --log-uid --log-tcp-options --log-ip-option"
;;
esac
# Deliberately allow word split here
# shellcheck disable=SC2086
iptables -w ${command} OUTPUT -p tcp --dport 80 -d ${METADATA_SERVER_IP} -m owner ${invert:-} --uid-owner=${METADATA_SERVER_ALLOWED_UID_RANGE:-0-2999} -j ${action}
}
function config-ip-firewall {
echo "Configuring IP firewall rules"
# Do not consider loopback addresses as martian source or destination while
# routing. This enables the use of 127/8 for local routing purposes.
sysctl -w net.ipv4.conf.all.route_localnet=1
# The GCI image has host firewall which drop most inbound/forwarded packets.
# We need to add rules to accept all TCP/UDP/ICMP/SCTP packets.
if iptables -w -L INPUT | grep "Chain INPUT (policy DROP)" > /dev/null; then
echo "Add rules to accept all inbound TCP/UDP/ICMP packets"
iptables -w -A INPUT -w -p TCP -j ACCEPT
iptables -w -A INPUT -w -p UDP -j ACCEPT
iptables -w -A INPUT -w -p ICMP -j ACCEPT
iptables -w -A INPUT -w -p SCTP -j ACCEPT
fi
if iptables -w -L FORWARD | grep "Chain FORWARD (policy DROP)" > /dev/null; then
echo "Add rules to accept all forwarded TCP/UDP/ICMP/SCTP packets"
iptables -w -A FORWARD -w -p TCP -j ACCEPT
iptables -w -A FORWARD -w -p UDP -j ACCEPT
iptables -w -A FORWARD -w -p ICMP -j ACCEPT
iptables -w -A FORWARD -w -p SCTP -j ACCEPT
fi
# Flush iptables nat table
iptables -w -t nat -F || true
if [[ "${NON_MASQUERADE_CIDR:-}" == "0.0.0.0/0" ]]; then
echo "Add rules for ip masquerade"
iptables -w -t nat -N IP-MASQ
iptables -w -t nat -A POSTROUTING -m comment --comment "ip-masq: ensure nat POSTROUTING directs all non-LOCAL destination traffic to our custom IP-MASQ chain" -m addrtype ! --dst-type LOCAL -j IP-MASQ
iptables -w -t nat -A IP-MASQ -d 169.254.0.0/16 -m comment --comment "ip-masq: local traffic is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 10.0.0.0/8 -m comment --comment "ip-masq: RFC 1918 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 172.16.0.0/12 -m comment --comment "ip-masq: RFC 1918 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 192.168.0.0/16 -m comment --comment "ip-masq: RFC 1918 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 240.0.0.0/4 -m comment --comment "ip-masq: RFC 5735 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 192.0.2.0/24 -m comment --comment "ip-masq: RFC 5737 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 198.51.100.0/24 -m comment --comment "ip-masq: RFC 5737 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 203.0.113.0/24 -m comment --comment "ip-masq: RFC 5737 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 100.64.0.0/10 -m comment --comment "ip-masq: RFC 6598 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 198.18.0.0/15 -m comment --comment "ip-masq: RFC 6815 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 192.0.0.0/24 -m comment --comment "ip-masq: RFC 6890 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -d 192.88.99.0/24 -m comment --comment "ip-masq: RFC 7526 reserved range is not subject to MASQUERADE" -j RETURN
iptables -w -t nat -A IP-MASQ -m comment --comment "ip-masq: outbound traffic is subject to MASQUERADE (must be last in chain)" -j MASQUERADE
fi
# If METADATA_CONCEALMENT_NO_FIREWALL is set, don't create a firewall on this
# node because we don't expect the daemonset to run on this node.
if [[ "${ENABLE_METADATA_CONCEALMENT:-}" == "true" ]] && [[ ! "${METADATA_CONCEALMENT_NO_FIREWALL:-}" == "true" ]]; then
echo "Add rule for metadata concealment"
iptables -w -t nat -I PREROUTING -p tcp ! -i eth0 -d "${METADATA_SERVER_IP}" --dport 80 -m comment --comment "metadata-concealment: bridge traffic to metadata server goes to metadata proxy" -j REDIRECT --to-ports 988
iptables -w -t nat -I PREROUTING -p tcp ! -i eth0 -d "${METADATA_SERVER_IP}" --dport 8080 -m comment --comment "metadata-concealment: bridge traffic to metadata server goes to metadata proxy" -j REDIRECT --to-ports 987
fi
iptables -w -t mangle -I OUTPUT -s 169.254.169.254 -j DROP
# Log all metadata access not from approved processes.
case "${METADATA_SERVER_FIREWALL_MODE:-off}" in
log)
echo "Installing metadata firewall logging rules"
gce-metadata-fw-helper -I LOG "MetadataServerFirewallReject" !
gce-metadata-fw-helper -I LOG "MetadataServerFirewallAccept"
;;
esac
}
function create-dirs {
echo "Creating required directories"
mkdir -p /var/lib/kubelet
mkdir -p /etc/kubernetes/manifests
if [[ "${KUBERNETES_MASTER:-}" == "false" ]]; then
mkdir -p /var/lib/kube-proxy
fi
}
# Gets the total number of $(1) and $(2) type disks specified
# by the user in ${NODE_LOCAL_SSDS_EXT}
function get-local-disk-num() {
local interface="${1}"
local format="${2}"
localdisknum=0
if [[ -n "${NODE_LOCAL_SSDS_EXT:-}" ]]; then
IFS=";" read -r -a ssdgroups <<< "${NODE_LOCAL_SSDS_EXT:-}"
for ssdgroup in "${ssdgroups[@]}"; do
IFS="," read -r -a ssdopts <<< "${ssdgroup}"
local opnum="${ssdopts[0]}"
local opinterface="${ssdopts[1]}"
local opformat="${ssdopts[2]}"
if [[ "${opformat,,}" == "${format,,}" && "${opinterface,,}" == "${interface,,}" ]]; then
localdisknum=$((localdisknum+opnum))
fi
done
fi
}
# Creates a symlink for a ($1) so that it may be used as block storage
function safe-block-symlink(){
local device="${1}"
local symdir="${2}"
mkdir -p "${symdir}"
get-or-generate-uuid "${device}"
local myuuid="${retuuid}"
local sym="${symdir}/local-ssd-${myuuid}"
# Do not "mkdir -p ${sym}" as that will cause unintended symlink behavior
ln -s "${device}" "${sym}"
echo "Created a symlink for SSD $ssd at ${sym}"
chmod a+w "${sym}"
}
# Gets a pregenerated UUID from ${ssdmap} if it exists, otherwise generates a new
# UUID and places it inside ${ssdmap}
function get-or-generate-uuid(){
local device="${1}"
local ssdmap="/home/kubernetes/localssdmap.txt"
echo "Generating or getting UUID from ${ssdmap}"
if [[ ! -e "${ssdmap}" ]]; then
touch "${ssdmap}"
chmod +w "${ssdmap}"
fi
# each line of the ssdmap looks like "${device} persistent-uuid"
local myuuid
if grep -q "${device}" "${ssdmap}"; then
#create symlink based on saved uuid
myuuid=$(grep "${device}" "${ssdmap}" | cut -d ' ' -f 2)
else
# generate new uuid and add it to the map
if ! myuuid=$(uuidgen); then
echo "Failed to generate valid UUID with uuidgen" >&2
exit 2
fi
echo "${device} ${myuuid}" >> "${ssdmap}"
fi
if [[ -z "${myuuid}" ]]; then
echo "Failed to get a uuid for device ${device} when symlinking." >&2
exit 2
fi
retuuid="${myuuid}"
}
#Formats the given device ($1) if needed and mounts it at given mount point
# ($2).
function safe-format-and-mount() {
local device
local mountpoint
device="$1"
mountpoint="$2"
# Format only if the disk is not already formatted.
if ! tune2fs -l "${device}" ; then
echo "Formatting '${device}'"
mkfs.ext4 -F "${device}"
fi
mkdir -p "${mountpoint}"
echo "Mounting '${device}' at '${mountpoint}'"
mount -o discard,defaults "${device}" "${mountpoint}"
chmod a+w "${mountpoint}"
}
# Gets a devices UUID and bind mounts the device to mount location in
# /mnt/disks/by-id/
function unique-uuid-bind-mount(){
local mountpoint
local actual_device
mountpoint="$1"
actual_device="$2"
# Trigger udev refresh so that newly formatted devices are propagated in by-uuid
udevadm control --reload-rules
udevadm trigger
udevadm settle
# find uuid for actual_device
local myuuid
myuuid=$(find -L /dev/disk/by-uuid -maxdepth 1 -samefile /dev/"${actual_device}" -printf '%P')
# myuuid should be the uuid of the device as found in /dev/disk/by-uuid/
if [[ -z "${myuuid}" ]]; then
echo "Failed to get a uuid for device ${actual_device} when mounting." >&2
exit 2
fi
# bindpoint should be the full path of the to-be-bound device
local bindpoint="${UUID_MNT_PREFIX}-${interface}-fs/local-ssd-${myuuid}"
safe-bind-mount "${mountpoint}" "${bindpoint}"
}
# Bind mounts device at mountpoint to bindpoint
function safe-bind-mount(){
local mountpoint="${1}"
local bindpoint="${2}"
# Mount device to the mountpoint
mkdir -p "${bindpoint}"
echo "Binding '${mountpoint}' at '${bindpoint}'"
mount --bind "${mountpoint}" "${bindpoint}"
chmod a+w "${bindpoint}"
}
# Mounts, bindmounts, or symlinks depending on the interface and format
# of the incoming device
function mount-ext(){
local ssd="${1}"
local devicenum="${2}"
local interface="${3}"
local format="${4}"
if [[ -z "${devicenum}" ]]; then
echo "Failed to get the local disk number for device ${ssd}" >&2
exit 2
fi
# TODO: Handle partitioned disks. Right now this code just ignores partitions
if [[ "${format}" == "fs" ]]; then
if [[ "${interface}" == "scsi" ]]; then
local actual_device
actual_device=$(readlink -f "${ssd}" | cut -d '/' -f 3)
# Error checking
if [[ "${actual_device}" != sd* ]]; then
echo "'actual_device' is not of the correct format. It must be the kernel name of the device, got ${actual_device} instead" >&2
exit 1
fi
local mountpoint="/mnt/disks/ssd${devicenum}"
else
# This path is required because the existing Google images do not
# expose NVMe devices in /dev/disk/by-id so we are using the /dev/nvme instead
local actual_device
actual_device=$(echo "${ssd}" | cut -d '/' -f 3)
# Error checking
if [[ "${actual_device}" != nvme* ]]; then
echo "'actual_device' is not of the correct format. It must be the kernel name of the device, got ${actual_device} instead" >&2
exit 1
fi
local mountpoint="/mnt/disks/ssd-nvme${devicenum}"
fi
safe-format-and-mount "${ssd}" "${mountpoint}"
# We only do the bindmount if users are using the new local ssd request method
# see https://github.com/kubernetes/kubernetes/pull/53466#discussion_r146431894
if [[ -n "${NODE_LOCAL_SSDS_EXT:-}" ]]; then
unique-uuid-bind-mount "${mountpoint}" "${actual_device}"
fi
elif [[ "${format}" == "block" ]]; then
local symdir="${UUID_BLOCK_PREFIX}-${interface}-block"
safe-block-symlink "${ssd}" "${symdir}"
else
echo "Disk format must be either fs or block, got ${format}"
fi
}
# Local ssds, if present, are mounted or symlinked to their appropriate
# locations
function ensure-local-ssds() {
if [ "${NODE_LOCAL_SSDS_EPHEMERAL:-false}" == "true" ]; then
ensure-local-ssds-ephemeral-storage
return
fi
get-local-disk-num "scsi" "block"
local scsiblocknum="${localdisknum}"
local i=0
for ssd in /dev/disk/by-id/google-local-ssd-*; do
if [ -e "${ssd}" ]; then
local devicenum
devicenum=$(echo "${ssd}" | sed -e 's/\/dev\/disk\/by-id\/google-local-ssd-\([0-9]*\)/\1/')
if [[ "${i}" -lt "${scsiblocknum}" ]]; then
mount-ext "${ssd}" "${devicenum}" "scsi" "block"
else
# GKE does not set NODE_LOCAL_SSDS so all non-block devices
# are assumed to be filesystem devices
mount-ext "${ssd}" "${devicenum}" "scsi" "fs"
fi
i=$((i+1))
else
echo "No local SCSI SSD disks found."
fi
done
# The following mounts or symlinks NVMe devices
get-local-disk-num "nvme" "block"
local nvmeblocknum="${localdisknum}"
get-local-disk-num "nvme" "fs"
local nvmefsnum="${localdisknum}"
# Check if NVMe SSD specified.
if [ "${nvmeblocknum}" -eq "0" ] && [ "${nvmefsnum}" -eq "0" ]; then
echo "No local NVMe SSD specified."
return
fi
local i=0
for ssd in /dev/nvme*; do
if [ -e "${ssd}" ]; then
# This workaround to find if the NVMe device is a disk is required because
# the existing Google images does not expose NVMe devices in /dev/disk/by-id
if [[ $(udevadm info --query=property --name="${ssd}" | grep DEVTYPE | sed "s/DEVTYPE=//") == "disk" ]]; then
# shellcheck disable=SC2155
local devicenum=$(echo "${ssd}" | sed -e 's/\/dev\/nvme0n\([0-9]*\)/\1/')
if [[ "${i}" -lt "${nvmeblocknum}" ]]; then
mount-ext "${ssd}" "${devicenum}" "nvme" "block"
else
mount-ext "${ssd}" "${devicenum}" "nvme" "fs"
fi
i=$((i+1))
fi
else
echo "No local NVMe SSD disks found."
fi
done
}
# Local SSDs, if present, are used in a single RAID 0 array and directories that
# back ephemeral storage are mounted on them (kubelet root, container runtime
# root and pod logs).
function ensure-local-ssds-ephemeral-storage() {
local devices=()
# Get nvme devices
for ssd in /dev/nvme*n*; do
if [ -e "${ssd}" ]; then
# This workaround to find if the NVMe device is a local SSD is required
# because the existing Google images does not them in /dev/disk/by-id
if [[ "$(lsblk -o MODEL -dn "${ssd}")" == "nvme_card" ]]; then
devices+=("${ssd}")
fi
fi
done
if [ "${#devices[@]}" -eq 0 ]; then
echo "No local NVMe SSD disks found."
return
fi
local device="${devices[0]}"
if [ "${#devices[@]}" -ne 1 ]; then
seen_arrays=(/dev/md/*)
device=${seen_arrays[0]}
echo "Setting RAID array with local SSDs on device ${device}"
if [ ! -e "$device" ]; then
device="/dev/md/0"
echo "y" | mdadm --create "${device}" --level=0 --raid-devices=${#devices[@]} "${devices[@]}"
fi
fi
local ephemeral_mountpoint="/mnt/stateful_partition/kube-ephemeral-ssd"
safe-format-and-mount "${device}" "${ephemeral_mountpoint}"
# mount container runtime root dir on SSD
local container_runtime="${CONTAINER_RUNTIME:-docker}"
systemctl stop "$container_runtime"
# Some images remount the container runtime root dir.
umount "/var/lib/${container_runtime}" || true
# Move the container runtime's directory to the new location to preserve
# preloaded images.
if [ ! -d "${ephemeral_mountpoint}/${container_runtime}" ]; then
mv "/var/lib/${container_runtime}" "${ephemeral_mountpoint}/${container_runtime}"
fi
safe-bind-mount "${ephemeral_mountpoint}/${container_runtime}" "/var/lib/${container_runtime}"
systemctl start "$container_runtime"
# mount kubelet root dir on SSD
mkdir -p "${ephemeral_mountpoint}/kubelet"
safe-bind-mount "${ephemeral_mountpoint}/kubelet" "/var/lib/kubelet"
# mount pod logs root dir on SSD
mkdir -p "${ephemeral_mountpoint}/log_pods"
safe-bind-mount "${ephemeral_mountpoint}/log_pods" "/var/log/pods"
}
# Installs logrotate configuration files
function setup-logrotate() {
mkdir -p /etc/logrotate.d/
if [[ "${ENABLE_LOGROTATE_FILES:-true}" = "true" ]]; then
# Configure log rotation for all logs in /var/log, which is where k8s services
# are configured to write their log files. Whenever logrotate is ran, this
# config will:
# * rotate the log file if its size is > 100Mb OR if one day has elapsed
# * save rotated logs into a gzipped timestamped backup
# * log file timestamp (controlled by 'dateformat') includes seconds too. This
# ensures that logrotate can generate unique logfiles during each rotation
# (otherwise it skips rotation if 'maxsize' is reached multiple times in a
# day).
# * keep only 5 old (rotated) logs, and will discard older logs.
cat > /etc/logrotate.d/allvarlogs <<EOF
/var/log/*.log {
rotate ${LOGROTATE_FILES_MAX_COUNT:-5}
copytruncate
missingok
notifempty
compress
maxsize ${LOGROTATE_MAX_SIZE:-100M}
daily
dateext
dateformat -%Y%m%d-%s
create 0644 root root
}
EOF
fi
if [[ "${ENABLE_POD_LOG:-false}" = "true" ]]; then
# Configure log rotation for pod logs in /var/log/pods/NAMESPACE_NAME_UID.
cat > /etc/logrotate.d/allpodlogs <<EOF
/var/log/pods/*/*.log {
rotate ${POD_LOG_MAX_FILE:-5}
copytruncate
missingok
notifempty
compress
maxsize ${POD_LOG_MAX_SIZE:-5M}
daily
dateext
dateformat -%Y%m%d-%s
create 0644 root root
}
EOF
fi
}
# Finds the master PD device; returns it in MASTER_PD_DEVICE
function find-master-pd {
MASTER_PD_DEVICE=""
if [[ ! -e /dev/disk/by-id/google-master-pd ]]; then
return
fi
device_info=$(ls -l /dev/disk/by-id/google-master-pd)
relative_path=${device_info##* }
MASTER_PD_DEVICE="/dev/disk/by-id/${relative_path}"
}
# Mounts a persistent disk (formatting if needed) to store the persistent data
# on the master -- etcd's data, a few settings, and security certs/keys/tokens.
# safe-format-and-mount only formats an unformatted disk, and mkdir -p will
# leave a directory be if it already exists.
function mount-master-pd {
find-master-pd
if [[ -z "${MASTER_PD_DEVICE:-}" ]]; then
return
fi
echo "Mounting master-pd"
local -r pd_path="/dev/disk/by-id/google-master-pd"
local -r mount_point="/mnt/disks/master-pd"
# Format and mount the disk, create directories on it for all of the master's
# persistent data, and link them to where they're used.
mkdir -p "${mount_point}"
safe-format-and-mount "${pd_path}" "${mount_point}"
echo "Mounted master-pd '${pd_path}' at '${mount_point}'"
# NOTE: These locations on the PD store persistent data, so to maintain
# upgradeability, these locations should not change. If they do, take care
# to maintain a migration path from these locations to whatever new
# locations.
# Contains all the data stored in etcd.
mkdir -p "${mount_point}/var/etcd"
chmod 700 "${mount_point}/var/etcd"
ln -s -f "${mount_point}/var/etcd" /var/etcd
mkdir -p /etc/srv
# Contains the dynamically generated apiserver auth certs and keys.
mkdir -p "${mount_point}/srv/kubernetes"
ln -s -f "${mount_point}/srv/kubernetes" /etc/srv/kubernetes
# Directory for kube-apiserver to store SSH key (if necessary).
mkdir -p "${mount_point}/srv/sshproxy"
ln -s -f "${mount_point}/srv/sshproxy" /etc/srv/sshproxy
chown -R etcd "${mount_point}/var/etcd"
chgrp -R etcd "${mount_point}/var/etcd"
}
# append_or_replace_prefixed_line ensures:
# 1. the specified file exists
# 2. existing lines with the specified ${prefix} are removed
# 3. a new line with the specified ${prefix}${suffix} is appended
function append_or_replace_prefixed_line {
local -r file="${1:-}"
local -r prefix="${2:-}"
local -r suffix="${3:-}"
local -r dirname=$(dirname "${file}")
local -r tmpfile=$(mktemp -t filtered.XXXX --tmpdir="${dirname}")
touch "${file}"
awk -v pfx="${prefix}" 'substr($0,1,length(pfx)) != pfx { print }' "${file}" > "${tmpfile}"
echo "${prefix}${suffix}" >> "${tmpfile}"
mv "${tmpfile}" "${file}"
}
function write-pki-data {
local data="${1}"
local path="${2}"
if [[ -n "${KUBE_PKI_READERS_GROUP:-}" ]]; then
(umask 027; echo "${data}" | base64 --decode > "${path}")
chgrp "${KUBE_PKI_READERS_GROUP:-}" "${path}"
chmod g+r "${path}"
else
(umask 077; echo "${data}" | base64 --decode > "${path}")
fi
}
function create-node-pki {
echo "Creating node pki files"
local -r pki_dir="/etc/srv/kubernetes/pki"
mkdir -p "${pki_dir}"
if [[ -z "${CA_CERT_BUNDLE:-}" ]]; then
CA_CERT_BUNDLE="${CA_CERT}"
fi
CA_CERT_BUNDLE_PATH="${pki_dir}/ca-certificates.crt"
write-pki-data "${CA_CERT_BUNDLE}" "${CA_CERT_BUNDLE_PATH}"
if [[ -n "${KUBELET_CERT:-}" && -n "${KUBELET_KEY:-}" ]]; then
KUBELET_CERT_PATH="${pki_dir}/kubelet.crt"
write-pki-data "${KUBELET_CERT}" "${KUBELET_CERT_PATH}"
KUBELET_KEY_PATH="${pki_dir}/kubelet.key"
write-pki-data "${KUBELET_KEY}" "${KUBELET_KEY_PATH}"
fi
}
function create-master-pki {
echo "Creating master pki files"
local -r pki_dir="/etc/srv/kubernetes/pki"
mkdir -p "${pki_dir}"
CA_CERT_PATH="${pki_dir}/ca.crt"
write-pki-data "${CA_CERT}" "${CA_CERT_PATH}"
# this is not true on GKE
if [[ -n "${CA_KEY:-}" ]]; then
CA_KEY_PATH="${pki_dir}/ca.key"
write-pki-data "${CA_KEY}" "${CA_KEY_PATH}"
fi
if [[ -z "${APISERVER_SERVER_CERT:-}" || -z "${APISERVER_SERVER_KEY:-}" ]]; then
APISERVER_SERVER_CERT="${MASTER_CERT}"
APISERVER_SERVER_KEY="${MASTER_KEY}"
fi
APISERVER_SERVER_CERT_PATH="${pki_dir}/apiserver.crt"
write-pki-data "${APISERVER_SERVER_CERT}" "${APISERVER_SERVER_CERT_PATH}"
APISERVER_SERVER_KEY_PATH="${pki_dir}/apiserver.key"
write-pki-data "${APISERVER_SERVER_KEY}" "${APISERVER_SERVER_KEY_PATH}"
if [[ -z "${APISERVER_CLIENT_CERT:-}" || -z "${APISERVER_CLIENT_KEY:-}" ]]; then
APISERVER_CLIENT_CERT="${KUBEAPISERVER_CERT}"
APISERVER_CLIENT_KEY="${KUBEAPISERVER_KEY}"
fi
APISERVER_CLIENT_CERT_PATH="${pki_dir}/apiserver-client.crt"
write-pki-data "${APISERVER_CLIENT_CERT}" "${APISERVER_CLIENT_CERT_PATH}"
APISERVER_CLIENT_KEY_PATH="${pki_dir}/apiserver-client.key"
write-pki-data "${APISERVER_CLIENT_KEY}" "${APISERVER_CLIENT_KEY_PATH}"
if [[ -z "${SERVICEACCOUNT_CERT:-}" || -z "${SERVICEACCOUNT_KEY:-}" ]]; then
SERVICEACCOUNT_CERT="${MASTER_CERT}"
SERVICEACCOUNT_KEY="${MASTER_KEY}"
fi
if [[ -n "${OLD_MASTER_CERT:-}" && -n "${OLD_MASTER_KEY:-}" ]]; then
OLD_MASTER_CERT_PATH="${pki_dir}/oldapiserver.crt"
echo "${OLD_MASTER_CERT}" | base64 --decode > "${OLD_MASTER_CERT_PATH}"
OLD_MASTER_KEY_PATH="${pki_dir}/oldapiserver.key"
echo "${OLD_MASTER_KEY}" | base64 --decode > "${OLD_MASTER_KEY_PATH}"
fi
SERVICEACCOUNT_CERT_PATH="${pki_dir}/serviceaccount.crt"
write-pki-data "${SERVICEACCOUNT_CERT}" "${SERVICEACCOUNT_CERT_PATH}"
SERVICEACCOUNT_KEY_PATH="${pki_dir}/serviceaccount.key"
write-pki-data "${SERVICEACCOUNT_KEY}" "${SERVICEACCOUNT_KEY_PATH}"
if [[ -n "${REQUESTHEADER_CA_CERT:-}" ]]; then
REQUESTHEADER_CA_CERT_PATH="${pki_dir}/aggr_ca.crt"
write-pki-data "${REQUESTHEADER_CA_CERT}" "${REQUESTHEADER_CA_CERT_PATH}"
PROXY_CLIENT_KEY_PATH="${pki_dir}/proxy_client.key"
write-pki-data "${PROXY_CLIENT_KEY}" "${PROXY_CLIENT_KEY_PATH}"
PROXY_CLIENT_CERT_PATH="${pki_dir}/proxy_client.crt"
write-pki-data "${PROXY_CLIENT_CERT}" "${PROXY_CLIENT_CERT_PATH}"
fi
}
# After the first boot and on upgrade, these files exist on the master-pd
# and should never be touched again (except perhaps an additional service
# account, see NB below.) One exception is if METADATA_CLOBBERS_CONFIG is
# enabled. In that case the basic_auth.csv file will be rewritten to make
# sure it matches the metadata source of truth.
function create-master-auth {
echo "Creating master auth files"
local -r auth_dir="/etc/srv/kubernetes"
local -r basic_auth_csv="${auth_dir}/basic_auth.csv"
if [[ -n "${KUBE_PASSWORD:-}" && -n "${KUBE_USER:-}" ]]; then
if [[ -e "${basic_auth_csv}" && "${METADATA_CLOBBERS_CONFIG:-false}" == "true" ]]; then
# If METADATA_CLOBBERS_CONFIG is true, we want to rewrite the file
# completely, because if we're changing KUBE_USER and KUBE_PASSWORD, we
# have nothing to match on. The file is replaced just below with
# append_or_replace_prefixed_line.
rm "${basic_auth_csv}"
fi
append_or_replace_prefixed_line "${basic_auth_csv}" "${KUBE_PASSWORD},${KUBE_USER}," "admin,system:masters"
fi
local -r known_tokens_csv="${auth_dir}/known_tokens.csv"
if [[ -e "${known_tokens_csv}" && "${METADATA_CLOBBERS_CONFIG:-false}" == "true" ]]; then
rm "${known_tokens_csv}"
fi
if [[ -n "${KUBE_BEARER_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_BEARER_TOKEN}," "admin,admin,system:masters"
fi
if [[ -n "${KUBE_BOOTSTRAP_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_BOOTSTRAP_TOKEN}," "gcp:kube-bootstrap,uid:gcp:kube-bootstrap,system:masters"
fi
if [[ -n "${KUBE_CONTROLLER_MANAGER_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_CONTROLLER_MANAGER_TOKEN}," "system:kube-controller-manager,uid:system:kube-controller-manager"
fi
if [[ -n "${KUBE_SCHEDULER_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_SCHEDULER_TOKEN}," "system:kube-scheduler,uid:system:kube-scheduler"
fi
if [[ -n "${KUBE_CLUSTER_AUTOSCALER_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_CLUSTER_AUTOSCALER_TOKEN}," "cluster-autoscaler,uid:cluster-autoscaler"
fi
if [[ -n "${KUBE_PROXY_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_PROXY_TOKEN}," "system:kube-proxy,uid:kube_proxy"
fi
if [[ -n "${NODE_PROBLEM_DETECTOR_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${NODE_PROBLEM_DETECTOR_TOKEN}," "system:node-problem-detector,uid:node-problem-detector"
fi
if [[ -n "${GCE_GLBC_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${GCE_GLBC_TOKEN}," "system:controller:glbc,uid:system:controller:glbc"
fi
if [[ -n "${ADDON_MANAGER_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${ADDON_MANAGER_TOKEN}," "system:addon-manager,uid:system:addon-manager,system:masters"
fi
if [[ -n "${KONNECTIVITY_SERVER_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${KONNECTIVITY_SERVER_TOKEN}," "system:konnectivity-server,uid:system:konnectivity-server"
create-kubeconfig "konnectivity-server" "${KONNECTIVITY_SERVER_TOKEN}"
fi
if [[ -n "${MONITORING_TOKEN:-}" ]]; then
append_or_replace_prefixed_line "${known_tokens_csv}" "${MONITORING_TOKEN}," "system:monitoring,uid:system:monitoring,system:monitoring"
fi
if [[ -n "${EXTRA_STATIC_AUTH_COMPONENTS:-}" ]]; then
# Create a static Bearer token and kubeconfig for extra, comma-separated components.
IFS="," read -r -a extra_components <<< "${EXTRA_STATIC_AUTH_COMPONENTS:-}"
for extra_component in "${extra_components[@]}"; do
local token
token="$(secure_random 32)"
append_or_replace_prefixed_line "${known_tokens_csv}" "${token}," "system:${extra_component},uid:system:${extra_component}"
create-kubeconfig "${extra_component}" "${token}"
done
fi
local use_cloud_config="false"
cat <<EOF >/etc/gce.conf
[global]
EOF
if [[ -n "${GCE_API_ENDPOINT:-}" ]]; then
cat <<EOF >>/etc/gce.conf
api-endpoint = ${GCE_API_ENDPOINT}
EOF
fi
if [[ -n "${TOKEN_URL:-}" && -n "${TOKEN_BODY:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
token-url = ${TOKEN_URL}
token-body = ${TOKEN_BODY}
EOF
fi
if [[ -n "${CONTAINER_API_ENDPOINT:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
container-api-endpoint = ${CONTAINER_API_ENDPOINT}
EOF
fi
if [[ -n "${PROJECT_ID:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
project-id = ${PROJECT_ID}
EOF
fi
if [[ -n "${NETWORK_PROJECT_ID:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
network-project-id = ${NETWORK_PROJECT_ID}
EOF
fi
if [[ -n "${NODE_NETWORK:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
network-name = ${NODE_NETWORK}
EOF
fi
if [[ -n "${NODE_SUBNETWORK:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
subnetwork-name = ${NODE_SUBNETWORK}
EOF
fi
if [[ -n "${NODE_INSTANCE_PREFIX:-}" ]]; then
use_cloud_config="true"
if [[ -n "${NODE_TAGS:-}" ]]; then
# split NODE_TAGS into an array by comma.
IFS=',' read -r -a node_tags <<< "${NODE_TAGS}"
else
local -r node_tags=("${NODE_INSTANCE_PREFIX}")
fi
cat <<EOF >>/etc/gce.conf
node-instance-prefix = ${NODE_INSTANCE_PREFIX}
EOF
for tag in "${node_tags[@]}"; do
cat <<EOF >>/etc/gce.conf
node-tags = ${tag}
EOF
done
fi
if [[ -n "${MULTIZONE:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
multizone = ${MULTIZONE}
EOF
fi
# Multimaster indicates that the cluster is HA.
# Currently the only HA clusters are regional.
# If we introduce zonal multimaster this will need to be revisited.
if [[ -n "${MULTIMASTER:-}" ]]; then
use_cloud_config="true"
cat <<EOF >>/etc/gce.conf
regional = ${MULTIMASTER}
EOF
fi
if [[ -n "${GCE_ALPHA_FEATURES:-}" ]]; then
use_cloud_config="true"
# split GCE_ALPHA_FEATURES into an array by comma.
IFS=',' read -r -a alpha_features <<< "${GCE_ALPHA_FEATURES}"
for feature in "${alpha_features[@]}"; do
cat <<EOF >>/etc/gce.conf
alpha-features = ${feature}
EOF
done
fi
if [[ -n "${SECONDARY_RANGE_NAME:-}" ]]; then
use_cloud_config="true"
cat <<EOF >> /etc/gce.conf
secondary-range-name = ${SECONDARY_RANGE_NAME}
EOF
fi
if [[ "${use_cloud_config}" != "true" ]]; then
rm -f /etc/gce.conf
fi
if [[ -n "${GCP_AUTHN_URL:-}" ]]; then
cat <<EOF >/etc/gcp_authn.config
clusters:
- name: gcp-authentication-server
cluster:
server: ${GCP_AUTHN_URL}
users:
- name: kube-apiserver
user:
auth-provider:
name: gcp
current-context: webhook
contexts:
- context:
cluster: gcp-authentication-server
user: kube-apiserver
name: webhook
EOF
fi
if [[ -n "${GCP_AUTHZ_URL:-}" ]]; then
cat <<EOF >/etc/gcp_authz.config
clusters:
- name: gcp-authorization-server
cluster:
server: ${GCP_AUTHZ_URL}
users:
- name: kube-apiserver
user:
auth-provider:
name: gcp
current-context: webhook
contexts:
- context:
cluster: gcp-authorization-server
user: kube-apiserver
name: webhook
EOF
fi
if [[ "${PREPARE_KONNECTIVITY_SERVICE:-false}" == "true" ]]; then
if [[ "${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}" == 'grpc' ]]; then
cat <<EOF >/etc/srv/kubernetes/egress_selector_configuration.yaml
apiVersion: apiserver.k8s.io/v1beta1
kind: EgressSelectorConfiguration
egressSelections:
- name: cluster
connection:
proxyProtocol: GRPC
transport:
uds:
udsName: /etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket
- name: master
connection:
proxyProtocol: Direct
- name: etcd
connection:
proxyProtocol: Direct
EOF
elif [[ "${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}" == 'http-connect' ]]; then
cat <<EOF >/etc/srv/kubernetes/egress_selector_configuration.yaml
apiVersion: apiserver.k8s.io/v1beta1
kind: EgressSelectorConfiguration
egressSelections:
- name: cluster
connection:
proxyProtocol: HTTPConnect
transport:
uds:
udsName: /etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket
- name: master
connection:
proxyProtocol: Direct
- name: etcd
connection:
proxyProtocol: Direct
EOF
else
echo "KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE must be set to either grpc or http-connect"
exit 1
fi
fi
if [[ -n "${WEBHOOK_GKE_EXEC_AUTH:-}" ]]; then
if [[ -z "${EXEC_AUTH_PLUGIN_URL:-}" ]]; then
1>&2 echo "You requested GKE exec auth support for webhooks, but EXEC_AUTH_PLUGIN_URL was not specified. This configuration depends on gke-exec-auth-plugin for authenticating to the webhook endpoint."
exit 1
fi
if [[ -z "${TOKEN_URL:-}" || -z "${TOKEN_BODY:-}" || -z "${TOKEN_BODY_UNQUOTED:-}" ]]; then
1>&2 echo "You requested GKE exec auth support for webhooks, but TOKEN_URL, TOKEN_BODY, and TOKEN_BODY_UNQUOTED were not provided. gke-exec-auth-plugin requires these values for its configuration."
exit 1
fi
# kubeconfig to be used by webhooks with GKE exec auth support. Note that
# the path to gke-exec-auth-plugin is the path when mounted inside the
# kube-apiserver pod.
cat <<EOF >/etc/srv/kubernetes/webhook.kubeconfig
apiVersion: v1
kind: Config
users:
- name: '*.googleapis.com'
user:
exec:
apiVersion: "client.authentication.k8s.io/v1alpha1"
command: /usr/bin/gke-exec-auth-plugin
args:
- --mode=alt-token
- --alt-token-url=${TOKEN_URL}
- --alt-token-body=${TOKEN_BODY_UNQUOTED}
EOF
fi
if [[ -n "${ADMISSION_CONTROL:-}" ]]; then
# Emit a basic admission control configuration file, with no plugins specified.
cat <<EOF >/etc/srv/kubernetes/admission_controller_config.yaml
apiVersion: apiserver.k8s.io/v1alpha1
kind: AdmissionConfiguration
plugins:
EOF
# Add resourcequota config to limit critical pods to kube-system by default
cat <<EOF >>/etc/srv/kubernetes/admission_controller_config.yaml
- name: "ResourceQuota"
configuration:
apiVersion: apiserver.config.k8s.io/v1
kind: ResourceQuotaConfiguration
limitedResources:
- resource: pods
matchScopes:
- scopeName: PriorityClass
operator: In
values: ["system-node-critical", "system-cluster-critical"]
EOF
if [[ "${ADMISSION_CONTROL:-}" == *"ImagePolicyWebhook"* ]]; then
if [[ -z "${GCP_IMAGE_VERIFICATION_URL:-}" ]]; then
1>&2 echo "The ImagePolicyWebhook admission control plugin was requested, but GCP_IMAGE_VERIFICATION_URL was not provided."
exit 1
fi
1>&2 echo "ImagePolicyWebhook admission control plugin requested. Configuring it to point at ${GCP_IMAGE_VERIFICATION_URL}"
# ImagePolicyWebhook does not use gke-exec-auth-plugin for authenticating
# to the webhook endpoint. Emit its special kubeconfig.
cat <<EOF >/etc/srv/kubernetes/gcp_image_review.kubeconfig
clusters:
- name: gcp-image-review-server
cluster:
server: ${GCP_IMAGE_VERIFICATION_URL}
users:
- name: kube-apiserver
user:
auth-provider:
name: gcp
current-context: webhook
contexts:
- context:
cluster: gcp-image-review-server
user: kube-apiserver
name: webhook
EOF
# Append config for ImagePolicyWebhook to the shared admission controller
# configuration file.
cat <<EOF >>/etc/srv/kubernetes/admission_controller_config.yaml
- name: ImagePolicyWebhook
configuration:
imagePolicy:
kubeConfigFile: /etc/srv/kubernetes/gcp_image_review.kubeconfig
allowTTL: 30
denyTTL: 30
retryBackoff: 500
defaultAllow: true
EOF
fi
# If GKE exec auth for webhooks has been requested, then
# ValidatingAdmissionWebhook should use it. Otherwise, run with the default
# config.
if [[ -n "${WEBHOOK_GKE_EXEC_AUTH:-}" ]]; then
1>&2 echo "ValidatingAdmissionWebhook requested, and WEBHOOK_GKE_EXEC_AUTH specified. Configuring ValidatingAdmissionWebhook to use gke-exec-auth-plugin."
# Append config for ValidatingAdmissionWebhook to the shared admission
# controller configuration file.
cat <<EOF >>/etc/srv/kubernetes/admission_controller_config.yaml
- name: ValidatingAdmissionWebhook
configuration:
apiVersion: apiserver.config.k8s.io/v1alpha1
kind: WebhookAdmission
kubeConfigFile: /etc/srv/kubernetes/webhook.kubeconfig
EOF
fi
fi
}
# Write the config for the audit policy.
function create-master-audit-policy {
local -r path="${1}"
local -r policy="${2:-}"
if [[ -n "${policy}" ]]; then
echo "${policy}" > "${path}"
return
fi
# Known api groups
local -r known_apis='
- group: "" # core
- group: "admissionregistration.k8s.io"
- group: "apiextensions.k8s.io"
- group: "apiregistration.k8s.io"
- group: "apps"
- group: "authentication.k8s.io"
- group: "authorization.k8s.io"
- group: "autoscaling"
- group: "batch"
- group: "certificates.k8s.io"
- group: "extensions"
- group: "metrics.k8s.io"
- group: "networking.k8s.io"
- group: "node.k8s.io"
- group: "policy"
- group: "rbac.authorization.k8s.io"
- group: "scheduling.k8s.io"
- group: "storage.k8s.io"'
cat <<EOF >"${path}"
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
# The following requests were manually identified as high-volume and low-risk,
# so drop them.
- level: None
users: ["system:kube-proxy"]
verbs: ["watch"]
resources:
- group: "" # core
resources: ["endpoints", "services", "services/status"]
- level: None
# Ingress controller reads 'configmaps/ingress-uid' through the unsecured port.
# TODO(#46983): Change this to the ingress controller service account.
users: ["system:unsecured"]
namespaces: ["kube-system"]
verbs: ["get"]
resources:
- group: "" # core
resources: ["configmaps"]
- level: None
users: ["kubelet"] # legacy kubelet identity
verbs: ["get"]
resources:
- group: "" # core
resources: ["nodes", "nodes/status"]
- level: None
userGroups: ["system:nodes"]
verbs: ["get"]
resources:
- group: "" # core
resources: ["nodes", "nodes/status"]
- level: None
users:
- system:kube-controller-manager
- system:kube-scheduler
- system:serviceaccount:kube-system:endpoint-controller
verbs: ["get", "update"]
namespaces: ["kube-system"]
resources:
- group: "" # core
resources: ["endpoints"]
- level: None
users: ["system:apiserver"]
verbs: ["get"]
resources:
- group: "" # core
resources: ["namespaces", "namespaces/status", "namespaces/finalize"]
- level: None
users: ["cluster-autoscaler"]
verbs: ["get", "update"]
namespaces: ["kube-system"]
resources:
- group: "" # core
resources: ["configmaps", "endpoints"]
# Don't log HPA fetching metrics.
- level: None
users:
- system:kube-controller-manager
verbs: ["get", "list"]
resources:
- group: "metrics.k8s.io"
# Don't log these read-only URLs.
- level: None
nonResourceURLs:
- /healthz*
- /version
- /swagger*
# Don't log events requests because of performance impact.
- level: None
resources:
- group: "" # core
resources: ["events"]
# node and pod status calls from nodes are high-volume and can be large, don't log responses for expected updates from nodes
- level: Request
users: ["kubelet", "system:node-problem-detector", "system:serviceaccount:kube-system:node-problem-detector"]
verbs: ["update","patch"]
resources:
- group: "" # core
resources: ["nodes/status", "pods/status"]
omitStages:
- "RequestReceived"
- level: Request
userGroups: ["system:nodes"]
verbs: ["update","patch"]
resources:
- group: "" # core
resources: ["nodes/status", "pods/status"]
omitStages:
- "RequestReceived"
# deletecollection calls can be large, don't log responses for expected namespace deletions
- level: Request
users: ["system:serviceaccount:kube-system:namespace-controller"]
verbs: ["deletecollection"]
omitStages:
- "RequestReceived"
# Secrets, ConfigMaps, and TokenReviews can contain sensitive & binary data,
# so only log at the Metadata level.
- level: Metadata
resources:
- group: "" # core
resources: ["secrets", "configmaps"]
- group: authentication.k8s.io
resources: ["tokenreviews"]
omitStages:
- "RequestReceived"
# Get repsonses can be large; skip them.
- level: Request
verbs: ["get", "list", "watch"]
resources: ${known_apis}
omitStages:
- "RequestReceived"
# Default level for known APIs
- level: RequestResponse
resources: ${known_apis}
omitStages:
- "RequestReceived"
# Default level for all other requests.
- level: Metadata
omitStages:
- "RequestReceived"
EOF
}
# Writes the configuration file used by the webhook advanced auditing backend.
function create-master-audit-webhook-config {
local -r path="${1}"
if [[ -n "${GCP_AUDIT_URL:-}" ]]; then
# The webhook config file is a kubeconfig file describing the webhook endpoint.
cat <<EOF >"${path}"
clusters:
- name: gcp-audit-server
cluster:
server: ${GCP_AUDIT_URL}
users:
- name: kube-apiserver
user:
auth-provider:
name: gcp
current-context: webhook
contexts:
- context:
cluster: gcp-audit-server
user: kube-apiserver
name: webhook
EOF
fi
}
function create-kubeconfig {
local component=$1
local token=$2
echo "Creating kubeconfig file for component ${component}"
mkdir -p "/etc/srv/kubernetes/${component}"
cat <<EOF >"/etc/srv/kubernetes/${component}/kubeconfig"
apiVersion: v1
kind: Config
users:
- name: ${component}
user:
token: ${token}
clusters:
- name: local
cluster:
insecure-skip-tls-verify: true
server: https://localhost:443
contexts:
- context:
cluster: local
user: ${component}
name: ${component}
current-context: ${component}
EOF
}
# Arg 1: the IP address of the API server
function create-kubelet-kubeconfig() {
local apiserver_address="${1}"
if [[ -z "${apiserver_address}" ]]; then
echo "Must provide API server address to create Kubelet kubeconfig file!"
exit 1
fi
if [[ "${CREATE_BOOTSTRAP_KUBECONFIG:-true}" == "true" ]]; then
echo "Creating kubelet bootstrap-kubeconfig file"
cat <<EOF >/var/lib/kubelet/bootstrap-kubeconfig
apiVersion: v1
kind: Config
users:
- name: kubelet
user:
client-certificate: ${KUBELET_CERT_PATH}
client-key: ${KUBELET_KEY_PATH}
clusters:
- name: local
cluster:
server: https://${apiserver_address}
certificate-authority: ${CA_CERT_BUNDLE_PATH}
contexts:
- context:
cluster: local
user: kubelet
name: service-account-context
current-context: service-account-context
EOF
elif [[ "${FETCH_BOOTSTRAP_KUBECONFIG:-false}" == "true" ]]; then
echo "Fetching kubelet bootstrap-kubeconfig file from metadata"
get-metadata-value "instance/attributes/bootstrap-kubeconfig" >/var/lib/kubelet/bootstrap-kubeconfig
else
echo "Fetching kubelet kubeconfig file from metadata"
get-metadata-value "instance/attributes/kubeconfig" >/var/lib/kubelet/kubeconfig
fi
}
# Uses KUBELET_CA_CERT (falling back to CA_CERT), KUBELET_CERT, and KUBELET_KEY
# to generate a kubeconfig file for the kubelet to securely connect to the apiserver.
# Set REGISTER_MASTER_KUBELET to true if kubelet on the master node
# should register to the apiserver.
function create-master-kubelet-auth {
# Only configure the kubelet on the master if the required variables are
# set in the environment.
if [[ -n "${KUBELET_APISERVER:-}" && -n "${KUBELET_CERT:-}" && -n "${KUBELET_KEY:-}" ]]; then
REGISTER_MASTER_KUBELET="true"
create-kubelet-kubeconfig "${KUBELET_APISERVER}"
fi
}
function create-kubeproxy-user-kubeconfig {
echo "Creating kube-proxy user kubeconfig file"
cat <<EOF >/var/lib/kube-proxy/kubeconfig
apiVersion: v1
kind: Config
users:
- name: kube-proxy
user:
token: ${KUBE_PROXY_TOKEN}
clusters:
- name: local
cluster:
certificate-authority-data: ${CA_CERT_BUNDLE}
contexts:
- context:
cluster: local
user: kube-proxy
name: service-account-context
current-context: service-account-context
EOF
}
function create-kube-scheduler-config {
echo "Creating kube-scheduler config file"
mkdir -p /etc/srv/kubernetes/kube-scheduler
cat <<EOF >/etc/srv/kubernetes/kube-scheduler/config
${KUBE_SCHEDULER_CONFIG}
EOF
}
# TODO(#92143): Remove legacy policy config creation once kube-scheduler config is GA.
function create-kubescheduler-policy-config {
echo "Creating kube-scheduler policy config file"
mkdir -p /etc/srv/kubernetes/kube-scheduler
cat <<EOF >/etc/srv/kubernetes/kube-scheduler/policy-config
${SCHEDULER_POLICY_CONFIG}
EOF
}
function create-node-problem-detector-kubeconfig {
local apiserver_address="${1}"
if [[ -z "${apiserver_address}" ]]; then
echo "Must provide API server address to create node-problem-detector kubeconfig file!"
exit 1
fi
echo "Creating node-problem-detector kubeconfig file"
mkdir -p /var/lib/node-problem-detector
cat <<EOF >/var/lib/node-problem-detector/kubeconfig
apiVersion: v1
kind: Config
users:
- name: node-problem-detector
user:
token: ${NODE_PROBLEM_DETECTOR_TOKEN}
clusters:
- name: local
cluster:
server: https://${apiserver_address}
certificate-authority-data: ${CA_CERT}
contexts:
- context:
cluster: local
user: node-problem-detector
name: service-account-context
current-context: service-account-context
EOF
}
function create-node-problem-detector-kubeconfig-from-kubelet {
echo "Creating node-problem-detector kubeconfig from /var/lib/kubelet/kubeconfig"
mkdir -p /var/lib/node-problem-detector
cp /var/lib/kubelet/kubeconfig /var/lib/node-problem-detector/kubeconfig
}
function create-master-etcd-auth {
if [[ -n "${ETCD_CA_CERT:-}" && -n "${ETCD_PEER_KEY:-}" && -n "${ETCD_PEER_CERT:-}" ]]; then
local -r auth_dir="/etc/srv/kubernetes"
echo "${ETCD_CA_CERT}" | base64 --decode | gunzip > "${auth_dir}/etcd-ca.crt"
echo "${ETCD_PEER_KEY}" | base64 --decode > "${auth_dir}/etcd-peer.key"
echo "${ETCD_PEER_CERT}" | base64 --decode | gunzip > "${auth_dir}/etcd-peer.crt"
fi
}
function create-master-etcd-apiserver-auth {
if [[ -n "${ETCD_APISERVER_CA_CERT:-}" && -n "${ETCD_APISERVER_SERVER_KEY:-}" && -n "${ETCD_APISERVER_SERVER_CERT:-}" && -n "${ETCD_APISERVER_CLIENT_KEY:-}" && -n "${ETCD_APISERVER_CLIENT_CERT:-}" ]]; then
local -r auth_dir="/etc/srv/kubernetes/pki"
ETCD_APISERVER_CA_KEY_PATH="${auth_dir}/etcd-apiserver-ca.key"
echo "${ETCD_APISERVER_CA_KEY}" | base64 --decode > "${ETCD_APISERVER_CA_KEY_PATH}"
# Keep in sync with add-replica-to-etcd/remove-replica-from-etcd in util.sh.
ETCD_APISERVER_CA_CERT_PATH="${auth_dir}/etcd-apiserver-ca.crt"
echo "${ETCD_APISERVER_CA_CERT}" | base64 --decode | gunzip > "${ETCD_APISERVER_CA_CERT_PATH}"
ETCD_APISERVER_SERVER_KEY_PATH="${auth_dir}/etcd-apiserver-server.key"
echo "${ETCD_APISERVER_SERVER_KEY}" | base64 --decode > "${ETCD_APISERVER_SERVER_KEY_PATH}"
ETCD_APISERVER_SERVER_CERT_PATH="${auth_dir}/etcd-apiserver-server.crt"
echo "${ETCD_APISERVER_SERVER_CERT}" | base64 --decode | gunzip > "${ETCD_APISERVER_SERVER_CERT_PATH}"
# Keep in sync with add-replica-to-etcd/remove-replica-from-etcd in util.sh.
ETCD_APISERVER_CLIENT_KEY_PATH="${auth_dir}/etcd-apiserver-client.key"
echo "${ETCD_APISERVER_CLIENT_KEY}" | base64 --decode > "${ETCD_APISERVER_CLIENT_KEY_PATH}"
# Keep in sync with add-replica-to-etcd/remove-replica-from-etcd in util.sh.
ETCD_APISERVER_CLIENT_CERT_PATH="${auth_dir}/etcd-apiserver-client.crt"
echo "${ETCD_APISERVER_CLIENT_CERT}" | base64 --decode | gunzip > "${ETCD_APISERVER_CLIENT_CERT_PATH}"
fi
}
function docker-installed {
if systemctl cat docker.service &> /dev/null ; then
return 0
else
return 1
fi
}
function assemble-docker-flags {
echo "Assemble docker command line flags"
local docker_opts="-p /var/run/docker.pid --iptables=false --ip-masq=false"
if [[ "${TEST_CLUSTER:-}" == "true" ]]; then
docker_opts+=" --log-level=debug"
else
docker_opts+=" --log-level=warn"
fi
if [[ "${NETWORK_PROVIDER:-}" == "kubenet" || "${NETWORK_PROVIDER:-}" == "cni" ]]; then
# set docker0 cidr to private ip address range to avoid conflict with cbr0 cidr range
docker_opts+=" --bip=169.254.123.1/24"
else
docker_opts+=" --bridge=cbr0"
fi
# Decide whether to enable a docker registry mirror. This is taken from
# the "kube-env" metadata value.
if [[ -n "${DOCKER_REGISTRY_MIRROR_URL:-}" ]]; then
echo "Enable docker registry mirror at: ${DOCKER_REGISTRY_MIRROR_URL}"
docker_opts+=" --registry-mirror=${DOCKER_REGISTRY_MIRROR_URL}"
fi
# Configure docker logging
docker_opts+=" --log-driver=${DOCKER_LOG_DRIVER:-json-file}"
docker_opts+=" --log-opt=max-size=${DOCKER_LOG_MAX_SIZE:-10m}"
docker_opts+=" --log-opt=max-file=${DOCKER_LOG_MAX_FILE:-5}"
# Disable live-restore if the environment variable is set.
if [[ "${DISABLE_DOCKER_LIVE_RESTORE:-false}" == "true" ]]; then
docker_opts+=" --live-restore=false"
fi
echo "DOCKER_OPTS=\"${docker_opts} ${EXTRA_DOCKER_OPTS:-}\"" > /etc/default/docker
# Ensure TasksMax is sufficient for docker.
# (https://github.com/kubernetes/kubernetes/issues/51977)
echo "Extend the docker.service configuration to set a higher pids limit"
mkdir -p /etc/systemd/system/docker.service.d
cat <<EOF >/etc/systemd/system/docker.service.d/01tasksmax.conf
[Service]
TasksMax=infinity
EOF
systemctl daemon-reload
echo "Docker command line is updated. Restart docker to pick it up"
systemctl restart docker
}
# This function assembles the kubelet systemd service file and starts it
# using systemctl.
function start-kubelet {
echo "Start kubelet"
local kubelet_bin="${KUBE_HOME}/bin/kubelet"
local -r version="$("${kubelet_bin}" --version=true | cut -f2 -d " ")"
local -r builtin_kubelet="/usr/bin/kubelet"
if [[ "${TEST_CLUSTER:-}" == "true" ]]; then
# Determine which binary to use on test clusters. We use the built-in
# version only if the downloaded version is the same as the built-in
# version. This allows GCI to run some of the e2e tests to qualify the
# built-in kubelet.
if [[ -x "${builtin_kubelet}" ]]; then
local -r builtin_version="$("${builtin_kubelet}" --version=true | cut -f2 -d " ")"
if [[ "${builtin_version}" == "${version}" ]]; then
kubelet_bin="${builtin_kubelet}"
fi
fi
fi
echo "Using kubelet binary at ${kubelet_bin}"
local -r kubelet_env_file="/etc/default/kubelet"
local kubelet_opts="${KUBELET_ARGS} ${KUBELET_CONFIG_FILE_ARG:-}"
echo "KUBELET_OPTS=\"${kubelet_opts}\"" > "${kubelet_env_file}"
echo "KUBE_COVERAGE_FILE=\"/var/log/kubelet.cov\"" >> "${kubelet_env_file}"
# Write the systemd service file for kubelet.
cat <<EOF >/etc/systemd/system/kubelet.service
[Unit]
Description=Kubernetes kubelet
Requires=network-online.target
After=network-online.target
[Service]
Restart=always
RestartSec=10
EnvironmentFile=${kubelet_env_file}
ExecStart=${kubelet_bin} \$KUBELET_OPTS
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start kubelet.service
}
# This function assembles the node problem detector systemd service file and
# starts it using systemctl.
function start-node-problem-detector {
echo "Start node problem detector"
local -r npd_bin="${KUBE_HOME}/bin/node-problem-detector"
echo "Using node problem detector binary at ${npd_bin}"
local flags="${NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}"
if [[ -z "${flags}" ]]; then
local -r km_config="${KUBE_HOME}/node-problem-detector/config/kernel-monitor.json"
# TODO(random-liu): Handle this for alternative container runtime.
local -r dm_config="${KUBE_HOME}/node-problem-detector/config/docker-monitor.json"
local -r sm_config="${KUBE_HOME}/node-problem-detector/config/systemd-monitor.json"
local -r ssm_config="${KUBE_HOME}/node-problem-detector/config/system-stats-monitor.json"
local -r custom_km_config="${KUBE_HOME}/node-problem-detector/config/kernel-monitor-counter.json"
local -r custom_sm_config="${KUBE_HOME}/node-problem-detector/config/systemd-monitor-counter.json"
flags="${NPD_TEST_LOG_LEVEL:-"--v=2"} ${NPD_TEST_ARGS:-}"
flags+=" --logtostderr"
flags+=" --config.system-log-monitor=${km_config},${dm_config},${sm_config}"
flags+=" --config.system-stats-monitor=${ssm_config}"
flags+=" --config.custom-plugin-monitor=${custom_km_config},${custom_sm_config}"
local -r npd_port=${NODE_PROBLEM_DETECTOR_PORT:-20256}
flags+=" --port=${npd_port}"
if [[ -n "${EXTRA_NPD_ARGS:-}" ]]; then
flags+=" ${EXTRA_NPD_ARGS}"
fi
fi
flags+=" --apiserver-override=https://${KUBERNETES_MASTER_NAME}?inClusterConfig=false&auth=/var/lib/node-problem-detector/kubeconfig"
# Write the systemd service file for node problem detector.
cat <<EOF >/etc/systemd/system/node-problem-detector.service
[Unit]
Description=Kubernetes node problem detector
Requires=network-online.target
After=network-online.target
[Service]
Restart=always
RestartSec=10
ExecStart=${npd_bin} ${flags}
[Install]
WantedBy=multi-user.target
EOF
systemctl start node-problem-detector.service
}
# Create the log file and set its properties.
#
# $1 is the file to create.
# $2: the log owner uid to set for the log file.
# $3: the log owner gid to set for the log file. If $KUBE_POD_LOG_READERS_GROUP
# is set then this value will not be used.
function prepare-log-file {
touch "$1"
if [[ -n "${KUBE_POD_LOG_READERS_GROUP:-}" ]]; then
chmod 640 "$1"
chown "${2:-root}":"${KUBE_POD_LOG_READERS_GROUP}" "$1"
else
chmod 644 "$1"
chown "${2:-${LOG_OWNER_USER:-root}}":"${3:-${LOG_OWNER_GROUP:-root}}" "$1"
fi
}
# Prepares parameters for kube-proxy manifest.
# $1 source path of kube-proxy manifest.
function prepare-kube-proxy-manifest-variables {
local -r src_file=$1;
local -r kubeconfig="--kubeconfig=/var/lib/kube-proxy/kubeconfig"
local kube_docker_registry="k8s.gcr.io"
if [[ -n "${KUBE_DOCKER_REGISTRY:-}" ]]; then
kube_docker_registry=${KUBE_DOCKER_REGISTRY}
fi
local -r kube_proxy_docker_tag=$(cat /home/kubernetes/kube-docker-files/kube-proxy.docker_tag)
local api_servers="--master=https://${KUBERNETES_MASTER_NAME}"
local params="${KUBEPROXY_TEST_LOG_LEVEL:-"--v=2"}"
if [[ -n "${FEATURE_GATES:-}" ]]; then
params+=" --feature-gates=${FEATURE_GATES}"
fi
if [[ "${KUBE_PROXY_MODE:-}" == "ipvs" ]];then
# use 'nf_conntrack' instead of 'nf_conntrack_ipv4' for linux kernel >= 4.19
# https://github.com/kubernetes/kubernetes/pull/70398
local -r kernel_version=$(uname -r | cut -d\. -f1,2)
local conntrack_module="nf_conntrack"
if [[ $(printf '%s\n4.18\n' "${kernel_version}" | sort -V | tail -1) == "4.18" ]]; then
conntrack_module="nf_conntrack_ipv4"
fi
if sudo modprobe -a ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh ${conntrack_module}; then
params+=" --proxy-mode=ipvs"
else
# If IPVS modules are not present, make sure the node does not come up as
# healthy.
exit 1
fi
fi
params+=" --iptables-sync-period=1m --iptables-min-sync-period=10s --ipvs-sync-period=1m --ipvs-min-sync-period=10s"
if [[ -n "${KUBEPROXY_TEST_ARGS:-}" ]]; then
params+=" ${KUBEPROXY_TEST_ARGS}"
fi
if [[ -n "${DETECT_LOCAL_MODE:-}" ]]; then
params+=" --detect-local-mode=${DETECT_LOCAL_MODE}"
fi
local container_env=""
local kube_cache_mutation_detector_env_name=""
local kube_cache_mutation_detector_env_value=""
if [[ -n "${ENABLE_CACHE_MUTATION_DETECTOR:-}" ]]; then
container_env="env:"
kube_cache_mutation_detector_env_name="- name: KUBE_CACHE_MUTATION_DETECTOR"
kube_cache_mutation_detector_env_value="value: \"${ENABLE_CACHE_MUTATION_DETECTOR}\""
fi
sed -i -e "s@{{kubeconfig}}@${kubeconfig}@g" "${src_file}"
sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${kube_docker_registry}@g" "${src_file}"
sed -i -e "s@{{pillar\['kube-proxy_docker_tag'\]}}@${kube_proxy_docker_tag}@g" "${src_file}"
sed -i -e "s@{{params}}@${params}@g" "${src_file}"
sed -i -e "s@{{container_env}}@${container_env}@g" "${src_file}"
sed -i -e "s@{{kube_cache_mutation_detector_env_name}}@${kube_cache_mutation_detector_env_name}@g" "${src_file}"
sed -i -e "s@{{kube_cache_mutation_detector_env_value}}@${kube_cache_mutation_detector_env_value}@g" "${src_file}"
sed -i -e "s@{{ cpurequest }}@100m@g" "${src_file}"
sed -i -e "s@{{api_servers_with_port}}@${api_servers}@g" "${src_file}"
sed -i -e "s@{{kubernetes_service_host_env_value}}@${KUBERNETES_MASTER_NAME}@g" "${src_file}"
if [[ -n "${CLUSTER_IP_RANGE:-}" ]]; then
sed -i -e "s@{{cluster_cidr}}@--cluster-cidr=${CLUSTER_IP_RANGE}@g" "${src_file}"
fi
}
# Starts kube-proxy static pod.
function start-kube-proxy {
echo "Start kube-proxy static pod"
prepare-log-file /var/log/kube-proxy.log
local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-proxy.manifest"
prepare-kube-proxy-manifest-variables "${src_file}"
cp "${src_file}" /etc/kubernetes/manifests
}
# Replaces the variables in the etcd manifest file with the real values, and then
# copy the file to the manifest dir
# $1: value for variable 'suffix'
# $2: value for variable 'port'
# $3: value for variable 'server_port'
# $4: value for variable 'cpulimit'
# $5: pod name, which should be either etcd or etcd-events
function prepare-etcd-manifest {
local host_name=${ETCD_HOSTNAME:-$(hostname -s)}
local -r host_ip=$(${PYTHON} -c "import socket;print(socket.gethostbyname(\"${host_name}\"))")
local etcd_cluster=""
local cluster_state="new"
local etcd_protocol="http"
local etcd_apiserver_protocol="http"
local etcd_creds=""
local etcd_apiserver_creds="${ETCD_APISERVER_CREDS:-}"
local etcd_extra_args="${ETCD_EXTRA_ARGS:-}"
local suffix="$1"
local etcd_listen_metrics_port="$2"
local etcdctl_certs=""
if [[ -n "${INITIAL_ETCD_CLUSTER_STATE:-}" ]]; then
cluster_state="${INITIAL_ETCD_CLUSTER_STATE}"
fi
if [[ -n "${ETCD_CA_CERT:-}" && -n "${ETCD_PEER_KEY:-}" && -n "${ETCD_PEER_CERT:-}" ]]; then
etcd_creds=" --peer-trusted-ca-file /etc/srv/kubernetes/etcd-ca.crt --peer-cert-file /etc/srv/kubernetes/etcd-peer.crt --peer-key-file /etc/srv/kubernetes/etcd-peer.key -peer-client-cert-auth "
etcd_protocol="https"
fi
# mTLS should only be enabled for etcd server but not etcd-events. if $1 suffix is empty, it's etcd server.
if [[ -z "${suffix}" && -n "${ETCD_APISERVER_CA_KEY:-}" && -n "${ETCD_APISERVER_CA_CERT:-}" && -n "${ETCD_APISERVER_SERVER_KEY:-}" && -n "${ETCD_APISERVER_SERVER_CERT:-}" && -n "${ETCD_APISERVER_CLIENT_KEY:-}" && -n "${ETCD_APISERVER_CLIENT_CERT:-}" ]]; then
etcd_apiserver_creds=" --client-cert-auth --trusted-ca-file ${ETCD_APISERVER_CA_CERT_PATH} --cert-file ${ETCD_APISERVER_SERVER_CERT_PATH} --key-file ${ETCD_APISERVER_SERVER_KEY_PATH} "
etcdctl_certs="--cacert ${ETCD_APISERVER_CA_CERT_PATH} --cert ${ETCD_APISERVER_CLIENT_CERT_PATH} --key ${ETCD_APISERVER_CLIENT_KEY_PATH}"
etcd_apiserver_protocol="https"
etcd_listen_metrics_port="2382"
etcd_extra_args+=" --listen-metrics-urls=http://${ETCD_LISTEN_CLIENT_IP:-127.0.0.1}:${etcd_listen_metrics_port} "
fi
if [[ -n "${ETCD_PROGRESS_NOTIFY_INTERVAL:-}" ]]; then
etcd_extra_args+=" --experimental-watch-progress-notify-interval=${ETCD_PROGRESS_NOTIFY_INTERVAL}"
fi
for host in $(echo "${INITIAL_ETCD_CLUSTER:-${host_name}}" | tr "," "\n"); do
etcd_host="etcd-${host}=${etcd_protocol}://${host}:$3"
if [[ -n "${etcd_cluster}" ]]; then
etcd_cluster+=","
fi
etcd_cluster+="${etcd_host}"
done
local -r temp_file="/tmp/$5"
cp "${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/etcd.manifest" "${temp_file}"
sed -i -e "s@{{ *suffix *}}@$1@g" "${temp_file}"
sed -i -e "s@{{ *port *}}@$2@g" "${temp_file}"
sed -i -e "s@{{ *server_port *}}@$3@g" "${temp_file}"
sed -i -e "s@{{ *cpulimit *}}@\"$4\"@g" "${temp_file}"
sed -i -e "s@{{ *hostname *}}@$host_name@g" "${temp_file}"
sed -i -e "s@{{ *host_ip *}}@$host_ip@g" "${temp_file}"
sed -i -e "s@{{ *etcd_cluster *}}@$etcd_cluster@g" "${temp_file}"
sed -i -e "s@{{ *liveness_probe_initial_delay *}}@${ETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC:-15}@g" "${temp_file}"
sed -i -e "s@{{ *listen_client_ip *}}@${ETCD_LISTEN_CLIENT_IP:-127.0.0.1}@g" "${temp_file}"
# Get default storage backend from manifest file.
local -r default_storage_backend=$( \
grep -o "{{ *pillar\.get('storage_backend', '\(.*\)') *}}" "${temp_file}" | \
sed -e "s@{{ *pillar\.get('storage_backend', '\(.*\)') *}}@\1@g")
if [[ -n "${STORAGE_BACKEND:-}" ]]; then
sed -i -e "s@{{ *pillar\.get('storage_backend', '\(.*\)') *}}@${STORAGE_BACKEND}@g" "${temp_file}"
else
sed -i -e "s@{{ *pillar\.get('storage_backend', '\(.*\)') *}}@\1@g" "${temp_file}"
fi
if [[ "${STORAGE_BACKEND:-${default_storage_backend}}" == "etcd3" ]]; then
sed -i -e "s@{{ *quota_bytes *}}@--quota-backend-bytes=${ETCD_QUOTA_BACKEND_BYTES:-4294967296}@g" "${temp_file}"
else
sed -i -e "s@{{ *quota_bytes *}}@@g" "${temp_file}"
fi
sed -i -e "s@{{ *cluster_state *}}@$cluster_state@g" "${temp_file}"
if [[ -n "${ETCD_IMAGE:-}" ]]; then
sed -i -e "s@{{ *pillar\.get('etcd_docker_tag', '\(.*\)') *}}@${ETCD_IMAGE}@g" "${temp_file}"
else
sed -i -e "s@{{ *pillar\.get('etcd_docker_tag', '\(.*\)') *}}@\1@g" "${temp_file}"
fi
if [[ -n "${ETCD_DOCKER_REPOSITORY:-}" ]]; then
sed -i -e "s@{{ *pillar\.get('etcd_docker_repository', '\(.*\)') *}}@${ETCD_DOCKER_REPOSITORY}@g" "${temp_file}"
else
sed -i -e "s@{{ *pillar\.get('etcd_docker_repository', '\(.*\)') *}}@\1@g" "${temp_file}"
fi
sed -i -e "s@{{ *etcd_protocol *}}@$etcd_protocol@g" "${temp_file}"
sed -i -e "s@{{ *etcd_apiserver_protocol *}}@$etcd_apiserver_protocol@g" "${temp_file}"
sed -i -e "s@{{ *etcd_creds *}}@$etcd_creds@g" "${temp_file}"
sed -i -e "s@{{ *etcdctl_certs *}}@$etcdctl_certs@g" "${temp_file}"
sed -i -e "s@{{ *etcd_apiserver_creds *}}@$etcd_apiserver_creds@g" "${temp_file}"
sed -i -e "s@{{ *etcd_extra_args *}}@$etcd_extra_args@g" "${temp_file}"
if [[ -n "${ETCD_VERSION:-}" ]]; then
sed -i -e "s@{{ *pillar\.get('etcd_version', '\(.*\)') *}}@${ETCD_VERSION}@g" "${temp_file}"
else
sed -i -e "s@{{ *pillar\.get('etcd_version', '\(.*\)') *}}@\1@g" "${temp_file}"
fi
# Replace the volume host path.
sed -i -e "s@/mnt/master-pd/var/etcd@/mnt/disks/master-pd/var/etcd@g" "${temp_file}"
mv "${temp_file}" /etc/kubernetes/manifests
}
# Starts etcd server pod (and etcd-events pod if needed).
# More specifically, it prepares dirs and files, sets the variable value
# in the manifests, and copies them to /etc/kubernetes/manifests.
function start-etcd-servers {
echo "Start etcd pods"
if [[ -d /etc/etcd ]]; then
rm -rf /etc/etcd
fi
if [[ -e /etc/default/etcd ]]; then
rm -f /etc/default/etcd
fi
if [[ -e /etc/systemd/system/etcd.service ]]; then
rm -f /etc/systemd/system/etcd.service
fi
if [[ -e /etc/init.d/etcd ]]; then
rm -f /etc/init.d/etcd
fi
prepare-log-file /var/log/etcd.log
prepare-etcd-manifest "" "2379" "2380" "200m" "etcd.manifest"
prepare-log-file /var/log/etcd-events.log
prepare-etcd-manifest "-events" "4002" "2381" "100m" "etcd-events.manifest"
}
# Replaces the variables in the konnectivity-server manifest file with the real values, and then
# copy the file to the manifest dir
# $1: value for variable "agent_port"
# $2: value for variable "health_port"
# $3: value for variable "admin_port"
function prepare-konnectivity-server-manifest {
local -r temp_file="/tmp/konnectivity-server.yaml"
params=()
cp "${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/konnectivity-server.yaml" "${temp_file}"
params+=("--log-file=/var/log/konnectivity-server.log")
params+=("--logtostderr=false")
params+=("--log-file-max-size=0")
params+=("--uds-name=/etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket")
params+=("--cluster-cert=/etc/srv/kubernetes/pki/apiserver.crt")
params+=("--cluster-key=/etc/srv/kubernetes/pki/apiserver.key")
if [[ "${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}" == 'grpc' ]]; then
params+=("--mode=grpc")
elif [[ "${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}" == 'http-connect' ]]; then
params+=("--mode=http-connect")
else
echo "KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE must be set to either grpc or http-connect"
exit 1
fi
params+=("--server-port=0")
params+=("--agent-port=$1")
params+=("--health-port=$2")
params+=("--admin-port=$3")
params+=("--agent-namespace=kube-system")
params+=("--agent-service-account=konnectivity-agent")
params+=("--kubeconfig=/etc/srv/kubernetes/konnectivity-server/kubeconfig")
params+=("--authentication-audience=system:konnectivity-server")
konnectivity_args=""
for param in "${params[@]}"; do
konnectivity_args+=", \"${param}\""
done
sed -i -e "s@{{ *konnectivity_args *}}@${konnectivity_args}@g" "${temp_file}"
sed -i -e "s@{{ *agent_port *}}@$1@g" "${temp_file}"
sed -i -e "s@{{ *health_port *}}@$2@g" "${temp_file}"
sed -i -e "s@{{ *admin_port *}}@$3@g" "${temp_file}"
sed -i -e "s@{{ *liveness_probe_initial_delay *}}@30@g" "${temp_file}"
mv "${temp_file}" /etc/kubernetes/manifests
}
# Starts konnectivity server pod.
# More specifically, it prepares dirs and files, sets the variable value
# in the manifests, and copies them to /etc/kubernetes/manifests.
function start-konnectivity-server {
echo "Start konnectivity server pods"
prepare-log-file /var/log/konnectivity-server.log
prepare-konnectivity-server-manifest "8132" "8133" "8134"
}
# Calculates the following variables based on env variables, which will be used
# by the manifests of several kube-master components.
# CLOUD_CONFIG_OPT
# CLOUD_CONFIG_VOLUME
# CLOUD_CONFIG_MOUNT
# DOCKER_REGISTRY
# FLEXVOLUME_HOSTPATH_MOUNT
# FLEXVOLUME_HOSTPATH_VOLUME
# INSECURE_PORT_MAPPING
function compute-master-manifest-variables {
CLOUD_CONFIG_OPT=""
CLOUD_CONFIG_VOLUME=""
CLOUD_CONFIG_MOUNT=""
if [[ -f /etc/gce.conf ]]; then
CLOUD_CONFIG_OPT="--cloud-config=/etc/gce.conf"
CLOUD_CONFIG_VOLUME="{\"name\": \"cloudconfigmount\",\"hostPath\": {\"path\": \"/etc/gce.conf\", \"type\": \"FileOrCreate\"}},"
CLOUD_CONFIG_MOUNT="{\"name\": \"cloudconfigmount\",\"mountPath\": \"/etc/gce.conf\", \"readOnly\": true},"
fi
DOCKER_REGISTRY="k8s.gcr.io"
if [[ -n "${KUBE_DOCKER_REGISTRY:-}" ]]; then
DOCKER_REGISTRY="${KUBE_DOCKER_REGISTRY}"
fi
FLEXVOLUME_HOSTPATH_MOUNT=""
FLEXVOLUME_HOSTPATH_VOLUME=""
if [[ -n "${VOLUME_PLUGIN_DIR:-}" ]]; then
FLEXVOLUME_HOSTPATH_MOUNT="{ \"name\": \"flexvolumedir\", \"mountPath\": \"${VOLUME_PLUGIN_DIR}\", \"readOnly\": true},"
FLEXVOLUME_HOSTPATH_VOLUME="{ \"name\": \"flexvolumedir\", \"hostPath\": {\"path\": \"${VOLUME_PLUGIN_DIR}\"}},"
fi
INSECURE_PORT_MAPPING=""
if [[ "${ENABLE_APISERVER_INSECURE_PORT:-false}" == "true" ]]; then
# INSECURE_PORT_MAPPING is used by sed
# shellcheck disable=SC2089
INSECURE_PORT_MAPPING='{ "name": "local", "containerPort": 8080, "hostPort": 8080},'
fi
# shellcheck disable=SC2090
export INSECURE_PORT_MAPPING
}
# A helper function that bind mounts kubelet dirs for running mount in a chroot
function prepare-mounter-rootfs {
echo "Prepare containerized mounter"
mount --bind "${CONTAINERIZED_MOUNTER_HOME}" "${CONTAINERIZED_MOUNTER_HOME}"
mount -o remount,exec "${CONTAINERIZED_MOUNTER_HOME}"
CONTAINERIZED_MOUNTER_ROOTFS="${CONTAINERIZED_MOUNTER_HOME}/rootfs"
mount --rbind /var/lib/kubelet/ "${CONTAINERIZED_MOUNTER_ROOTFS}/var/lib/kubelet"
mount --make-rshared "${CONTAINERIZED_MOUNTER_ROOTFS}/var/lib/kubelet"
mount --bind -o ro /proc "${CONTAINERIZED_MOUNTER_ROOTFS}/proc"
mount --bind -o ro /dev "${CONTAINERIZED_MOUNTER_ROOTFS}/dev"
cp /etc/resolv.conf "${CONTAINERIZED_MOUNTER_ROOTFS}/etc/"
}
# Updates node labels used by addons.
function update-legacy-addon-node-labels() {
# need kube-apiserver to be ready
until kubectl get nodes; do
sleep 5
done
update-node-label "beta.kubernetes.io/metadata-proxy-ready=true,cloud.google.com/metadata-proxy-ready!=true" "cloud.google.com/metadata-proxy-ready=true"
update-node-label "beta.kubernetes.io/kube-proxy-ds-ready=true,node.kubernetes.io/kube-proxy-ds-ready!=true" "node.kubernetes.io/kube-proxy-ds-ready=true"
update-node-label "beta.kubernetes.io/masq-agent-ds-ready=true,node.kubernetes.io/masq-agent-ds-ready!=true" "node.kubernetes.io/masq-agent-ds-ready=true"
}
# A helper function for labeling all nodes matching a given selector.
# Runs: kubectl label --overwrite nodes -l "${1}" "${2}"
# Retries on failure
#
# $1: label selector of nodes
# $2: label to apply
function update-node-label() {
local selector="$1"
local label="$2"
local retries=5
until (( retries == 0 )); do
if kubectl label --overwrite nodes -l "${selector}" "${label}"; then
break
fi
(( retries-- ))
sleep 3
done
}
# A helper function that sets file permissions for kube-controller-manager to
# run as non root.
# User and group should never contain characters that need to be quoted
# shellcheck disable=SC2086
function run-kube-controller-manager-as-non-root {
prepare-log-file /var/log/kube-controller-manager.log ${KUBE_CONTROLLER_MANAGER_RUNASUSER}
setfacl -m u:${KUBE_CONTROLLER_MANAGER_RUNASUSER}:r "${CA_CERT_BUNDLE_PATH}"
setfacl -m u:${KUBE_CONTROLLER_MANAGER_RUNASUSER}:r "${SERVICEACCOUNT_CERT_PATH}"
setfacl -m u:${KUBE_CONTROLLER_MANAGER_RUNASUSER}:r "${SERVICEACCOUNT_KEY_PATH}"
}
# Starts kubernetes controller manager.
# It prepares the log file, loads the docker image, calculates variables, sets them
# in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.
#
# Assumed vars (which are calculated in function compute-master-manifest-variables)
# CLOUD_CONFIG_OPT
# CLOUD_CONFIG_VOLUME
# CLOUD_CONFIG_MOUNT
# DOCKER_REGISTRY
function start-kube-controller-manager {
echo "Start kubernetes controller-manager"
create-kubeconfig "kube-controller-manager" "${KUBE_CONTROLLER_MANAGER_TOKEN}"
prepare-log-file /var/log/kube-controller-manager.log
# Calculate variables and assemble the command line.
local params=("${CONTROLLER_MANAGER_TEST_LOG_LEVEL:-"--v=2"}" "${CONTROLLER_MANAGER_TEST_ARGS:-}" "${CLOUD_CONFIG_OPT}")
local config_path='/etc/srv/kubernetes/kube-controller-manager/kubeconfig'
params+=("--use-service-account-credentials")
params+=("--cloud-provider=gce")
params+=("--kubeconfig=${config_path}" "--authentication-kubeconfig=${config_path}" "--authorization-kubeconfig=${config_path}")
params+=("--root-ca-file=${CA_CERT_BUNDLE_PATH}")
params+=("--service-account-private-key-file=${SERVICEACCOUNT_KEY_PATH}")
if [[ -n "${ENABLE_GARBAGE_COLLECTOR:-}" ]]; then
params+=("--enable-garbage-collector=${ENABLE_GARBAGE_COLLECTOR}")
fi
if [[ -n "${INSTANCE_PREFIX:-}" ]]; then
params+=("--cluster-name=${INSTANCE_PREFIX}")
fi
if [[ -n "${CLUSTER_IP_RANGE:-}" ]]; then
params+=("--cluster-cidr=${CLUSTER_IP_RANGE}")
fi
if [[ -n "${CA_KEY:-}" ]]; then
params+=("--cluster-signing-cert-file=${CA_CERT_PATH}")
params+=("--cluster-signing-key-file=${CA_KEY_PATH}")
fi
if [[ -n "${SERVICE_CLUSTER_IP_RANGE:-}" ]]; then
params+=("--service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}")
fi
if [[ -n "${CONCURRENT_SERVICE_SYNCS:-}" ]]; then
params+=("--concurrent-service-syncs=${CONCURRENT_SERVICE_SYNCS}")
fi
if [[ "${NETWORK_PROVIDER:-}" == "kubenet" ]]; then
params+=("--allocate-node-cidrs=true")
elif [[ -n "${ALLOCATE_NODE_CIDRS:-}" ]]; then
params+=("--allocate-node-cidrs=${ALLOCATE_NODE_CIDRS}")
fi
if [[ -n "${TERMINATED_POD_GC_THRESHOLD:-}" ]]; then
params+=("--terminated-pod-gc-threshold=${TERMINATED_POD_GC_THRESHOLD}")
fi
if [[ "${ENABLE_IP_ALIASES:-}" == 'true' ]]; then
params+=("--cidr-allocator-type=${NODE_IPAM_MODE}")
params+=("--configure-cloud-routes=false")
fi
if [[ -n "${FEATURE_GATES:-}" ]]; then
params+=("--feature-gates=${FEATURE_GATES}")
fi
if [[ -n "${VOLUME_PLUGIN_DIR:-}" ]]; then
params+=("--flex-volume-plugin-dir=${VOLUME_PLUGIN_DIR}")
fi
if [[ -n "${CLUSTER_SIGNING_DURATION:-}" ]]; then
params+=("--cluster-signing-duration=$CLUSTER_SIGNING_DURATION")
fi
# Disable using HPA metrics REST clients if metrics-server isn't enabled,
# or if we want to explicitly disable it by setting HPA_USE_REST_CLIENT.
if [[ "${ENABLE_METRICS_SERVER:-}" != "true" ]] ||
[[ "${HPA_USE_REST_CLIENTS:-}" == "false" ]]; then
params+=("--horizontal-pod-autoscaler-use-rest-clients=false")
fi
if [[ -n "${PV_RECYCLER_OVERRIDE_TEMPLATE:-}" ]]; then
params+=("--pv-recycler-pod-template-filepath-nfs=$PV_RECYCLER_OVERRIDE_TEMPLATE")
params+=("--pv-recycler-pod-template-filepath-hostpath=$PV_RECYCLER_OVERRIDE_TEMPLATE")
fi
if [[ -n "${RUN_CONTROLLERS:-}" ]]; then
params+=("--controllers=${RUN_CONTROLLERS}")
fi
local -r kube_rc_docker_tag=$(cat /home/kubernetes/kube-docker-files/kube-controller-manager.docker_tag)
local container_env=""
if [[ -n "${ENABLE_CACHE_MUTATION_DETECTOR:-}" ]]; then
container_env="\"env\":[{\"name\": \"KUBE_CACHE_MUTATION_DETECTOR\", \"value\": \"${ENABLE_CACHE_MUTATION_DETECTOR}\"}],"
fi
local paramstring
paramstring="$(convert-manifest-params "${params[*]}")"
local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-controller-manager.manifest"
# Evaluate variables.
sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${DOCKER_REGISTRY}@g" "${src_file}"
sed -i -e "s@{{pillar\['kube-controller-manager_docker_tag'\]}}@${kube_rc_docker_tag}@g" "${src_file}"
sed -i -e "s@{{params}}@${paramstring}@g" "${src_file}"
sed -i -e "s@{{container_env}}@${container_env}@g" "${src_file}"
sed -i -e "s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g" "${src_file}"
sed -i -e "s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g" "${src_file}"
sed -i -e "s@{{additional_cloud_config_mount}}@@g" "${src_file}"
sed -i -e "s@{{additional_cloud_config_volume}}@@g" "${src_file}"
sed -i -e "s@{{pv_recycler_mount}}@${PV_RECYCLER_MOUNT}@g" "${src_file}"
sed -i -e "s@{{pv_recycler_volume}}@${PV_RECYCLER_VOLUME}@g" "${src_file}"
sed -i -e "s@{{flexvolume_hostpath_mount}}@${FLEXVOLUME_HOSTPATH_MOUNT}@g" "${src_file}"
sed -i -e "s@{{flexvolume_hostpath}}@${FLEXVOLUME_HOSTPATH_VOLUME}@g" "${src_file}"
sed -i -e "s@{{cpurequest}}@${KUBE_CONTROLLER_MANAGER_CPU_REQUEST}@g" "${src_file}"
if [[ -n "${KUBE_CONTROLLER_MANAGER_RUNASUSER:-}" && -n "${KUBE_CONTROLLER_MANAGER_RUNASGROUP:-}" ]]; then
run-kube-controller-manager-as-non-root
sed -i -e "s@{{runAsUser}}@${KUBE_CONTROLLER_MANAGER_RUNASUSER}@g" "${src_file}"
sed -i -e "s@{{runAsGroup}}@${KUBE_CONTROLLER_MANAGER_RUNASGROUP}@g" "${src_file}"
else
sed -i -e "s@{{runAsUser}}@0@g" "${src_file}"
sed -i -e "s@{{runAsGroup}}@0@g" "${src_file}"
fi
cp "${src_file}" /etc/kubernetes/manifests
}
# Starts kubernetes scheduler.
# It prepares the log file, loads the docker image, calculates variables, sets them
# in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.
#
# Assumed vars (which are calculated in compute-master-manifest-variables)
# DOCKER_REGISTRY
function start-kube-scheduler {
if [[ "${KUBE_SCHEDULER_CRP:-}" == "true" ]]; then
echo "kube-scheduler is configured to be deployed through CRP."
return
fi
echo "Start kubernetes scheduler"
create-kubeconfig "kube-scheduler" "${KUBE_SCHEDULER_TOKEN}"
# User and group should never contain characters that need to be quoted
# shellcheck disable=SC2086
prepare-log-file /var/log/kube-scheduler.log ${KUBE_SCHEDULER_RUNASUSER:-2001}
# Calculate variables and set them in the manifest.
params=("${SCHEDULER_TEST_LOG_LEVEL:-"--v=2"}" "${SCHEDULER_TEST_ARGS:-}")
if [[ -n "${FEATURE_GATES:-}" ]]; then
params+=("--feature-gates=${FEATURE_GATES}")
fi
# Scheduler Component Config takes precedence over some flags.
if [[ -n "${KUBE_SCHEDULER_CONFIG:-}" ]]; then
create-kube-scheduler-config
params+=("--config=/etc/srv/kubernetes/kube-scheduler/config")
else
params+=("--kubeconfig=/etc/srv/kubernetes/kube-scheduler/kubeconfig")
if [[ -n "${SCHEDULING_ALGORITHM_PROVIDER:-}" ]]; then
params+=("--algorithm-provider=${SCHEDULING_ALGORITHM_PROVIDER}")
fi
if [[ -n "${SCHEDULER_POLICY_CONFIG:-}" ]]; then
create-kubescheduler-policy-config
params+=("--use-legacy-policy-config")
params+=("--policy-config-file=/etc/srv/kubernetes/kube-scheduler/policy-config")
fi
fi
local config_path
config_path='/etc/srv/kubernetes/kube-scheduler/kubeconfig'
params+=("--authentication-kubeconfig=${config_path}" "--authorization-kubeconfig=${config_path}")
local paramstring
paramstring="$(convert-manifest-params "${params[*]}")"
local -r kube_scheduler_docker_tag=$(cat "${KUBE_HOME}/kube-docker-files/kube-scheduler.docker_tag")
# Remove salt comments and replace variables with values.
local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-scheduler.manifest"
sed -i -e "s@{{params}}@${paramstring}@g" "${src_file}"
sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${DOCKER_REGISTRY}@g" "${src_file}"
sed -i -e "s@{{pillar\['kube-scheduler_docker_tag'\]}}@${kube_scheduler_docker_tag}@g" "${src_file}"
sed -i -e "s@{{cpurequest}}@${KUBE_SCHEDULER_CPU_REQUEST}@g" "${src_file}"
sed -i -e "s@{{runAsUser}}@${KUBE_SCHEDULER_RUNASUSER:-2001}@g" "${src_file}"
sed -i -e "s@{{runAsGroup}}@${KUBE_SCHEDULER_RUNASGROUP:-2001}@g" "${src_file}"
cp "${src_file}" /etc/kubernetes/manifests
}
# Starts cluster autoscaler.
# Assumed vars (which are calculated in function compute-master-manifest-variables)
# CLOUD_CONFIG_OPT
# CLOUD_CONFIG_VOLUME
# CLOUD_CONFIG_MOUNT
function start-cluster-autoscaler {
if [[ "${ENABLE_CLUSTER_AUTOSCALER:-}" == "true" ]]; then
echo "Start kubernetes cluster autoscaler"
setup-addon-manifests "addons" "rbac/cluster-autoscaler"
create-kubeconfig "cluster-autoscaler" "${KUBE_CLUSTER_AUTOSCALER_TOKEN}"
prepare-log-file /var/log/cluster-autoscaler.log
# Remove salt comments and replace variables with values
local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/cluster-autoscaler.manifest"
local params
read -r -a params <<< "${AUTOSCALER_MIG_CONFIG}"
params+=("${CLOUD_CONFIG_OPT}" "${AUTOSCALER_EXPANDER_CONFIG:---expander=price}")
params+=("--kubeconfig=/etc/srv/kubernetes/cluster-autoscaler/kubeconfig")
# split the params into separate arguments passed to binary
local params_split
params_split=$(eval 'for param in "${params[@]}"; do echo -n \""$param"\",; done')
params_split=${params_split%?}
sed -i -e "s@{{params}}@${params_split}@g" "${src_file}"
sed -i -e "s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g" "${src_file}"
sed -i -e "s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g" "${src_file}"
sed -i -e "s@{%.*%}@@g" "${src_file}"
cp "${src_file}" /etc/kubernetes/manifests
fi
}
# A helper function for setting up addon manifests.
#
# $1: addon category under /etc/kubernetes
# $2: manifest source dir
# $3: (optional) auxiliary manifest source dir
function setup-addon-manifests {
local -r src_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty"
local -r dst_dir="/etc/kubernetes/$1/$2"
copy-manifests "${src_dir}/$2" "${dst_dir}"
# If the PodSecurityPolicy admission controller is enabled,
# set up the corresponding addon policies.
if [[ "${ENABLE_POD_SECURITY_POLICY:-}" == "true" ]]; then
local -r psp_dir="${src_dir}/${3:-$2}/podsecuritypolicies"
if [[ -d "${psp_dir}" ]]; then
copy-manifests "${psp_dir}" "${dst_dir}"
fi
fi
if [[ "${ENABLE_NODE_TERMINATION_HANDLER:-}" == "true" ]]; then
local -r nth_dir="${src_dir}/${3:-$2}/node-termination-handler"
if [[ -d "${nth_dir}" ]]; then
copy-manifests "${nth_dir}" "${dst_dir}"
fi
fi
}
# A function that downloads extra addons from a URL and puts them in the GCI
# manifests directory.
function download-extra-addons {
local -r out_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/gce-extras"
mkdir -p "${out_dir}"
local curl_cmd=(
"curl"
"--fail"
"--retry" "5"
"--retry-delay" "3"
"--silent"
"--show-error"
)
if [[ -n "${CURL_RETRY_CONNREFUSED:-}" ]]; then
curl_cmd+=("${CURL_RETRY_CONNREFUSED}")
fi
if [[ -n "${EXTRA_ADDONS_HEADER:-}" ]]; then
curl_cmd+=("-H" "${EXTRA_ADDONS_HEADER}")
fi
curl_cmd+=("-o" "${out_dir}/extras.json")
curl_cmd+=("${EXTRA_ADDONS_URL}")
"${curl_cmd[@]}"
}
# A function that fetches a GCE metadata value and echoes it out.
#
# $1: URL path after /computeMetadata/v1/ (without heading slash).
function get-metadata-value {
# We do not want quotes for CURL_RETRY_CONNREFUSED
# shellcheck disable=SC2086
curl \
--retry 5 \
--retry-delay 3 \
${CURL_RETRY_CONNREFUSED} \
--fail \
--silent \
-H 'Metadata-Flavor: Google' \
"http://metadata/computeMetadata/v1/${1}"
}
# A helper function for copying manifests and setting dir/files
# permissions.
#
# $1: absolute source dir
# $2: absolute destination dir
function copy-manifests {
local -r src_dir="$1"
local -r dst_dir="$2"
if [[ ! -d "${dst_dir}" ]]; then
mkdir -p "${dst_dir}"
fi
if [[ -n "$(ls "${src_dir}"/*.yaml 2>/dev/null)" ]]; then
cp "${src_dir}/"*.yaml "${dst_dir}"
fi
if [[ -n "$(ls "${src_dir}"/*.json 2>/dev/null)" ]]; then
cp "${src_dir}/"*.json "${dst_dir}"
fi
if [[ -n "$(ls "${src_dir}"/*.yaml.in 2>/dev/null)" ]]; then
cp "${src_dir}/"*.yaml.in "${dst_dir}"
fi
chown -R root:root "${dst_dir}"
chmod 755 "${dst_dir}"
chmod 644 "${dst_dir}"/*
}
# Fluentd resources are modified using ScalingPolicy CR, which may not be
# available at this point. Run this as a background process.
function wait-for-apiserver-and-update-fluentd {
local any_overrides=false
if [[ -n "${FLUENTD_GCP_MEMORY_LIMIT:-}" ]]; then
any_overrides=true
fi
if [[ -n "${FLUENTD_GCP_CPU_REQUEST:-}" ]]; then
any_overrides=true
fi
if [[ -n "${FLUENTD_GCP_MEMORY_REQUEST:-}" ]]; then
any_overrides=true
fi
if ! $any_overrides; then
# Nothing to do here.
exit
fi
# Wait until ScalingPolicy CRD is in place.
until kubectl get scalingpolicies.scalingpolicy.kope.io
do
sleep 10
done
# Single-shot, not managed by addon manager. Can be later modified or removed
# at will.
cat <<EOF | kubectl apply -f -
apiVersion: scalingpolicy.kope.io/v1alpha1
kind: ScalingPolicy
metadata:
name: fluentd-gcp-scaling-policy
namespace: kube-system
spec:
containers:
- name: fluentd-gcp
resources:
requests:
- resource: cpu
base: ${FLUENTD_GCP_CPU_REQUEST:-}
- resource: memory
base: ${FLUENTD_GCP_MEMORY_REQUEST:-}
limits:
- resource: memory
base: ${FLUENTD_GCP_MEMORY_LIMIT:-}
EOF
}
# Trigger background process that will ultimately update fluentd resource
# requirements.
function start-fluentd-resource-update {
wait-for-apiserver-and-update-fluentd &
}
# VolumeSnapshot CRDs and controller are installed by cluster addon manager,
# which may not be available at this point. Run this as a background process.
function wait-for-volumesnapshot-crd-and-controller {
# Wait until volumesnapshot CRDs and controller are in place.
echo "Wait until volume snapshot CRDs are installed"
until kubectl get volumesnapshotclasses.snapshot.storage.k8s.io
do
sleep 10
done
until kubectl get volumesnapshotcontents.snapshot.storage.k8s.io
do
sleep 10
done
until kubectl get volumesnapshots.snapshot.storage.k8s.io
do
sleep 10
done
echo "Wait until volume snapshot RBAC rules are installed"
until kubectl get clusterrolebinding volume-snapshot-controller-role
do
sleep 10
done
echo "Wait until volume snapshot controller is installed"
until kubectl get statefulset volume-snapshot-controller | grep volume-snapshot-controller | grep "1/1"
do
sleep 10
done
}
# Trigger background process that will wait for volumesnapshot CRDs
# and snapshot-controller to be installed
function start-volumesnapshot-crd-and-controller {
wait-for-volumesnapshot-crd-and-controller &
}
# Update {{ fluentd_container_runtime_service }} with actual container runtime name,
# and {{ container_runtime_endpoint }} with actual container runtime
# endpoint.
function update-container-runtime {
local -r file="$1"
local -r container_runtime_endpoint="${CONTAINER_RUNTIME_ENDPOINT:-unix:///var/run/dockershim.sock}"
sed -i \
-e "s@{{ *fluentd_container_runtime_service *}}@${FLUENTD_CONTAINER_RUNTIME_SERVICE:-${CONTAINER_RUNTIME_NAME:-docker}}@g" \
-e "s@{{ *container_runtime_endpoint *}}@${container_runtime_endpoint#unix://}@g" \
"${file}"
}
# Remove configuration in yaml file if node journal is not enabled.
function update-node-journal {
local -r configmap_yaml="$1"
if [[ "${ENABLE_NODE_JOURNAL:-}" != "true" ]]; then
# Removes all lines between two patterns (throws away node-journal)
sed -i -e "/# BEGIN_NODE_JOURNAL/,/# END_NODE_JOURNAL/d" "${configmap_yaml}"
fi
}
# Updates parameters in yaml file for prometheus-to-sd configuration, or
# removes component if it is disabled.
function update-prometheus-to-sd-parameters {
if [[ "${ENABLE_PROMETHEUS_TO_SD:-}" == "true" ]]; then
sed -i -e "s@{{ *prometheus_to_sd_prefix *}}@${PROMETHEUS_TO_SD_PREFIX}@g" "$1"
sed -i -e "s@{{ *prometheus_to_sd_endpoint *}}@${PROMETHEUS_TO_SD_ENDPOINT}@g" "$1"
else
# Removes all lines between two patterns (throws away prometheus-to-sd)
sed -i -e "/# BEGIN_PROMETHEUS_TO_SD/,/# END_PROMETHEUS_TO_SD/d" "$1"
fi
}
# Updates parameters in yaml file for prometheus-to-sd configuration in daemon sets, or
# removes component if it is disabled.
function update-daemon-set-prometheus-to-sd-parameters {
if [[ "${DISABLE_PROMETHEUS_TO_SD_IN_DS:-}" == "true" ]]; then
# Removes all lines between two patterns (throws away prometheus-to-sd)
sed -i -e "/# BEGIN_PROMETHEUS_TO_SD/,/# END_PROMETHEUS_TO_SD/d" "$1"
else
update-prometheus-to-sd-parameters "$1"
fi
}
# Updates parameters in yaml file for event-exporter configuration
function update-event-exporter {
local -r stackdriver_resource_model="${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}"
sed -i -e "s@{{ exporter_sd_resource_model }}@${stackdriver_resource_model}@g" "$1"
sed -i -e "s@{{ exporter_sd_endpoint }}@${STACKDRIVER_ENDPOINT:-}@g" "$1"
}
function update-dashboard-deployment {
if [ -n "${CUSTOM_KUBE_DASHBOARD_BANNER:-}" ]; then
sed -i -e "s@\( \+\)# PLATFORM-SPECIFIC ARGS HERE@\1- --system-banner=${CUSTOM_KUBE_DASHBOARD_BANNER}\n\1- --system-banner-severity=WARNING@" "$1"
fi
}
# Sets up the manifests of coreDNS for k8s addons.
function setup-coredns-manifest {
setup-addon-manifests "addons" "0-dns/coredns"
local -r coredns_file="${dst_dir}/0-dns/coredns/coredns.yaml"
mv "${dst_dir}/0-dns/coredns/coredns.yaml.in" "${coredns_file}"
# Replace the salt configurations with variable values.
sed -i -e "s@dns_domain@${DNS_DOMAIN}@g" "${coredns_file}"
sed -i -e "s@dns_server@${DNS_SERVER_IP}@g" "${coredns_file}"
sed -i -e "s@{{ *pillar\['service_cluster_ip_range'\] *}}@${SERVICE_CLUSTER_IP_RANGE}@g" "${coredns_file}"
sed -i -e "s@dns_memory_limit@${DNS_MEMORY_LIMIT:-170Mi}@g" "${coredns_file}"
if [[ "${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-}" == "true" ]]; then
setup-addon-manifests "addons" "dns-horizontal-autoscaler" "gce"
local -r dns_autoscaler_file="${dst_dir}/dns-horizontal-autoscaler/dns-horizontal-autoscaler.yaml"
sed -i'' -e "s@{{.Target}}@${COREDNS_AUTOSCALER}@g" "${dns_autoscaler_file}"
fi
}
# Sets up the manifests of Fluentd configmap and yamls for k8s addons.
function setup-fluentd {
local -r dst_dir="$1"
local -r fluentd_gcp_yaml="${dst_dir}/fluentd-gcp/fluentd-gcp-ds.yaml"
local -r fluentd_gcp_scaler_yaml="${dst_dir}/fluentd-gcp/scaler-deployment.yaml"
# Ingest logs against new resources like "k8s_container" and "k8s_node" if
# LOGGING_STACKDRIVER_RESOURCE_TYPES is "new".
# Ingest logs against old resources like "gke_container" and "gce_instance" if
# LOGGING_STACKDRIVER_RESOURCE_TYPES is "old".
if [[ "${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}" == "new" ]]; then
local -r fluentd_gcp_configmap_yaml="${dst_dir}/fluentd-gcp/fluentd-gcp-configmap.yaml"
fluentd_gcp_configmap_name="fluentd-gcp-config"
else
local -r fluentd_gcp_configmap_yaml="${dst_dir}/fluentd-gcp/fluentd-gcp-configmap-old.yaml"
fluentd_gcp_configmap_name="fluentd-gcp-config-old"
fi
sed -i -e "s@{{ fluentd_gcp_configmap_name }}@${fluentd_gcp_configmap_name}@g" "${fluentd_gcp_yaml}"
fluentd_gcp_yaml_version="${FLUENTD_GCP_YAML_VERSION:-v3.2.0}"
sed -i -e "s@{{ fluentd_gcp_yaml_version }}@${fluentd_gcp_yaml_version}@g" "${fluentd_gcp_yaml}"
sed -i -e "s@{{ fluentd_gcp_yaml_version }}@${fluentd_gcp_yaml_version}@g" "${fluentd_gcp_scaler_yaml}"
fluentd_gcp_version="${FLUENTD_GCP_VERSION:-1.6.17}"
sed -i -e "s@{{ fluentd_gcp_version }}@${fluentd_gcp_version}@g" "${fluentd_gcp_yaml}"
update-daemon-set-prometheus-to-sd-parameters "${fluentd_gcp_yaml}"
start-fluentd-resource-update "${fluentd_gcp_yaml}"
update-container-runtime "${fluentd_gcp_configmap_yaml}"
update-node-journal "${fluentd_gcp_configmap_yaml}"
}
# Sets up the manifests of kube-dns for k8s addons.
function setup-kube-dns-manifest {
setup-addon-manifests "addons" "0-dns/kube-dns"
local -r kubedns_file="${dst_dir}/0-dns/kube-dns/kube-dns.yaml"
mv "${dst_dir}/0-dns/kube-dns/kube-dns.yaml.in" "${kubedns_file}"
if [ -n "${CUSTOM_KUBE_DNS_YAML:-}" ]; then
# Replace with custom GKE kube-dns deployment.
cat > "${kubedns_file}" <<EOF
$CUSTOM_KUBE_DNS_YAML
EOF
update-prometheus-to-sd-parameters "${kubedns_file}"
fi
# Replace the salt configurations with variable values.
sed -i -e "s@dns_domain@${DNS_DOMAIN}@g" "${kubedns_file}"
sed -i -e "s@dns_server@${DNS_SERVER_IP}@g" "${kubedns_file}"
sed -i -e "s@dns_memory_limit@${DNS_MEMORY_LIMIT:-170Mi}@g" "${kubedns_file}"
if [[ "${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-}" == "true" ]]; then
setup-addon-manifests "addons" "dns-horizontal-autoscaler" "gce"
local -r dns_autoscaler_file="${dst_dir}/dns-horizontal-autoscaler/dns-horizontal-autoscaler.yaml"
sed -i'' -e "s@{{.Target}}@${KUBEDNS_AUTOSCALER}@g" "${dns_autoscaler_file}"
fi
}
# Sets up the manifests of local dns cache agent for k8s addons.
function setup-nodelocaldns-manifest {
setup-addon-manifests "addons" "0-dns/nodelocaldns"
local -r localdns_file="${dst_dir}/0-dns/nodelocaldns/nodelocaldns.yaml"
setup-addon-custom-yaml "addons" "0-dns/nodelocaldns" "nodelocaldns.yaml" "${CUSTOM_NODELOCAL_DNS_YAML:-}"
# eventually all the __PILLAR__ stuff will be gone, but theyre still in nodelocaldns for backward compat.
sed -i -e "s/__PILLAR__DNS__DOMAIN__/${DNS_DOMAIN}/g" "${localdns_file}"
sed -i -e "s/__PILLAR__DNS__SERVER__/${DNS_SERVER_IP}/g" "${localdns_file}"
sed -i -e "s/__PILLAR__LOCAL__DNS__/${LOCAL_DNS_IP}/g" "${localdns_file}"
}
# Sets up the manifests of netd for k8s addons.
function setup-netd-manifest {
local -r netd_file="${dst_dir}/netd/netd.yaml"
mkdir -p "${dst_dir}/netd"
touch "${netd_file}"
if [ -n "${CUSTOM_NETD_YAML:-}" ]; then
# Replace with custom GCP netd deployment.
cat > "${netd_file}" <<EOF
$CUSTOM_NETD_YAML
EOF
fi
}
# A helper function to set up a custom yaml for a k8s addon.
#
# $1: addon category under /etc/kubernetes
# $2: manifest source dir
# $3: manifest file
# $4: custom yaml
function setup-addon-custom-yaml {
local -r manifest_path="/etc/kubernetes/$1/$2/$3"
local -r custom_yaml="$4"
if [ -n "${custom_yaml:-}" ]; then
# Replace with custom manifest.
cat > "${manifest_path}" <<EOF
$custom_yaml
EOF
fi
}
# Prepares the manifests of k8s addons, and starts the addon manager.
# Vars assumed:
# CLUSTER_NAME
function start-kube-addons {
echo "Prepare kube-addons manifests and start kube addon manager"
local -r src_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty"
local -r dst_dir="/etc/kubernetes/addons"
create-kubeconfig "addon-manager" "${ADDON_MANAGER_TOKEN}"
# User and group should never contain characters that need to be quoted
# shellcheck disable=SC2086
prepare-log-file /var/log/kube-addon-manager.log ${KUBE_ADDON_MANAGER_RUNASUSER:-2002}
# prep addition kube-up specific rbac objects
setup-addon-manifests "addons" "rbac/kubelet-api-auth"
setup-addon-manifests "addons" "rbac/kubelet-cert-rotation"
if [[ "${REGISTER_MASTER_KUBELET:-false}" == "true" ]]; then
setup-addon-manifests "addons" "rbac/legacy-kubelet-user"
else
setup-addon-manifests "addons" "rbac/legacy-kubelet-user-disable"
fi
if [[ "${ENABLE_POD_SECURITY_POLICY:-}" == "true" ]]; then
setup-addon-manifests "addons" "podsecuritypolicies"
fi
# Set up manifests of other addons.
if [[ "${KUBE_PROXY_DAEMONSET:-}" == "true" ]] && [[ "${KUBE_PROXY_DISABLE:-}" != "true" ]]; then
if [ -n "${CUSTOM_KUBE_PROXY_YAML:-}" ]; then
# Replace with custom GKE kube proxy.
cat > "$src_dir/kube-proxy/kube-proxy-ds.yaml" <<EOF
$CUSTOM_KUBE_PROXY_YAML
EOF
update-daemon-set-prometheus-to-sd-parameters "$src_dir/kube-proxy/kube-proxy-ds.yaml"
fi
prepare-kube-proxy-manifest-variables "$src_dir/kube-proxy/kube-proxy-ds.yaml"
setup-addon-manifests "addons" "kube-proxy"
fi
if [[ "${ENABLE_CLUSTER_LOGGING:-}" == "true" ]] &&
[[ "${LOGGING_DESTINATION:-}" == "gcp" ]]; then
if [[ "${ENABLE_METADATA_AGENT:-}" == "stackdriver" ]]; then
metadata_agent_cpu_request="${METADATA_AGENT_CPU_REQUEST:-40m}"
metadata_agent_memory_request="${METADATA_AGENT_MEMORY_REQUEST:-50Mi}"
metadata_agent_cluster_level_cpu_request="${METADATA_AGENT_CLUSTER_LEVEL_CPU_REQUEST:-40m}"
metadata_agent_cluster_level_memory_request="${METADATA_AGENT_CLUSTER_LEVEL_MEMORY_REQUEST:-50Mi}"
setup-addon-manifests "addons" "metadata-agent/stackdriver"
metadata_agent_yaml="${dst_dir}/metadata-agent/stackdriver/metadata-agent.yaml"
sed -i -e "s@{{ metadata_agent_cpu_request }}@${metadata_agent_cpu_request}@g" "${metadata_agent_yaml}"
sed -i -e "s@{{ metadata_agent_memory_request }}@${metadata_agent_memory_request}@g" "${metadata_agent_yaml}"
sed -i -e "s@{{ metadata_agent_cluster_level_cpu_request }}@${metadata_agent_cluster_level_cpu_request}@g" "${metadata_agent_yaml}"
sed -i -e "s@{{ metadata_agent_cluster_level_memory_request }}@${metadata_agent_cluster_level_memory_request}@g" "${metadata_agent_yaml}"
fi
fi
if [[ "${ENABLE_METRICS_SERVER:-}" == "true" ]]; then
setup-addon-manifests "addons" "metrics-server"
base_metrics_server_cpu="40m"
base_metrics_server_memory="40Mi"
metrics_server_memory_per_node="4"
metrics_server_min_cluster_size="16"
if [[ "${ENABLE_SYSTEM_ADDON_RESOURCE_OPTIMIZATIONS:-}" == "true" ]]; then
base_metrics_server_cpu="40m"
base_metrics_server_memory="35Mi"
metrics_server_memory_per_node="4"
metrics_server_min_cluster_size="5"
fi
local -r metrics_server_yaml="${dst_dir}/metrics-server/metrics-server-deployment.yaml"
sed -i -e "s@{{ base_metrics_server_cpu }}@${base_metrics_server_cpu}@g" "${metrics_server_yaml}"
sed -i -e "s@{{ base_metrics_server_memory }}@${base_metrics_server_memory}@g" "${metrics_server_yaml}"
sed -i -e "s@{{ metrics_server_memory_per_node }}@${metrics_server_memory_per_node}@g" "${metrics_server_yaml}"
sed -i -e "s@{{ metrics_server_min_cluster_size }}@${metrics_server_min_cluster_size}@g" "${metrics_server_yaml}"
fi
if [[ "${ENABLE_NVIDIA_GPU_DEVICE_PLUGIN:-}" == "true" ]]; then
setup-addon-manifests "addons" "device-plugins/nvidia-gpu"
fi
if [[ "${ENABLE_NODE_TERMINATION_HANDLER:-}" == "true" ]]; then
setup-addon-manifests "addons" "node-termination-handler"
setup-node-termination-handler-manifest ''
fi
# Setting up the konnectivity-agent daemonset
if [[ "${RUN_KONNECTIVITY_PODS:-false}" == "true" ]]; then
setup-addon-manifests "addons" "konnectivity-agent"
setup-konnectivity-agent-manifest
fi
if [[ "${ENABLE_CLUSTER_DNS:-}" == "true" ]]; then
# Create a new directory for the DNS addon and prepend a "0" on the name.
# Prepending "0" to the directory ensures that add-on manager
# creates the dns service first. This ensures no other add-on
# can "steal" the designated DNS clusterIP.
BASE_ADDON_DIR=${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty
BASE_DNS_DIR=${BASE_ADDON_DIR}/dns
NEW_DNS_DIR=${BASE_ADDON_DIR}/0-dns
mkdir "${NEW_DNS_DIR}" && mv "${BASE_DNS_DIR}"/* "${NEW_DNS_DIR}" && rm -r "${BASE_DNS_DIR}"
if [[ "${CLUSTER_DNS_CORE_DNS:-}" == "true" ]]; then
setup-coredns-manifest
else
setup-kube-dns-manifest
fi
if [[ "${ENABLE_NODELOCAL_DNS:-}" == "true" ]]; then
setup-nodelocaldns-manifest
fi
fi
if [[ "${ENABLE_NETD:-}" == "true" ]]; then
setup-netd-manifest
fi
if [[ "${ENABLE_NODE_LOGGING:-}" == "true" ]] && \
[[ "${LOGGING_DESTINATION:-}" == "elasticsearch" ]] && \
[[ "${ENABLE_CLUSTER_LOGGING:-}" == "true" ]]; then
setup-addon-manifests "addons" "fluentd-elasticsearch"
local -r fluentd_es_configmap_yaml="${dst_dir}/fluentd-elasticsearch/fluentd-es-configmap.yaml"
update-container-runtime ${fluentd_es_configmap_yaml}
fi
if [[ "${ENABLE_NODE_LOGGING:-}" == "true" ]] && \
[[ "${LOGGING_DESTINATION:-}" == "gcp" ]]; then
setup-addon-manifests "addons" "fluentd-gcp"
setup-fluentd ${dst_dir}
local -r event_exporter_yaml="${dst_dir}/fluentd-gcp/event-exporter.yaml"
update-event-exporter ${event_exporter_yaml}
update-prometheus-to-sd-parameters ${event_exporter_yaml}
fi
if [[ "${ENABLE_CLUSTER_UI:-}" == "true" ]]; then
setup-addon-manifests "addons" "dashboard"
local -r dashboard_deployment_yaml="${dst_dir}/dashboard/dashboard-deployment.yaml"
update-dashboard-deployment ${dashboard_deployment_yaml}
fi
if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "daemonset" ]]; then
setup-addon-manifests "addons" "node-problem-detector"
fi
if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "standalone" ]]; then
# Setup role binding(s) for standalone node problem detector.
if [[ -n "${NODE_PROBLEM_DETECTOR_TOKEN:-}" ]]; then
setup-addon-manifests "addons" "node-problem-detector/standalone"
fi
setup-addon-manifests "addons" "node-problem-detector/kubelet-user-standalone" "node-problem-detector"
fi
if echo "${ADMISSION_CONTROL:-}" | grep -q "LimitRanger"; then
setup-addon-manifests "admission-controls" "limit-range" "gce"
fi
setup-addon-manifests "addons" "admission-resource-quota-critical-pods"
if [[ "${NETWORK_POLICY_PROVIDER:-}" == "calico" ]]; then
setup-addon-manifests "addons" "calico-policy-controller"
setup-addon-custom-yaml "addons" "calico-policy-controller" "calico-node-daemonset.yaml" "${CUSTOM_CALICO_NODE_DAEMONSET_YAML:-}"
setup-addon-custom-yaml "addons" "calico-policy-controller" "typha-deployment.yaml" "${CUSTOM_TYPHA_DEPLOYMENT_YAML:-}"
# Configure Calico CNI directory.
local -r ds_file="${dst_dir}/calico-policy-controller/calico-node-daemonset.yaml"
sed -i -e "s@__CALICO_CNI_DIR__@/home/kubernetes/bin@g" "${ds_file}"
fi
if [[ "${ENABLE_DEFAULT_STORAGE_CLASS:-}" == "true" ]]; then
setup-addon-manifests "addons" "storage-class/gce"
fi
if [[ "${ENABLE_VOLUME_SNAPSHOTS:-}" == "true" ]]; then
setup-addon-manifests "addons" "volumesnapshots/crd"
setup-addon-manifests "addons" "volumesnapshots/volume-snapshot-controller"
start-volumesnapshot-crd-and-controller
fi
if [[ "${ENABLE_IP_MASQ_AGENT:-}" == "true" ]]; then
setup-addon-manifests "addons" "ip-masq-agent"
fi
if [[ "${ENABLE_METADATA_CONCEALMENT:-}" == "true" ]]; then
setup-addon-manifests "addons" "metadata-proxy/gce"
local -r metadata_proxy_yaml="${dst_dir}/metadata-proxy/gce/metadata-proxy.yaml"
update-daemon-set-prometheus-to-sd-parameters ${metadata_proxy_yaml}
fi
if [[ "${ENABLE_ISTIO:-}" == "true" ]]; then
if [[ "${ISTIO_AUTH_TYPE:-}" == "MUTUAL_TLS" ]]; then
setup-addon-manifests "addons" "istio/auth"
else
setup-addon-manifests "addons" "istio/noauth"
fi
fi
if [[ -n "${EXTRA_ADDONS_URL:-}" ]]; then
download-extra-addons
setup-addon-manifests "addons" "gce-extras"
fi
# Place addon manager pod manifest.
src_file="${src_dir}/kube-addon-manager.yaml"
sed -i -e "s@{{kubectl_prune_whitelist_override}}@${KUBECTL_PRUNE_WHITELIST_OVERRIDE:-}@g" "${src_file}"
sed -i -e "s@{{kubectl_extra_prune_whitelist}}@${ADDON_MANAGER_PRUNE_WHITELIST:-}@g" "${src_file}"
sed -i -e "s@{{runAsUser}}@${KUBE_ADDON_MANAGER_RUNASUSER:-2002}@g" "${src_file}"
sed -i -e "s@{{runAsGroup}}@${KUBE_ADDON_MANAGER_RUNASGROUP:-2002}@g" "${src_file}"
cp "${src_file}" /etc/kubernetes/manifests
}
function setup-node-termination-handler-manifest {
local -r nth_manifest="/etc/kubernetes/$1/$2/daemonset.yaml"
if [[ -n "${NODE_TERMINATION_HANDLER_IMAGE}" ]]; then
sed -i "s|image:.*|image: ${NODE_TERMINATION_HANDLER_IMAGE}|" "${nth_manifest}"
fi
}
function setup-konnectivity-agent-manifest {
local -r manifest="/etc/kubernetes/addons/konnectivity-agent/konnectivity-agent-ds.yaml"
sed -i "s|__APISERVER_IP__|${KUBERNETES_MASTER_NAME}|g" "${manifest}"
}
# Setups manifests for ingress controller and gce-specific policies for service controller.
function start-lb-controller {
setup-addon-manifests "addons" "loadbalancing"
# Starts a l7 loadbalancing controller for ingress.
if [[ "${ENABLE_L7_LOADBALANCING:-}" == "glbc" ]]; then
echo "Start GCE L7 pod"
prepare-log-file /var/log/glbc.log
setup-addon-manifests "addons" "cluster-loadbalancing/glbc"
setup-addon-manifests "addons" "rbac/cluster-loadbalancing/glbc"
create-kubeconfig "l7-lb-controller" "${GCE_GLBC_TOKEN}"
local -r src_manifest="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/glbc.manifest"
local -r dest_manifest="/etc/kubernetes/manifests/glbc.manifest"
if [[ -n "${CUSTOM_INGRESS_YAML:-}" ]]; then
echo "${CUSTOM_INGRESS_YAML}" > "${dest_manifest}"
else
cp "${src_manifest}" "${dest_manifest}"
fi
# Override the glbc image if GCE_GLBC_IMAGE is specified.
if [[ -n "${GCE_GLBC_IMAGE:-}" ]]; then
sed -i "s|image:.*|image: ${GCE_GLBC_IMAGE}|" "${dest_manifest}"
fi
fi
}
# Setup working directory for kubelet.
function setup-kubelet-dir {
echo "Making /var/lib/kubelet executable for kubelet"
mount -B /var/lib/kubelet /var/lib/kubelet/
mount -B -o remount,exec,suid,dev /var/lib/kubelet
# TODO(#60123): The kubelet should create the cert-dir directory if it doesn't exist
mkdir -p /var/lib/kubelet/pki/
# Mount /var/lib/kubelet/pki on a tmpfs so it doesn't persist across
# reboots. This can help avoid some rare instances of corrupt cert files
# (e.g. created but not written during a shutdown). Kubelet crash-loops
# in these cases. Do this after above mount calls so it isn't overwritten.
echo "Mounting /var/lib/kubelet/pki on tmpfs"
mount -t tmpfs tmpfs /var/lib/kubelet/pki
}
# Override for GKE custom master setup scripts (no-op outside of GKE).
function gke-master-start {
if [[ -e "${KUBE_HOME}/bin/gke-internal-configure-helper.sh" ]]; then
echo "Running GKE internal configuration script"
. "${KUBE_HOME}/bin/gke-internal-configure-helper.sh"
gke-internal-master-start
elif [[ -n "${KUBE_BEARER_TOKEN:-}" ]]; then
echo "setting up local admin kubeconfig"
create-kubeconfig "local-admin" "${KUBE_BEARER_TOKEN}"
echo "export KUBECONFIG=/etc/srv/kubernetes/local-admin/kubeconfig" > /etc/profile.d/kubeconfig.sh
fi
}
function reset-motd {
# kubelet is installed both on the master and nodes, and the version is easy to parse (unlike kubectl)
local -r version="$("${KUBE_HOME}"/bin/kubelet --version=true | cut -f2 -d " ")"
# This logic grabs either a release tag (v1.2.1 or v1.2.1-alpha.1),
# or the git hash that's in the build info.
local gitref
gitref="$(echo "${version}" | sed -r "s/(v[0-9]+\.[0-9]+\.[0-9]+)(-[a-z]+\.[0-9]+)?.*/\1\2/g")"
local devel=""
if [[ "${gitref}" != "${version}" ]]; then
devel="
Note: This looks like a development version, which might not be present on GitHub.
If it isn't, the closest tag is at:
https://github.com/kubernetes/kubernetes/tree/${gitref}
"
gitref="${version//*+/}"
fi
cat > /etc/motd <<EOF
Welcome to Kubernetes ${version}!
You can find documentation for Kubernetes at:
http://docs.kubernetes.io/
The source for this release can be found at:
/home/kubernetes/kubernetes-src.tar.gz
Or you can download it at:
https://storage.googleapis.com/kubernetes-release/release/${version}/kubernetes-src.tar.gz
It is based on the Kubernetes source at:
https://github.com/kubernetes/kubernetes/tree/${gitref}
${devel}
For Kubernetes copyright and licensing information, see:
/home/kubernetes/LICENSES
EOF
}
function override-kubectl {
echo "overriding kubectl"
echo "export PATH=${KUBE_HOME}/bin:\$PATH" > /etc/profile.d/kube_env.sh
# source the file explicitly otherwise we have
# issues on a ubuntu OS image finding the kubectl
# shellcheck disable=SC1091
source /etc/profile.d/kube_env.sh
# Add ${KUBE_HOME}/bin into sudoer secure path.
local sudo_path
sudo_path=$(sudo env | grep "^PATH=")
if [[ -n "${sudo_path}" ]]; then
sudo_path=${sudo_path#PATH=}
(
umask 027
echo "Defaults secure_path=\"${KUBE_HOME}/bin:${sudo_path}\"" > /etc/sudoers.d/kube_secure_path
)
fi
}
function override-pv-recycler {
if [[ -z "${PV_RECYCLER_OVERRIDE_TEMPLATE:-}" ]]; then
echo "PV_RECYCLER_OVERRIDE_TEMPLATE is not set"
exit 1
fi
PV_RECYCLER_VOLUME="{\"name\": \"pv-recycler-mount\",\"hostPath\": {\"path\": \"${PV_RECYCLER_OVERRIDE_TEMPLATE}\", \"type\": \"FileOrCreate\"}},"
PV_RECYCLER_MOUNT="{\"name\": \"pv-recycler-mount\",\"mountPath\": \"${PV_RECYCLER_OVERRIDE_TEMPLATE}\", \"readOnly\": true},"
cat > "${PV_RECYCLER_OVERRIDE_TEMPLATE}" <<EOF
version: v1
kind: Pod
metadata:
generateName: pv-recycler-
namespace: default
spec:
activeDeadlineSeconds: 60
restartPolicy: Never
volumes:
- name: vol
containers:
- name: pv-recycler
image: k8s.gcr.io/busybox:1.27
command:
- /bin/sh
args:
- -c
- test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z $(ls -A /scrub) || exit 1
volumeMounts:
- name: vol
mountPath: /scrub
EOF
}
function wait-till-apiserver-ready() {
until kubectl get nodes; do
sleep 5
done
}
function ensure-master-bootstrap-kubectl-auth {
# By default, `kubectl` uses http://localhost:8080
# If the insecure port is disabled, kubectl will need to use an admin-authenticated kubeconfig.
if [[ -n "${KUBE_BOOTSTRAP_TOKEN:-}" ]]; then
create-kubeconfig "kube-bootstrap" "${KUBE_BOOTSTRAP_TOKEN}"
export KUBECONFIG=/etc/srv/kubernetes/kube-bootstrap/kubeconfig
fi
}
function setup-containerd {
echo "Generate containerd config"
local config_path="${CONTAINERD_CONFIG_PATH:-"/etc/containerd/config.toml"}"
mkdir -p "$(dirname "${config_path}")"
local cni_template_path="${KUBE_HOME}/cni.template"
cat > "${cni_template_path}" <<EOF
{
"name": "k8s-pod-network",
"cniVersion": "0.3.1",
"plugins": [
{
"type": "ptp",
"mtu": 1460,
"ipam": {
"type": "host-local",
"subnet": "{{.PodCIDR}}",
"routes": [
{
"dst": "0.0.0.0/0"
}
]
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
EOF
if [[ "${KUBERNETES_MASTER:-}" != "true" ]]; then
if [[ "${NETWORK_POLICY_PROVIDER:-"none"}" != "none" || "${ENABLE_NETD:-}" == "true" ]]; then
# Use Kubernetes cni daemonset on node if network policy provider is specified
# or netd is enabled.
cni_template_path=""
fi
fi
cat > "${config_path}" <<EOF
# Kubernetes doesn't use containerd restart manager.
disabled_plugins = ["restart"]
oom_score = -999
[debug]
level = "${CONTAINERD_LOG_LEVEL:-"info"}"
[plugins.cri]
stream_server_address = "127.0.0.1"
max_container_log_line_size = ${CONTAINERD_MAX_CONTAINER_LOG_LINE:-262144}
[plugins.cri.cni]
bin_dir = "${KUBE_HOME}/bin"
conf_dir = "/etc/cni/net.d"
conf_template = "${cni_template_path}"
[plugins.cri.registry.mirrors."docker.io"]
endpoint = ["https://mirror.gcr.io","https://registry-1.docker.io"]
EOF
if [[ "${CONTAINER_RUNTIME_TEST_HANDLER:-}" == "true" ]]; then
cat >> "${config_path}" <<EOF
# Setup a runtime with the magic name ("test-handler") used for Kubernetes
# runtime class tests ...
[plugins.cri.containerd.runtimes.test-handler]
runtime_type = "io.containerd.runtime.v1.linux"
EOF
fi
# Reuse docker group for containerd.
local -r containerd_gid="$(grep ^docker: /etc/group | cut -d: -f 3)"
if [[ -n "${containerd_gid:-}" ]]; then
cat >> "${config_path}" <<EOF
# reuse id of the docker group
[grpc]
gid = ${containerd_gid}
EOF
fi
chmod 644 "${config_path}"
echo "Restart containerd to load the config change"
systemctl restart containerd
}
########### Main Function ###########
function main() {
echo "Start to configure instance for kubernetes"
readonly UUID_MNT_PREFIX="/mnt/disks/by-uuid/google-local-ssds"
readonly UUID_BLOCK_PREFIX="/dev/disk/by-uuid/google-local-ssds"
readonly COREDNS_AUTOSCALER="Deployment/coredns"
readonly KUBEDNS_AUTOSCALER="Deployment/kube-dns"
# Resource requests of master components.
KUBE_CONTROLLER_MANAGER_CPU_REQUEST="${KUBE_CONTROLLER_MANAGER_CPU_REQUEST:-200m}"
KUBE_SCHEDULER_CPU_REQUEST="${KUBE_SCHEDULER_CPU_REQUEST:-75m}"
# Use --retry-connrefused opt only if it's supported by curl.
CURL_RETRY_CONNREFUSED=""
if curl --help | grep -q -- '--retry-connrefused'; then
CURL_RETRY_CONNREFUSED='--retry-connrefused'
fi
KUBE_HOME="/home/kubernetes"
KUBE_BIN=${KUBE_HOME}/bin
CONTAINERIZED_MOUNTER_HOME="${KUBE_HOME}/containerized_mounter"
PV_RECYCLER_OVERRIDE_TEMPLATE="${KUBE_HOME}/kube-manifests/kubernetes/pv-recycler-template.yaml"
if [[ "$(python -V 2>&1)" =~ "Python 2" ]]; then
# found python2, just use that
PYTHON="python"
elif [[ -f "/usr/bin/python2.7" ]]; then
# System python not defaulted to python 2 but using 2.7 during migration
PYTHON="/usr/bin/python2.7"
else
# No python2 either by default, let's see if we can find python3
PYTHON="python3"
if ! command -v ${PYTHON} >/dev/null 2>&1; then
echo "ERROR Python not found. Aborting."
exit 2
fi
fi
echo "Version : $(${PYTHON} -V 2>&1)"
if [[ ! -e "${KUBE_HOME}/kube-env" ]]; then
echo "The ${KUBE_HOME}/kube-env file does not exist!! Terminate cluster initialization."
exit 1
fi
source "${KUBE_HOME}/kube-env"
if [[ -f "${KUBE_HOME}/kubelet-config.yaml" ]]; then
echo "Found Kubelet config file at ${KUBE_HOME}/kubelet-config.yaml"
KUBELET_CONFIG_FILE_ARG="--config ${KUBE_HOME}/kubelet-config.yaml"
fi
if [[ -e "${KUBE_HOME}/kube-master-certs" ]]; then
source "${KUBE_HOME}/kube-master-certs"
fi
if [[ -n "${KUBE_USER:-}" ]]; then
if ! [[ "${KUBE_USER}" =~ ^[-._@a-zA-Z0-9]+$ ]]; then
echo "Bad KUBE_USER format."
exit 1
fi
fi
KUBE_CONTROLLER_MANAGER_TOKEN="$(secure_random 32)"
KUBE_SCHEDULER_TOKEN="$(secure_random 32)"
KUBE_CLUSTER_AUTOSCALER_TOKEN="$(secure_random 32)"
if [[ "${ENABLE_L7_LOADBALANCING:-}" == "glbc" ]]; then
GCE_GLBC_TOKEN="$(secure_random 32)"
fi
ADDON_MANAGER_TOKEN="$(secure_random 32)"
if [[ "${ENABLE_APISERVER_INSECURE_PORT:-false}" != "true" ]]; then
KUBE_BOOTSTRAP_TOKEN="$(secure_random 32)"
fi
if [[ "${PREPARE_KONNECTIVITY_SERVICE:-false}" == "true" ]]; then
KONNECTIVITY_SERVER_TOKEN="$(secure_random 32)"
fi
if [[ "${ENABLE_MONITORING_TOKEN:-false}" == "true" ]]; then
MONITORING_TOKEN="$(secure_random 32)"
fi
setup-os-params
config-ip-firewall
create-dirs
ensure-local-ssds
setup-kubelet-dir
setup-logrotate
if [[ "${KUBERNETES_MASTER:-}" == "true" ]]; then
mount-master-pd
create-node-pki
create-master-pki
create-master-auth
ensure-master-bootstrap-kubectl-auth
create-master-kubelet-auth
create-master-etcd-auth
create-master-etcd-apiserver-auth
override-pv-recycler
gke-master-start
else
create-node-pki
create-kubelet-kubeconfig "${KUBERNETES_MASTER_NAME}"
if [[ "${KUBE_PROXY_DAEMONSET:-}" != "true" ]] && [[ "${KUBE_PROXY_DISABLE:-}" != "true" ]]; then
create-kubeproxy-user-kubeconfig
fi
if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "standalone" ]]; then
if [[ -n "${NODE_PROBLEM_DETECTOR_TOKEN:-}" ]]; then
create-node-problem-detector-kubeconfig "${KUBERNETES_MASTER_NAME}"
elif [[ -f "/var/lib/kubelet/kubeconfig" ]]; then
create-node-problem-detector-kubeconfig-from-kubelet
else
echo "Either NODE_PROBLEM_DETECTOR_TOKEN or /var/lib/kubelet/kubeconfig must be set"
exit 1
fi
fi
fi
override-kubectl
container_runtime="${CONTAINER_RUNTIME:-docker}"
# Run the containerized mounter once to pre-cache the container image.
if [[ "${container_runtime}" == "docker" ]]; then
assemble-docker-flags
elif [[ "${container_runtime}" == "containerd" ]]; then
if docker-installed; then
# We still need to configure docker so it wouldn't reserver the 172.17.0/16 subnet
# And if somebody will start docker to build or pull something, logging will also be set up
assemble-docker-flags
# stop docker if it is present as we want to use just containerd
systemctl stop docker || echo "unable to stop docker"
fi
setup-containerd
fi
if [[ -n "${KUBE_POD_LOG_READERS_GROUP:-}" ]]; then
mkdir -p /var/log/pods/
chgrp -R "${KUBE_POD_LOG_READERS_GROUP:-}" /var/log/pods/
chmod -R g+s /var/log/pods/
fi
start-kubelet
if [[ "${KUBERNETES_MASTER:-}" == "true" ]]; then
compute-master-manifest-variables
if [[ -z "${ETCD_SERVERS:-}" ]]; then
start-etcd-servers
fi
source ${KUBE_BIN}/configure-kubeapiserver.sh
start-kube-apiserver
if [[ "${RUN_KONNECTIVITY_PODS:-false}" == "true" ]]; then
start-konnectivity-server
fi
start-kube-controller-manager
start-kube-scheduler
wait-till-apiserver-ready
start-kube-addons
start-cluster-autoscaler
start-lb-controller
update-legacy-addon-node-labels &
else
if [[ "${KUBE_PROXY_DAEMONSET:-}" != "true" ]] && [[ "${KUBE_PROXY_DISABLE:-}" != "true" ]]; then
start-kube-proxy
fi
if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "standalone" ]]; then
start-node-problem-detector
fi
fi
reset-motd
prepare-mounter-rootfs
modprobe configs
echo "Done for the configuration for kubernetes"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "${@}"
fi
|
JacobTanenbaum/kubernetes
|
cluster/gce/gci/configure-helper.sh
|
Shell
|
apache-2.0
| 118,961
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function (require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
// exports is for Haml
var constantOtherSymbol = exports.constantOtherSymbol = {
token: "constant.other.symbol.ruby", // symbol
regex: "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"
};
var qString = exports.qString = {
token: "string", // single line
regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
};
var qqString = exports.qqString = {
token: "string", // single line
regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
};
var tString = exports.tString = {
token: "string", // backtick string
regex: "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"
};
var constantNumericHex = exports.constantNumericHex = {
token: "constant.numeric", // hex
regex: "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"
};
var constantNumericFloat = exports.constantNumericFloat = {
token: "constant.numeric", // float
regex: "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"
};
var RubyHighlightRules = function () {
var builtinFunctions = (
"abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" +
"assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" +
"assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" +
"assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" +
"assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" +
"assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" +
"attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" +
"caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" +
"exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" +
"gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" +
"link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" +
"p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" +
"raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" +
"set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" +
"throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" +
"render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" +
"content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" +
"fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" +
"time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" +
"select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" +
"file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" +
"protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" +
"send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" +
"validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" +
"validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" +
"authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" +
"filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" +
"translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" +
"cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" +
"has_many|has_one|belongs_to|has_and_belongs_to_many"
);
var keywords = (
"alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" +
"__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" +
"redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield"
);
var buildinConstants = (
"true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" +
"RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING"
);
var builtinVariables = (
"$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|" +
"$!|root_url|flash|session|cookies|params|request|response|logger|self"
);
var keywordMapper = this.$keywords = this.createKeywordMapper({
"keyword": keywords,
"constant.language": buildinConstants,
"variable.language": builtinVariables,
"support.function": builtinFunctions,
"invalid.deprecated": "debugger" // TODO is this a remnant from js mode?
}, "identifier");
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start": [
{
token: "comment",
regex: "#.*$"
}, {
token: "comment", // multi line comment
regex: "^=begin(?:$|\\s.*$)",
next: "comment"
}, {
token: "string.regexp",
regex: "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
},
[{
regex: "[{}]", onMatch: function (val, state, stack) {
this.next = val == "{" ? this.nextState : "";
if (val == "{" && stack.length) {
stack.unshift("start", state);
return "paren.lparen";
}
if (val == "}" && stack.length) {
stack.shift();
this.next = stack.shift();
if (this.next.indexOf("string") != -1)
return "paren.end";
}
return val == "{" ? "paren.lparen" : "paren.rparen";
},
nextState: "start"
}, {
token: "string.start",
regex: /"/,
push: [{
token: "constant.language.escape",
regex: /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/
}, {
token: "paren.start",
regex: /#{/,
push: "start"
}, {
token: "string.end",
regex: /"/,
next: "pop"
}, {
defaultToken: "string"
}]
}, {
token: "string.start",
regex: /`/,
push: [{
token: "constant.language.escape",
regex: /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/
}, {
token: "paren.start",
regex: /#{/,
push: "start"
}, {
token: "string.end",
regex: /`/,
next: "pop"
}, {
defaultToken: "string"
}]
}, {
token: "string.start",
regex: /'/,
push: [{
token: "constant.language.escape",
regex: /\\['\\]/
}, {
token: "string.end",
regex: /'/,
next: "pop"
}, {
defaultToken: "string"
}]
}],
// TODO: add support for %[QqxWwrs][{[(]
{
token: "text", // namespaces aren't symbols
regex: "::"
}, {
token: "variable.instance", // instance variable
regex: "@{1,2}[a-zA-Z_\\d]+"
}, {
token: "support.class", // class name
regex: "[A-Z][a-zA-Z_\\d]+"
},
constantOtherSymbol,
constantNumericHex,
constantNumericFloat,
{
token: "constant.language.boolean",
regex: "(?:true|false)\\b"
}, {
token: keywordMapper,
// TODO: Unicode escape sequences
// TODO: Unicode identifiers
regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token: "punctuation.separator.key-value",
regex: "=>"
}, {
stateName: "heredoc",
onMatch: function (value, currentState, stack) {
var next = value[2] == '-' ? "indentedHeredoc" : "heredoc";
var tokens = value.split(this.splitRegex);
stack.push(next, tokens[3]);
return [
{type: "constant", value: tokens[1]},
{type: "string", value: tokens[2]},
{type: "support.class", value: tokens[3]},
{type: "string", value: tokens[4]}
];
},
regex: "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)",
rules: {
heredoc: [{
onMatch: function (value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}],
indentedHeredoc: [{
token: "string",
regex: "^ +"
}, {
onMatch: function (value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}]
}
}, {
regex: "$",
token: "empty",
next: function (currentState, stack) {
if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc")
return stack[0];
return currentState;
}
}, {
token: "string.character",
regex: "\\B\\?."
}, {
token: "keyword.operator",
regex: "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token: "paren.lparen",
regex: "[[({]"
}, {
token: "paren.rparen",
regex: "[\\])}]"
}, {
token: "text",
regex: "\\s+"
}
],
"comment": [
{
token: "comment", // closing comment
regex: "^=end(?:$|\\s.*$)",
next: "start"
}, {
token: "comment", // comment spanning whole line
regex: ".+"
}
]
};
this.normalizeRules();
};
oop.inherits(RubyHighlightRules, TextHighlightRules);
exports.RubyHighlightRules = RubyHighlightRules;
});
|
wso2/carbon-analytics
|
components/org.wso2.carbon.siddhi.editor.core/src/main/resources/web/editor/commons/lib/ace-editor/mode/ruby_highlight_rules.js
|
JavaScript
|
apache-2.0
| 15,221
|
<!DOCTYPE html>
<html>
<head>
<title>A6-3我的收藏</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet"/>
<link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/>
<link href="data/styles.css" type="text/css" rel="stylesheet"/>
<link href="files/a6-3我的收藏/styles.css" type="text/css" rel="stylesheet"/>
<script src="resources/scripts/jquery-1.7.1.min.js"></script>
<script src="resources/scripts/jquery-ui-1.8.10.custom.min.js"></script>
<script src="resources/scripts/axure/axQuery.js"></script>
<script src="resources/scripts/axure/globals.js"></script>
<script src="resources/scripts/axutils.js"></script>
<script src="resources/scripts/axure/annotation.js"></script>
<script src="resources/scripts/axure/axQuery.std.js"></script>
<script src="resources/scripts/axure/doc.js"></script>
<script src="data/document.js"></script>
<script src="resources/scripts/messagecenter.js"></script>
<script src="resources/scripts/axure/events.js"></script>
<script src="resources/scripts/axure/recording.js"></script>
<script src="resources/scripts/axure/action.js"></script>
<script src="resources/scripts/axure/expr.js"></script>
<script src="resources/scripts/axure/geometry.js"></script>
<script src="resources/scripts/axure/flyout.js"></script>
<script src="resources/scripts/axure/ie.js"></script>
<script src="resources/scripts/axure/model.js"></script>
<script src="resources/scripts/axure/repeater.js"></script>
<script src="resources/scripts/axure/sto.js"></script>
<script src="resources/scripts/axure/utils.temp.js"></script>
<script src="resources/scripts/axure/variables.js"></script>
<script src="resources/scripts/axure/drag.js"></script>
<script src="resources/scripts/axure/move.js"></script>
<script src="resources/scripts/axure/visibility.js"></script>
<script src="resources/scripts/axure/style.js"></script>
<script src="resources/scripts/axure/adaptive.js"></script>
<script src="resources/scripts/axure/tree.js"></script>
<script src="resources/scripts/axure/init.temp.js"></script>
<script src="files/a6-3我的收藏/data.js"></script>
<script src="resources/scripts/axure/legacy.js"></script>
<script src="resources/scripts/axure/viewer.js"></script>
<script src="resources/scripts/axure/math.js"></script>
<script type="text/javascript">
$axure.utils.getTransparentGifPath = function() { return 'resources/images/transparent.gif'; };
$axure.utils.getOtherPath = function() { return 'resources/Other.html'; };
$axure.utils.getReloadPath = function() { return 'resources/reload.html'; };
</script>
</head>
<body>
<div id="base" class="">
<!-- Unnamed (Group) -->
<div id="u5943" class="ax_default">
<!-- Unnamed (Rectangle) -->
<div id="u5944" class="ax_default shape1">
<div id="u5944_div" class=""></div>
<!-- Unnamed () -->
<div id="u5945" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5946" class="ax_default shape1">
<div id="u5946_div" class=""></div>
<!-- Unnamed () -->
<div id="u5947" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5948" class="ax_default shape1">
<div id="u5948_div" class=""></div>
<!-- Unnamed () -->
<div id="u5949" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5950" class="ax_default shape1">
<div id="u5950_div" class=""></div>
<!-- Unnamed () -->
<div id="u5951" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5952" class="ax_default shape1">
<div id="u5952_div" class=""></div>
<!-- Unnamed () -->
<div id="u5953" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5954" class="ax_default shape1">
<div id="u5954_div" class=""></div>
<!-- Unnamed () -->
<div id="u5955" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5956" class="ax_default shape1">
<div id="u5956_div" class=""></div>
<!-- Unnamed () -->
<div id="u5957" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5958" class="ax_default shape1">
<div id="u5958_div" class=""></div>
<!-- Unnamed () -->
<div id="u5959" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5960" class="ax_default shape1">
<div id="u5960_div" class=""></div>
<!-- Unnamed () -->
<div id="u5961" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
</div>
<!-- Unnamed (Drop) -->
<div id="u5962" class="ax_default">
<img id="u5962_img" class="img " src="images/a3首页/u912.png"/>
<!-- Unnamed () -->
<div id="u5963" class="text" style="visibility: visible;">
<p><span>1</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5964" class="ax_default label">
<div id="u5964_div" class=""></div>
<!-- Unnamed () -->
<div id="u5965" class="text" style="visibility: visible;">
<p><span>点击编辑进行取消操作,点击后底部显示操作栏,编辑按钮变为取消按钮;取消收藏需要进行二次确认,使用弹框提醒;</span></p>
</div>
</div>
<!-- Unnamed (Ellipse) -->
<div id="u5966" class="ax_default">
<img id="u5966_img" class="img " src="images/a3首页/u916.png"/>
<!-- Unnamed () -->
<div id="u5967" class="text" style="visibility: visible;">
<p><span>1</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5968" class="ax_default">
<div id="u5968_div" class=""></div>
<!-- Unnamed () -->
<div id="u5969" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Group) -->
<div id="u5970" class="ax_default">
</div>
<!-- Unnamed (Group) -->
<div id="u5971" class="ax_default">
</div>
<!-- Unnamed (Image) -->
<div id="u5972" class="ax_default image1">
<img id="u5972_img" class="img " src="images/a1登录/u524.png"/>
<!-- Unnamed () -->
<div id="u5973" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5974" class="ax_default label">
<div id="u5974_div" class=""></div>
<!-- Unnamed () -->
<div id="u5975" class="text" style="visibility: visible;">
<p><span>我的收藏</span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u5976" class="ax_default">
<img id="u5976_img" class="img " src="images/a1登录/u562.png"/>
<!-- Unnamed () -->
<div id="u5977" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5978" class="ax_default _文本段落">
<div id="u5978_div" class=""></div>
<!-- Unnamed () -->
<div id="u5979" class="text" style="visibility: visible;">
<p><span>编辑</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5980" class="ax_default _形状1">
<div id="u5980_div" class=""></div>
<!-- Unnamed () -->
<div id="u5981" class="text" style="visibility: visible;">
<p><span>课程</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5982" class="ax_default _形状1">
<div id="u5982_div" class=""></div>
<!-- Unnamed () -->
<div id="u5983" class="text" style="visibility: visible;">
<p><span>老师</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5984" class="ax_default box_2">
<div id="u5984_div" class=""></div>
<!-- Unnamed () -->
<div id="u5985" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Radio Button) -->
<div id="u5986" class="ax_default radio_button">
<label for="u5986_input">
<!-- Unnamed () -->
<div id="u5987" class="text" style="visibility: visible;">
<p><span>全选</span></p>
</div>
</label>
<input id="u5986_input" type="radio" value="radio" name="u5986"/>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5988" class="ax_default label">
<div id="u5988_div" class=""></div>
<!-- Unnamed () -->
<div id="u5989" class="text" style="visibility: visible;">
<p><span>取消收藏</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5990" class="ax_default label">
<div id="u5990_div" class=""></div>
<!-- Unnamed () -->
<div id="u5991" class="text" style="visibility: visible;">
<p><span>点击编辑</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5992" class="ax_default label">
<div id="u5992_div" class=""></div>
<!-- Unnamed () -->
<div id="u5993" class="text" style="visibility: visible;">
<p><span>弹框提醒</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5994" class="ax_default shape1">
<div id="u5994_div" class=""></div>
<!-- Unnamed () -->
<div id="u5995" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Horizontal Line) -->
<div id="u5996" class="ax_default horizontal_line">
<img id="u5996_img" class="img " src="images/a3-1__/u1334.png"/>
<!-- Unnamed () -->
<div id="u5997" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u5998" class="ax_default paragraph1">
<div id="u5998_div" class=""></div>
<!-- Unnamed () -->
<div id="u5999" class="text" style="visibility: visible;">
<p><span>取消</span></p>
</div>
</div>
<!-- Unnamed (Vertical Line) -->
<div id="u6000" class="ax_default vertical_line">
<img id="u6000_img" class="img " src="images/a3-1__/u1338.png"/>
<!-- Unnamed () -->
<div id="u6001" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6002" class="ax_default paragraph1">
<div id="u6002_div" class=""></div>
<!-- Unnamed () -->
<div id="u6003" class="text" style="visibility: visible;">
<p><span>确认</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6004" class="ax_default paragraph1">
<div id="u6004_div" class=""></div>
<!-- Unnamed () -->
<div id="u6005" class="text" style="visibility: visible;">
<p><span>取消收藏</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6006" class="ax_default paragraph1">
<div id="u6006_div" class=""></div>
<!-- Unnamed () -->
<div id="u6007" class="text" style="visibility: visible;">
<p><span>所选收藏内容将会删除</span></p>
</div>
</div>
<!-- Unnamed (Drop) -->
<div id="u6008" class="ax_default">
<img id="u6008_img" class="img " src="images/a3首页/u912.png"/>
<!-- Unnamed () -->
<div id="u6009" class="text" style="visibility: visible;">
<p><span>2</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6010" class="ax_default label">
<div id="u6010_div" class=""></div>
<!-- Unnamed () -->
<div id="u6011" class="text" style="visibility: visible;">
<p><span>点击进行切换,教师列表项样式如下:</span></p>
</div>
</div>
<!-- Unnamed (Ellipse) -->
<div id="u6012" class="ax_default">
<img id="u6012_img" class="img " src="images/a3首页/u916.png"/>
<!-- Unnamed () -->
<div id="u6013" class="text" style="visibility: visible;">
<p><span>2</span></p>
</div>
</div>
<!-- Unnamed (A_Teacher List) -->
<!-- Unnamed (Rectangle) -->
<div id="u6015" class="ax_default box_2">
<div id="u6015_div" class=""></div>
<!-- Unnamed () -->
<div id="u6016" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6017" class="ax_default box_1">
<div id="u6017_div" class=""></div>
<!-- Unnamed () -->
<div id="u6018" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Triangle) -->
<div id="u6019" class="ax_default box_3">
<img id="u6019_img" class="img " src="images/a3首页/u1103.png"/>
<!-- Unnamed () -->
<div id="u6020" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Triangle) -->
<div id="u6021" class="ax_default box_3">
<img id="u6021_img" class="img " src="images/a3首页/u1105.png"/>
<!-- Unnamed () -->
<div id="u6022" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Ellipse) -->
<div id="u6023" class="ax_default box_3">
<img id="u6023_img" class="img " src="images/a3首页/u1107.png"/>
<!-- Unnamed () -->
<div id="u6024" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6025" class="ax_default label">
<div id="u6025_div" class=""></div>
<!-- Unnamed () -->
<div id="u6026" class="text" style="visibility: visible;">
<p><span>教师名称</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6027" class="ax_default label">
<div id="u6027_div" class=""></div>
<!-- Unnamed () -->
<div id="u6028" class="text" style="visibility: visible;">
<p><span>语文中考提分高手,十年教龄的优质老师。</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6029" class="ax_default label">
<div id="u6029_div" class=""></div>
<!-- Unnamed () -->
<div id="u6030" class="text" style="visibility: visible;">
<p><span>180人收藏 56条评价</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6031" class="ax_default label">
<div id="u6031_div" class=""></div>
<!-- Unnamed () -->
<div id="u6032" class="text" style="visibility: visible;">
<p><span>评分:4.0</span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6033" class="ax_default image">
<img id="u6033_img" class="img " src="images/a3首页/u1117.png"/>
<!-- Unnamed () -->
<div id="u6034" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6035" class="ax_default image">
<img id="u6035_img" class="img " src="images/a3首页/u1117.png"/>
<!-- Unnamed () -->
<div id="u6036" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6037" class="ax_default image">
<img id="u6037_img" class="img " src="images/a3首页/u1117.png"/>
<!-- Unnamed () -->
<div id="u6038" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6039" class="ax_default image">
<img id="u6039_img" class="img " src="images/a3首页/u1117.png"/>
<!-- Unnamed () -->
<div id="u6040" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6041" class="ax_default image">
<img id="u6041_img" class="img " src="images/a3首页/u1125.png"/>
<!-- Unnamed () -->
<div id="u6042" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6043" class="ax_default box_1">
<div id="u6043_div" class=""></div>
<!-- Unnamed () -->
<div id="u6044" class="text" style="visibility: visible;">
<p><span>风趣幽默</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6045" class="ax_default box_1">
<div id="u6045_div" class=""></div>
<!-- Unnamed () -->
<div id="u6046" class="text" style="visibility: visible;">
<p><span>经验丰富</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6047" class="ax_default box_1">
<div id="u6047_div" class=""></div>
<!-- Unnamed () -->
<div id="u6048" class="text" style="visibility: visible;">
<p><span>我手写我心</span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6049" class="ax_default image">
<img id="u6049_img" class="img " src="images/a3首页/u1133.png"/>
<!-- Unnamed () -->
<div id="u6050" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (A_Class Card List Child) -->
<!-- Unnamed (Rectangle) -->
<div id="u6052" class="ax_default box_2">
<div id="u6052_div" class=""></div>
<!-- Unnamed () -->
<div id="u6053" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6054" class="ax_default box_31">
<div id="u6054_div" class=""></div>
<!-- Unnamed () -->
<div id="u6055" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6056" class="ax_default label">
<div id="u6056_div" class=""></div>
<!-- Unnamed () -->
<div id="u6057" class="text" style="visibility: visible;">
<p><span>钟家村教学区 JPHD3001</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6058" class="ax_default label">
<div id="u6058_div" class=""></div>
<!-- Unnamed () -->
<div id="u6059" class="text" style="visibility: visible;">
<p><span>2016-09-12开课,每周六18:00-20:00上课</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6060" class="ax_default label">
<div id="u6060_div" class=""></div>
<!-- Unnamed () -->
<div id="u6061" class="text" style="visibility: visible;">
<p><span>百树桃源校区 班级教室号信息</span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6062" class="ax_default image">
<img id="u6062_img" class="img " src="images/a3首页/u1045.png"/>
<!-- Unnamed () -->
<div id="u6063" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6064" class="ax_default label">
<div id="u6064_div" class=""></div>
<!-- Unnamed () -->
<div id="u6065" class="text" style="visibility: visible;">
<p><span>25人班,已报20人,还剩5人</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6066" class="ax_default link_button">
<div id="u6066_div" class=""></div>
<!-- Unnamed () -->
<div id="u6067" class="text" style="visibility: visible;">
<p><span>详情</span></p>
</div>
</div>
<!-- 删除价 (Group) -->
<div id="u6068" class="ax_default" data-label="删除价">
<!-- Unnamed (Rectangle) -->
<div id="u6069" class="ax_default label">
<div id="u6069_div" class=""></div>
<!-- Unnamed () -->
<div id="u6070" class="text" style="visibility: visible;">
<p><span>¥1200.00</span></p>
</div>
</div>
<!-- Unnamed (Horizontal Line) -->
<div id="u6071" class="ax_default line">
<img id="u6071_img" class="img " src="images/a3首页/u1054.png"/>
<!-- Unnamed () -->
<div id="u6072" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6073" class="ax_default label">
<div id="u6073_div" class=""></div>
<!-- Unnamed () -->
<div id="u6074" class="text" style="visibility: visible;">
<p><span>¥520.00</span></p>
</div>
</div>
<!-- Unnamed (A_Class Card List Child) -->
<!-- Unnamed (Rectangle) -->
<div id="u6076" class="ax_default box_2">
<div id="u6076_div" class=""></div>
<!-- Unnamed () -->
<div id="u6077" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6078" class="ax_default box_31">
<div id="u6078_div" class=""></div>
<!-- Unnamed () -->
<div id="u6079" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6080" class="ax_default label">
<div id="u6080_div" class=""></div>
<!-- Unnamed () -->
<div id="u6081" class="text" style="visibility: visible;">
<p><span>钟家村教学区 JPHD3001</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6082" class="ax_default label">
<div id="u6082_div" class=""></div>
<!-- Unnamed () -->
<div id="u6083" class="text" style="visibility: visible;">
<p><span>2016-09-12开课,每周六18:00-20:00上课</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6084" class="ax_default label">
<div id="u6084_div" class=""></div>
<!-- Unnamed () -->
<div id="u6085" class="text" style="visibility: visible;">
<p><span>百树桃源校区 班级教室号信息</span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6086" class="ax_default image">
<img id="u6086_img" class="img " src="images/a3首页/u1045.png"/>
<!-- Unnamed () -->
<div id="u6087" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6088" class="ax_default label">
<div id="u6088_div" class=""></div>
<!-- Unnamed () -->
<div id="u6089" class="text" style="visibility: visible;">
<p><span>25人班,已报20人,还剩5人</span></p>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6090" class="ax_default link_button">
<div id="u6090_div" class=""></div>
<!-- Unnamed () -->
<div id="u6091" class="text" style="visibility: visible;">
<p><span>详情</span></p>
</div>
</div>
<!-- 删除价 (Group) -->
<div id="u6092" class="ax_default" data-label="删除价">
<!-- Unnamed (Rectangle) -->
<div id="u6093" class="ax_default label">
<div id="u6093_div" class=""></div>
<!-- Unnamed () -->
<div id="u6094" class="text" style="visibility: visible;">
<p><span>¥1200.00</span></p>
</div>
</div>
<!-- Unnamed (Horizontal Line) -->
<div id="u6095" class="ax_default line">
<img id="u6095_img" class="img " src="images/a3首页/u1054.png"/>
<!-- Unnamed () -->
<div id="u6096" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
</div>
<!-- Unnamed (Rectangle) -->
<div id="u6097" class="ax_default label">
<div id="u6097_div" class=""></div>
<!-- Unnamed () -->
<div id="u6098" class="text" style="visibility: visible;">
<p><span>¥520.00</span></p>
</div>
</div>
<!-- Unnamed (Radio Button) -->
<div id="u6099" class="ax_default radio_button">
<label for="u6099_input">
<!-- Unnamed () -->
<div id="u6100" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</label>
<input id="u6099_input" type="radio" value="radio" name="u6099"/>
</div>
<!-- Unnamed (Image) -->
<div id="u6101" class="ax_default image">
<img id="u6101_img" class="img " src="images/a6-3我的收藏/u6101.png"/>
<!-- Unnamed () -->
<div id="u6102" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
<!-- Unnamed (Image) -->
<div id="u6103" class="ax_default image">
<img id="u6103_img" class="img " src="images/a6-3我的收藏/u6103.png"/>
<!-- Unnamed () -->
<div id="u6104" class="text" style="display: none; visibility: hidden">
<p><span></span></p>
</div>
</div>
</div>
</body>
</html>
|
yicold/axure-case
|
100treeedu/a6-3我的收藏.html
|
HTML
|
apache-2.0
| 27,863
|
# Cercospora dalbergiae-latifoliae Chidd. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Sydowia 13: 158 (1959)
#### Original name
Cercospora dalbergiae-latifoliae Chidd.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Cercospora/Cercospora dalbergiae-latifoliae/README.md
|
Markdown
|
apache-2.0
| 225
|
# Russula furcata f. subtomentosa (Cern. & H. Raab) H. Raab FORM
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Sydowia 10(1-6): 191 (1957)
#### Original name
Russula subtomentosa Cern. & H. Raab
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Russulaceae/Russula/Russula cyanoxantha/Russula furcata subtomentosa/README.md
|
Markdown
|
apache-2.0
| 242
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.appeligo.fliptv.simulator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
public class KeywordSimulator {
private Date startTime;
private Date endTime;
private String listenerEndpoint = "http://localhost:8080/fliptv/internal/keywordListener";
private String demoOffsetEndpoint = "http://localhost:8080/fliptv/demo/offset.action?startDemo=true&deleteSearch=41";
public String getListenerEndpoint() {
return listenerEndpoint;
}
public void setListenerEndpoint(String listenerEndpoint) {
this.listenerEndpoint = listenerEndpoint;
}
/**
* @return Returns the demoOffsetEndpoint.
*/
public String getDemoOffsetEndpoint() {
return demoOffsetEndpoint;
}
/**
* @param demoOffsetEndpoint The demoOffsetEndpoint to set.
*/
public void setDemoOffsetEndpoint(String demoOffsetEndpoint) {
this.demoOffsetEndpoint = demoOffsetEndpoint;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public void export() throws IOException {
System.out.println("Start: " + startTime);
System.out.println("End: " + endTime);
System.err.println("Feature not implemented yet.");
}
public void play(File file) throws MalformedURLException {
if (file == null) {
System.err.println("You must specify a file.");
printHelp();
}
if (!file.isFile()) {
System.err.println("The file does not exist: " + file);
printHelp();
}
ScriptPlayer player = new ScriptPlayer(this, file);
player.start();
}
public static void printHelp() {
System.out.println("Usage: java com.appeligo.fliptv.simulator.KeywordSimulator -[e] [options] <file>");
System.out.println(" -e <start> <end>: exports a script for a certain time period. Dates ");
System.out.println(" must be in the format: yyyy-MM-dd'T'HH:mm:ss (ex. 2007-06-25T12:08:56)");
System.out.println(" -h <server>: Specify the hostname to connect to (default: localhost)");
System.out.println(" -p <port>: Specify the port to connect to (default: 8080)");
System.out.println(" --help : prints out the help screen");
System.exit(0);
}
public static void main(String[] args) throws Exception {
// if (sendOffset) {
// try {
// URL url = new URL("http://localhost:80/fliptv/demo/offset.action?startDemo=true&deleteSearch=41");
// URLConnection connect = url.openConnection();
// connect.connect();
// InputStream stream = connect.getInputStream();
// stream.close();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// System.exit(0);
// } catch (IOException e) {
// e.printStackTrace();
// System.exit(0);
// }
// }
KeywordSimulator sim = new KeywordSimulator();
boolean export = false;
File file = null;
String arg;
String host = "localhost";
String port = "8080";
for (int i=0; i < args.length; i++) {
arg = args[i];
if ("--help".equals(arg)) {
printHelp();
} else if ("-e".equals(arg)) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
if (i+2 >= args.length) {
System.err.println("You must specify a start and end date.");
printHelp();
}
sim.setStartTime(df.parse(args[++i]));
sim.setEndTime(df.parse(args[++i]));
export = true;
} else if ("-h".equals(arg)) {
host = args[++i];
} else if ("-p".equals(arg)) {
port = args[++i];
} else {
if (file != null) {
printHelp();
}
file = new File(arg);
}
}
sim.setListenerEndpoint("http://" + host + ":" + port + "/fliptv/internal/keywordListener");
sim.setDemoOffsetEndpoint("http://" + host + ":" + port + "/fliptv/demo/offset.action?startDemo=true&deleteSearch=41");
if (export) {
sim.export();
} else {
sim.play(file);
}
}
}
|
richkadel/flip.tv
|
kwsim/src/main/java/com/appeligo/fliptv/simulator/KeywordSimulator.java
|
Java
|
apache-2.0
| 5,771
|
/**
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openengsb.parser.csharp.reader;
import java.io.IOException;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.List;
import org.openengsb.parser.csharp.structure.CType;
/**
* @author peter
*
*/
public interface Reader {
public void initialize(String configFile, URLClassLoader loader) throws IOException;
public Collection<CType<?>> process();
public List<String> getErrors();
}
|
frenzqse/loom-csharp-parser
|
src/main/java/org/openengsb/parser/csharp/reader/Reader.java
|
Java
|
apache-2.0
| 1,265
|
/*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.guvnor.common.services.backend.cache;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.uberfire.commons.validation.PortablePreconditions;
/**
* A simple LRU cache keyed on Paths
*/
public abstract class LRUCache<Path, V> implements Cache<Path, V> {
private static final int MAX_ENTRIES = 20;
private Map<Path, V> cache;
public LRUCache() {
cache = new LinkedHashMap<Path, V>(MAX_ENTRIES + 1,
0.75f,
true) {
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
};
cache = (Map) Collections.synchronizedMap(cache);
}
@Override
public V getEntry(final Path path) {
PortablePreconditions.checkNotNull("path",
path);
return cache.get(path);
}
@Override
public void setEntry(final Path path,
final V value) {
PortablePreconditions.checkNotNull("path",
path);
PortablePreconditions.checkNotNull("value",
value);
cache.put(path,
value);
}
@Override
public void invalidateCache() {
this.cache.clear();
}
@Override
public void invalidateCache(final Path path) {
PortablePreconditions.checkNotNull("path",
path);
this.cache.remove(path);
}
public Set<Path> getKeys() {
return cache.keySet();
}
}
|
adrielparedes/guvnor
|
guvnor-services/guvnor-services-api/src/main/java/org/guvnor/common/services/backend/cache/LRUCache.java
|
Java
|
apache-2.0
| 2,340
|
package org.example.domain.query.assoc;
import io.ebean.typequery.PLong;
import io.ebean.typequery.PString;
import io.ebean.typequery.PTimestamp;
import io.ebean.typequery.TQAssocBean;
import io.ebean.typequery.TQProperty;
import io.ebean.typequery.TypeQueryBean;
import org.example.domain.Contact;
import org.example.domain.query.QContact;
/**
* Association query bean for AssocContact.
*
* THIS IS A GENERATED OBJECT, DO NOT MODIFY THIS CLASS.
*/
@TypeQueryBean
public class QAssocContact<R> extends TQAssocBean<Contact,R> {
public PLong<R> id;
public PLong<R> version;
public PTimestamp<R> whenCreated;
public PTimestamp<R> whenUpdated;
public PString<R> firstName;
public PString<R> lastName;
public PString<R> email;
public PString<R> phone;
public QAssocCustomer<R> customer;
public QAssocContactNote<R> notes;
/**
* Eagerly fetch this association loading the specified properties.
*/
@SafeVarargs
public final R fetch(TQProperty<QContact>... properties) {
return fetchProperties(properties);
}
public QAssocContact(String name, R root) {
super(name, root);
}
}
|
ebean-orm/avaje-ebeanorm-typequery-generator
|
src/test/java/org/example/domain/query/assoc/QAssocContact.java
|
Java
|
apache-2.0
| 1,124
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
/**
* CacheFactory
*/
@SPI("lru")
public interface CacheFactory {
@Adaptive("cache")
Cache getCache(URL url, Invocation invocation);
}
|
JasonHZXie/dubbo
|
dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java
|
Java
|
apache-2.0
| 1,189
|
package com.deliveredtechnologies.rulebook.model.runner.test.rulebooks.subpkg;
import com.deliveredtechnologies.rulebook.Fact;
import com.deliveredtechnologies.rulebook.FactMap;
import com.deliveredtechnologies.rulebook.RuleState;
import com.deliveredtechnologies.rulebook.annotation.Rule;
import com.deliveredtechnologies.rulebook.annotation.Given;
import com.deliveredtechnologies.rulebook.annotation.When;
import com.deliveredtechnologies.rulebook.annotation.Then;
import com.deliveredtechnologies.rulebook.annotation.Result;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
/**
* Sample POJO rule with facts and a result.
*/
@Rule(order = 2, name = "Result Rule")
public class SampleRuleWithResult {
@Given("fact1")
private Fact<String> _fact1;
@Given("fact2")
private Fact<String> _fact2;
@Given
private List<String> _strList;
@Given
private Map<String, String> _strMap;
@Given
private Set<String> _strSet;
@Given
private Queue<String> _queue;
@Given
private FactMap<String> _factMap;
@Given("value1")
private int _value1;
@Given
private Set<Integer> _valueSet;
@Given
private List<Integer> _valueList;
@Given
private Map<String, Integer> _valueMap;
@Result
private String _result;
@When
public boolean when() {
return _fact1.getValue().equals(_fact2.getValue());
}
/**
* Method then() performs the rule's action.
* @return RuleState.NEXT to continue to the next rule in the chain
*/
@Then
public RuleState then() {
_fact2.setValue("So Factual Too!");
_fact1.setValue("So Factual Too!");
_result = _result != null && (_result.equals("default") || _result.equals("Equivalence Default"))
? "Equivalence Default" : "Equivalence, Bitches!";
return RuleState.NEXT;
}
public String getFact1() {
return _fact1.getValue();
}
public String getFact2() {
return _fact2.getValue();
}
public List<String> getStrList() {
return _strList;
}
public Set<String> getStrSet() {
return _strSet;
}
public Map<String, String> getStrMap() {
return _strMap;
}
public FactMap<String> getFactMap() {
return _factMap;
}
public int getValue1() {
return _value1;
}
public Set<Integer> getValueSet() {
return _valueSet;
}
public List<Integer> getValueList() {
return _valueList;
}
public Map<String, Integer> getValueMap() {
return _valueMap;
}
public String getResult() {
return _result;
}
public Queue<String> getQueue() {
return _queue;
}
}
|
rulebook-rules/rulebook
|
rulebook-core/src/test/java/com/deliveredtechnologies/rulebook/model/runner/test/rulebooks/subpkg/SampleRuleWithResult.java
|
Java
|
apache-2.0
| 2,588
|
/**
* 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.
*/
/**
* 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
* <p>
* 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.pires.obd.exceptions;
/**
* Thrown when there is "ERROR" in the response
*/
public class UnknownObdErrorException extends ObdResponseException {
public UnknownObdErrorException() {
super("ERROR");
}
}
|
mikes01/obd-java-api
|
src/main/java/com/github/pires/obd/exceptions/UnknownObdErrorException.java
|
Java
|
apache-2.0
| 1,361
|
# Carex littoralis Petrie SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex litorosa/ Syn. Carex littoralis/README.md
|
Markdown
|
apache-2.0
| 180
|
// Copyright 2003-2004 DigitalCraftsmen - http://www.digitalcraftsmen.com.br/
//
// 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.
namespace Castle.ManagementExtensions.Test
{
using System;
using NUnit.Framework;
using Castle.ManagementExtensions.Default;
using Castle.ManagementExtensions.Test.Components;
/// <summary>
/// Summary description for InterfacedComponentTestCase.
/// </summary>
[TestFixture]
public class InterfacedComponentTestCase : Assertion
{
[Test]
public void TestInfoObtation()
{
MDefaultServer server = new MDefaultServer();
ManagedObjectName name1 = new ManagedObjectName("domain.org:type=dummyService");
try
{
Type serviceType = typeof(DummyService);
Object service = server.Instantiate( serviceType.Assembly.FullName, serviceType.FullName );
server.RegisterManagedObject( service, name1 );
ManagementInfo info = server.GetManagementInfo( name1 );
AssertNotNull( info );
AssertEquals( 1, info.Operations.Count );
AssertEquals( 1, info.Attributes.Count );
}
finally
{
server.UnregisterManagedObject( name1 );
}
}
}
}
|
castleproject/castle-READONLY-SVN-dump
|
Experiments/Attic/ManagedExtensions/ManagementExtensionsTest/InterfacedComponentTestCase.cs
|
C#
|
apache-2.0
| 1,632
|
# Hebanthe Mart. GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Hebanthe/README.md
|
Markdown
|
apache-2.0
| 162
|
/*
* Copyright 2014 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.way.gdrive;
import br.com.objectos.core.lang.Builder;
import com.google.inject.Module;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
public class WayGDriveModuleBuilder implements Builder<Module> {
private String accessToken;
private String refreshToken;
@Override
public Module build() {
GDriveTokens tokens = new GDriveTokens(accessToken, refreshToken);
return new WayGDriveModule(tokens);
}
public WayGDriveModuleBuilder accessToken(String accessToken) {
this.accessToken = accessToken;
return this;
}
public WayGDriveModuleBuilder refreshToken(String refreshToken) {
this.refreshToken = refreshToken;
return this;
}
}
|
objectos/gdrive
|
src/main/java/br/com/objectos/way/gdrive/WayGDriveModuleBuilder.java
|
Java
|
apache-2.0
| 1,313
|
# Copyright (c) 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.test import attr
from tempest_lib import exceptions
from murano_tempest_tests.tests.api.application_catalog import base
from murano_tempest_tests import utils
class TestEnvironmentsNegative(base.BaseApplicationCatalogTest):
@attr(type='negative')
def test_delete_environment_with_wrong_env_id(self):
self.assertRaises(exceptions.NotFound,
self.application_catalog_client.delete_environment,
utils.generate_uuid())
@attr(type='negative')
def test_double_delete_environment(self):
name = utils.generate_name('double_del_negavive')
environment = self.application_catalog_client.\
create_environment(name)
self.application_catalog_client.delete_environment(environment['id'])
self.assertRaises(exceptions.NotFound,
self.application_catalog_client.delete_environment,
environment['id'])
@attr(type='negative')
def test_get_deleted_environment(self):
name = utils.generate_name('double_del_negavive')
environment = self.application_catalog_client.\
create_environment(name)
self.application_catalog_client.delete_environment(environment['id'])
self.assertRaises(exceptions.NotFound,
self.application_catalog_client.get_environment,
environment['id'])
class TestEnvironmentNegativeTenantIsolation(base.BaseApplicationCatalogTest):
@classmethod
def resource_setup(cls):
super(TestEnvironmentNegativeTenantIsolation, cls).resource_setup()
name = utils.generate_name(cls.__name__)
cls.environment = cls.application_catalog_client.\
create_environment(name)
cls.alt_client = cls.get_client_with_isolated_creds(
type_of_creds='alt')
@classmethod
def resource_cleanup(cls):
cls.application_catalog_client.\
delete_environment(cls.environment['id'])
super(TestEnvironmentNegativeTenantIsolation, cls).resource_cleanup()
@attr(type='negative')
def test_get_environment_from_another_tenant(self):
self.assertRaises(exceptions.Forbidden,
self.alt_client.get_environment,
self.environment['id'])
@attr(type='negative')
def test_update_environment_from_another_tenant(self):
self.assertRaises(exceptions.Forbidden,
self.alt_client.update_environment,
self.environment['id'])
@attr(type='negative')
def test_delete_environment_from_another_tenant(self):
self.assertRaises(exceptions.Forbidden,
self.alt_client.delete_environment,
self.environment['id'])
|
olivierlemasle/murano
|
murano_tempest_tests/tests/api/application_catalog/test_environments_negative.py
|
Python
|
apache-2.0
| 3,454
|
package io.leopard.javahost.impl;
import io.leopard.javahost.Hosts;
import io.leopard.javahost.model.Host;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Hosts文件解析抽象实现.
*
* @author 阿海
*
*/
public abstract class AbstractHosts implements Hosts {
/**
* 获取hosts文件路径.
*
* @return hosts文件路径
*/
protected String getHostsPath() {
String path;
if (System.getProperty("os.name").startsWith("Windows")) {
path = "c:/windows/System32/drivers/etc/hosts";
}
else {
path = "/etc/hosts";
}
return path;
}
/**
* 读取hosts文件内容.
*
* @return hosts文件内容
* @throws IOException
*/
protected String readHostsFile() throws IOException {
String path = this.getHostsPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
protected List<Host> parseLine(String line) {
line = line.trim();
line = line.replaceFirst("#.*$", "");// 过滤注释
List<Host> list = new ArrayList<Host>();
if (line.length() == 0) {
return list;
}
String[] hosts = line.split("\\s+");
if (hosts.length < 2) {
throw new RuntimeException("非法host记录[" + line + "].");
}
for (int i = 1; i < hosts.length; i++) {
Host host = new Host();
host.setIp(hosts[0]);
host.setHost(hosts[i]);
list.add(host);
}
return list;
}
}
|
tanhaichao/javahost
|
src/main/java/io/leopard/javahost/impl/AbstractHosts.java
|
Java
|
apache-2.0
| 1,628
|
# Desmotheca S.O. Lindberg, 1873 GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Bryophyta/Bryopsida/Orthotrichales/Orthotrichaceae/Desmotheca/README.md
|
Markdown
|
apache-2.0
| 186
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.rya.mongodb.document.operators.aggregation;
import static org.apache.rya.mongodb.document.operators.aggregation.PipelineOperators.redact;
import static org.apache.rya.mongodb.document.operators.aggregation.SetOperators.anyElementTrue;
import static org.apache.rya.mongodb.document.operators.aggregation.SetOperators.setIsSubsetNullSafe;
import static org.apache.rya.mongodb.document.operators.aggregation.VariableOperators.map;
import static org.apache.rya.mongodb.document.operators.query.ArrayOperators.size;
import static org.apache.rya.mongodb.document.operators.query.ComparisonOperators.eq;
import static org.apache.rya.mongodb.document.operators.query.LogicalOperators.or;
import java.util.ArrayList;
import java.util.List;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.rya.mongodb.MongoDbRdfConstants;
import org.apache.rya.mongodb.dao.SimpleMongoDBStorageStrategy;
import org.apache.rya.mongodb.document.operators.aggregation.PipelineOperators.RedactAggregationResult;
import org.apache.rya.mongodb.document.util.AuthorizationsUtil;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Utility methods for MongoDB aggregation.
*/
public final class AggregationUtil {
/**
* Private constructor to prevent instantiation.
*/
private AggregationUtil() {
}
/**
* Creates a MongoDB $redact aggregation pipeline that only include
* documents whose document visibility match the provided authorizations.
* All other documents are excluded.
* @param authorizations the {@link Authorization}s to include in the
* $redact. Only documents that match the authorizations will be returned.
* @return the {@link List} of {@link DBObject}s that represents the $redact
* aggregation pipeline.
*/
public static List<DBObject> createRedactPipeline(final Authorizations authorizations) {
if (MongoDbRdfConstants.ALL_AUTHORIZATIONS.equals(authorizations)) {
return Lists.newArrayList();
}
final List<String> authList = AuthorizationsUtil.getAuthorizationsStrings(authorizations);
final String documentVisibilityField = "$" + SimpleMongoDBStorageStrategy.DOCUMENT_VISIBILITY;
final String mapVariableCursorName = "dvItemCursorTag";
final BasicDBObject anyElementTrue =
anyElementTrue(
map(
documentVisibilityField,
mapVariableCursorName,
setIsSubsetNullSafe(
"$$" + mapVariableCursorName,
authList.toArray()
)
)
);
// If the field is empty then there are no authorizations required,
// so all users should be able to view it when they query.
final BasicDBObject isFieldSizeZero =
eq(
size(documentVisibilityField),
0
);
final BasicDBObject orExpression = or(anyElementTrue, isFieldSizeZero);
final List<DBObject> pipeline = new ArrayList<>();
pipeline.add(
redact(
orExpression,
RedactAggregationResult.DESCEND,
RedactAggregationResult.PRUNE
)
);
return pipeline;
}
}
|
pujav65/incubator-rya
|
dao/mongodb.rya/src/main/java/org/apache/rya/mongodb/document/operators/aggregation/AggregationUtil.java
|
Java
|
apache-2.0
| 4,191
|
// Copyright 2021 gRPC 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.
#include <android/binder_auto_utils.h>
#include <android/binder_ibinder.h>
#include <android/binder_ibinder_jni.h>
#include <android/binder_interface_utils.h>
#include <android/log.h>
#include <grpcpp/grpcpp.h>
#include <jni.h>
#include "examples/protos/helloworld.grpc.pb.h"
#include "examples/protos/helloworld.pb.h"
// TODO(mingcl): Uncomment this after server interfaces are merged
// #include "src/core/ext/transport/binder/server/binder_server.h"
// #include "src/core/ext/transport/binder/server/binder_server_credentials.h"
namespace {
class GreeterService : public helloworld::Greeter::Service {
public:
grpc::Status SayHello(grpc::ServerContext*,
const helloworld::HelloRequest* request,
helloworld::HelloReply* response) override {
__android_log_print(ANDROID_LOG_INFO, "DemoServer", "Line number %d",
__LINE__);
__android_log_print(ANDROID_LOG_INFO, "DemoServer", "Got hello request: %s",
request->name().c_str());
response->set_message("Hi, " + request->name());
return grpc::Status::OK;
}
};
} // namespace
extern "C" JNIEXPORT void JNICALL
Java_io_grpc_binder_cpp_exampleserver_ExportedEndpointService_init_1grpc_1server(
JNIEnv* env, jobject /*this*/) {
__android_log_print(ANDROID_LOG_INFO, "DemoServer", "Line number %d",
__LINE__);
static std::unique_ptr<grpc::Server> server = nullptr;
if (server != nullptr) {
// Already initiated
return;
}
static GreeterService service;
grpc::ServerBuilder server_builder;
server_builder.RegisterService(&service);
// TODO(mingcl): Uncomment this after server interfaces are merged
//
// grpc_endpoint_binder_pool_init();
// server_builder.AddListeningPort("binder://example.service",
// grpc::experimental::BinderServerCredentials());
server = server_builder.BuildAndStart();
}
extern "C" JNIEXPORT jobject JNICALL
Java_io_grpc_binder_cpp_exampleserver_ExportedEndpointService_get_1endpoint_1binder(
JNIEnv* env, jobject /*this*/) {
__android_log_print(ANDROID_LOG_INFO, "DemoServer", "Line number %d",
__LINE__);
// TODO(mingcl): Uncomment this after server interfaces are merged
// auto ai_binder =
// static_cast<AIBinder*>(grpc::experimental::binder::GetEndpointBinder("example.service"));
AIBinder* ai_binder = nullptr;
__android_log_print(ANDROID_LOG_INFO, "DemoServer", "ai_binder = %p",
ai_binder);
return AIBinder_toJavaBinder(env, ai_binder);
}
|
nicolasnoble/grpc
|
examples/android/binder/java/io/grpc/binder/cpp/exampleserver/native.cc
|
C++
|
apache-2.0
| 3,156
|
---
layout: feature
title: 'Person'
shortdef: 'person'
udver: '2'
---
<table class="typeindex" border="1">
<tr>
<td style="background-color:cornflowerblue;color:white"><strong>Values:</strong> </td>
<td><a href="">1</a></td>
<td><a href="">2</a></td>
<td><a href="">3</a></td>
</tr>
</table>
`Person` in Ka'apor may take the the following values: 1, 2, and 3. *ta*.
### <a name="1">`1`</a>: 1
The example below has
#### Examples
* _<b>some example</b> _ “soe example”
### <a name="2">`2`</a>: 2
The example below has
#### Examples
* _<b>remusak</b> _ “you got sb. to see” (SG.2 causative)
### <a name="3">`3`</a>: 3
The example below has
#### Examples
* _<b>aʔe uʔu</b> _ “he eats”
## Diffs
### Prague Dependency Treebank
The PDT tagset does not distinguish `Ptan` from `Plur` and `Coll` from `Sing`,
therefore this distinction is not being made in the converted data.
<!-- Interlanguage links updated St lis 3 20:58:26 CET 2021 -->
|
UniversalDependencies/docs
|
_urb/feat/Person.md
|
Markdown
|
apache-2.0
| 1,010
|
Opendi Solr Client Changelog
============================
1.1.0. (2015-12-07)
-------------------
* Update to new major version of `opendi/lang` (for php7 compatibility)
1.0.2. (2015-09-09)
-------------------
* Fixed a broken test
1.0.1. (2015-09-09)
-------------------
* Added `SolrClientServiceProvider::factory()`
* Fixed passing of options to Guzzle
1.0.0 (2015-07-17)
------------------
* No changes compared to beta1
1.0.0-beta1 (2015-07-14)
------------------------
* Reorganized code sructure (BC thoroughly broken)
* Queries moved to `Query` subnamespace
* Removed `Parser` classes, replaced by Select subclasses
* Removed `Filter` classes, replaced by `Select::filter()`
* Reimplemented `Expression` and added `Term`
* Added a Pimple service provider
* Added more options to queries
* `Core::update()` and `Core::select()` will request and decode JSON. Use `raw`
variants to avoid this.
0.5.0 (2015-04-07)
------------------
* Updated dependencies to Symfony components 2.6 and Guzzle 5
0.4.2 (2014-10-22)
------------------
* Fixed a bug in `bin/solr` which prevented autoloading (#8) when installed as
a dependency.
0.4.1 (2014-10-22)
------------------
* Added bin/solr binary to composer.json so that it will be available to
libraries which use solrclient (#7)
0.4.0 (2014-10-20)
------------------
* Added `Group` class for better sorting
* Added `Solr:group()`
* Added `Core::count()`
* Added `Core::deleteAll()`
* Added `Core::deleteByID()`
* Added `Core::deleteByQuery()`
* Added `Core::status()`
* Added `Client::factory()` for easier client construction
* Moved `Client::ping()` to `Core::ping()`
* Modified the ping command to take a core name as argument
0.3.2 (2014-08-25)
------------------
#### Features
* Added a [Pimple service provider](https://github.com/fabpot/Pimple#extending-a-container)
for the Solr client
0.3.1 (2014-07-25)
------------------
#### Bugfixes
* Fixed solr update which didn't work by adding headers for JSON content type
0.3.0 (2014-06-23)
------------------
#### BC breaks
* Renamed classes, removed the "Solr" prefix, so `SolrClient` becomes `Client`,
etc.
* Separated `Connection` class into `Core` and `Client`. Methods `select()` and
`update()` methods have been moved to `Core` class. To excecute a select, run
`$client->core('<core>')->select($select)` where '<core>' is the name of the
core on which you want to run the query.
#### Features
* Added `Client::coreStatus()`
* Added `Client::getEmitter()`
* Added `Client::ping()`
* Added `Solr` factory class for easier chaining.
0.2.1 (2014-06-11)
------------------
* Reworked facet support, added new options such as pivot
* facet.field is no longer mandatory
* Removed __toString magic methods from SolrSelect and SolrFacet
|
opendi/solrclient
|
CHANGELOG.md
|
Markdown
|
apache-2.0
| 2,783
|
/*
* Copyright 2015 herd contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.finra.herd.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.finra.herd.model.api.xml.SchemaColumn;
import org.finra.herd.model.jpa.BusinessObjectFormatEntity;
import org.finra.herd.model.jpa.SchemaColumnEntity;
@Component
public class SchemaColumnDaoTestHelper
{
@Autowired
private SchemaColumnDao schemaColumnDao;
/**
* Creates and persists a new schema column entity.
*
* @param businessObjectFormatEntity the business object format entity
* @param columnName the name of the schema column
*
* @return the newly created schema column entity
*/
public SchemaColumnEntity createSchemaColumnEntity(BusinessObjectFormatEntity businessObjectFormatEntity, String columnName)
{
SchemaColumnEntity schemaColumnEntity = new SchemaColumnEntity();
schemaColumnEntity.setBusinessObjectFormat(businessObjectFormatEntity);
schemaColumnEntity.setName(columnName);
schemaColumnEntity.setType(AbstractDaoTest.COLUMN_DATA_TYPE);
return schemaColumnDao.saveAndRefresh(schemaColumnEntity);
}
/**
* Returns a list of schema columns that use hard coded test values.
*
* @return the list of test schema column entities
*/
public List<SchemaColumn> getTestPartitionColumns()
{
return getTestSchemaColumns("PRTN_CLMN", AbstractDaoTest.PARTITION_COLUMNS);
}
/**
* Returns a list of schema partition columns that use hard coded test values.
*
* @return the list of test schema partition columns
*/
public List<SchemaColumn> getTestPartitionColumns(String randomSuffix)
{
List<SchemaColumn> partitionColumns = new ArrayList<>();
// Add first 3 partition column matching to regular partition columns.
partitionColumns.addAll(getTestSchemaColumns(AbstractDaoTest.SCHEMA_COLUMN_NAME_PREFIX, 0, 3, randomSuffix));
// Add the remaining partition columns.
partitionColumns.addAll(getTestSchemaColumns(AbstractDaoTest.SCHEMA_PARTITION_COLUMN_NAME_PREFIX, 3, AbstractDaoTest.MAX_PARTITIONS - 3, randomSuffix));
// Update top level partition column name to match the business object format partition key.
partitionColumns.get(0).setName(AbstractDaoTest.PARTITION_KEY);
return partitionColumns;
}
/**
* Returns a list of schema columns that use hard coded test values.
*
* @param randomSuffix the random suffix
*
* @return the list of test schema columns
*/
public List<SchemaColumn> getTestSchemaColumns(String randomSuffix)
{
return getTestSchemaColumns(AbstractDaoTest.SCHEMA_COLUMN_NAME_PREFIX, 0, AbstractDaoTest.MAX_COLUMNS, randomSuffix);
}
/**
* Returns a list of schema columns that use passed attributes and hard coded test values.
*
* @param columnNamePrefix the column name prefix to use for the test columns
* @param offset the offset index to start generating columns with
* @param numColumns the number of columns
* @param randomSuffix the random suffix
*
* @return the list of test schema columns
*/
public List<SchemaColumn> getTestSchemaColumns(String columnNamePrefix, Integer offset, Integer numColumns, String randomSuffix)
{
// Build a list of schema columns.
List<SchemaColumn> columns = new ArrayList<>();
for (int i = 0; i < numColumns; i++)
{
SchemaColumn schemaColumn = new SchemaColumn();
columns.add(schemaColumn);
// Set a value for the required column name field.
schemaColumn.setName(String.format("%s-%d%s", columnNamePrefix, i + offset, randomSuffix));
// Set a value for the required column type field.
schemaColumn.setType(String.format("Type-%d", i + offset));
// Set a value for the optional column size field for every other column.
schemaColumn.setSize(i % 2 == 0 ? null : String.format("Size-%d", i + offset));
// Set a value for the optional column required flag for each two out of 3 columns with the flag value alternating between true and false.
schemaColumn.setRequired(i % 3 == 0 ? null : i % 2 == 0);
// Set a value for the optional default value field for every other column.
schemaColumn.setDefaultValue(i % 2 == 0 ? null : String.format("Clmn-Dflt-Value-%d%s", i, randomSuffix));
// Set a value for the optional column size field for every other column.
schemaColumn.setDescription(i % 2 == 0 ? null : String.format("Clmn-Desc-%d%s", i, randomSuffix));
}
return columns;
}
/**
* Returns a list of schema columns that use hard coded test values.
*
* @return the list of test schema column entities
*/
public List<SchemaColumn> getTestSchemaColumns()
{
return getTestSchemaColumns("COLUMN", AbstractDaoTest.SCHEMA_COLUMNS);
}
/**
* Returns a list of schema columns that use hard coded test values.
*
* @param columnNamePrefix the column name prefix
* @param schemaColumnDataTypes the list of schema column data types
*
* @return the list of test schema column entities
*/
public List<SchemaColumn> getTestSchemaColumns(String columnNamePrefix, String[][] schemaColumnDataTypes)
{
// Build a list of schema columns.
List<SchemaColumn> schemaColumns = new ArrayList<>();
int index = 1;
for (String[] schemaColumnDataType : schemaColumnDataTypes)
{
SchemaColumn schemaColumn = new SchemaColumn();
schemaColumns.add(schemaColumn);
String columnName = String.format("%s%03d", columnNamePrefix, index);
schemaColumn.setName(columnName);
schemaColumn.setType(schemaColumnDataType[0]);
schemaColumn.setSize(schemaColumnDataType[1]);
index++;
}
// Column comment is an optional field, so provide comment for the second column only.
schemaColumns.get(1).setDescription(
String.format("This is '%s' column. Here are \\'single\\' and \"double\" quotes along with a backslash \\.", schemaColumns.get(1).getName()));
return schemaColumns;
}
}
|
FINRAOS/herd
|
herd-code/herd-dao/src/test/java/org/finra/herd/dao/SchemaColumnDaoTestHelper.java
|
Java
|
apache-2.0
| 7,044
|
package org.webdsl.lang;
public interface IEnvironmentTemplateLookup {
public Class<?> getTemplate(String key);
public IEnvironmentTemplateLookup putTemplate(String key, Class<?> value);
}
|
webdsl/webdsl
|
java-runtime/src/org/webdsl/lang/IEnvironmentTemplateLookup.java
|
Java
|
apache-2.0
| 195
|
\subsubsection{HistorySetSnapShot}
\label{HistorySetSnapShot}
This PostProcessor performs a conversion from HistorySet to PointSet.
The conversion is made so that each history $H$ is converted to a single point $P$.
There are several methods that can be employed to choose the single point from the history:
\begin{itemize}
\item min: Take a time slice when the \xmlNode{pivotVar} is at its smallest value,
\item max: Take a time slice when the \xmlNode{pivotVar} is at its largest value,
\item average: Take a time slice when the \xmlNode{pivotVar} is at its time-weighted average value,
\item value: Take a time slice when the \xmlNode{pivotVar} \emph{first passes} its specified value,
\item timeSlice: Take a time slice index from the sampled time instance space.
\end{itemize}
To demonstrate the timeSlice, assume that each history H is a dict of n output variables $x_1=[...],
x_n=[...]$, then the resulting point P is at time instant index t: $P=[x_1[t],...,x_n[t]]$.
Choosing one the these methods for the \xmlNode{type} node will take a time slice for all the variables in the
output space based on the provided parameters. Alternatively, a \xmlString{mixed} type can be used, in which
each output variable can use a different time slice parameter. In other words, you can take the max of one
variable while taking the minimum of another, etc.
\ppType{HistorySetSnapShot}{HistorySetSnapShot}
In the \xmlNode{PostProcessor} input block, the following XML sub-nodes are required,
independent of the \xmlAttr{subType} specified:
\begin{itemize}
\item \xmlNode{type}, \xmlDesc{string, required field}, type of operation: \xmlString{min}, \xmlString{max},
\xmlString{average}, \xmlString{value}, \xmlString{timeSlice}, or \xmlString{mixed}
\item \xmlNode{extension}, \xmlDesc{string, required field}, type of extension when the sync process goes outside the boundaries of the history (zeroed or extended)
\item \xmlNode{pivotParameter}, \xmlDesc{string, optional field}, name of the temporal variable. Required for the
\xmlString{average} and \xmlString{timeSlice} methods.
\end{itemize}
If a \xmlString{timeSlice} type is in use, the following nodes also are required:
\begin{itemize}
\item \xmlNode{timeInstant}, \xmlDesc{integer, required field}, required and only used in the
\xmlString{timeSlice} type. Location of the time slice (integer index)
\item \xmlNode{numberOfSamples}, \xmlDesc{integer, required field}, number of samples
\end{itemize}
If instead a \xmlString{min}, \xmlString{max}, \xmlString{average}, or \xmlString{value} is used, the following nodes
are also required:
\begin{itemize}
\item \xmlNode{pivotVar}, \xmlDesc{string, required field}, Name of the chosen indexing variable (the
variable whose min, max, average, or value is used to determine the time slice)
\item \xmlNode{pivotVal}, \xmlDesc{float, optional field}, required for \xmlString{value} type, the value for the chosen variable
\end{itemize}
Lastly, if a \xmlString{mixed} approach is used, the following nodes apply:
\begin{itemize}
\item \xmlNode{max}, \xmlDesc{string, optional field}, the names of variables whose output should be their
own maximum value within the history.
\item \xmlNode{min}, \xmlDesc{string, optional field}, the names of variables whose output should be their
own minimum value within the history.
\item \xmlNode{average}, \xmlDesc{string, optional field}, the names of variables whose output should be their
own average value within the history. Note that a \xmlNode{pivotParameter} node is required to perform averages.
\item \xmlNode{value}, \xmlDesc{string, optional field}, the names of variables whose output should be taken
at a time slice determined by another variable. As with the non-mixed \xmlString{value} type, the first
time the \xmlAttr{pivotVar} crosses the specified \xmlAttr{pivotVal} will be the time slice taken.
This node requires two attributes, if used:
\begin{itemize}
\item \xmlAttr{pivotVar}, \xmlDesc{string, required field}, the name of the variable on which the time
slice will be performed. That is, if we want the value of $y$ when $t=0.245$,
this attribute would be \xmlString{t}.
\item \xmlAttr{pivotVal}, \xmlDesc{float, required field}, the value of the \xmlAttr{pivotVar} on which the time
slice will be performed. That is, if we want the value of $y$ when $t=0.245$,
this attribute would be \xmlString{0.245}.
\end{itemize}
Note that all the outputs of the \xmlNode{DataObject} output of this PostProcessor must be listed under one
of the \xmlString{mixed} node types in order for values to be returned.
\end{itemize}
\textbf{Example (mixed):}
This example will output the average value of $x$ for $x$, the value of $y$ at
time$=0.245$ for $y$, and the value of $z$ at $x=4.0$ for $z$.
\begin{lstlisting}[style=XML,morekeywords={subType,debug,name,class,type}]
<Simulation>
...
<Models>
...
<PostProcessor name="mampp2" subType="HistorySetSnapShot">
<type>mixed</type>
<average>x</average>
<value pivotVar="time" pivotVal="0.245">y</value>
<value pivotVar="x" pivotVal="4.0">z</value>
<pivotParameter>time</pivotParameter>
<extension>zeroed</extension>
</PostProcessor>
...
</Models>
...
</Simulation>
\end{lstlisting}
|
idaholab/raven
|
doc/user_manual/PostProcessors/HistorySetSnapShot.tex
|
TeX
|
apache-2.0
| 5,418
|
# Copyright 2021 Google LLC
#
# 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.
from ..images.get import get_image
from ..images.list import list_images
def test_list_images():
images = list_images("debian-cloud")
for img in images:
assert img.kind == "compute#image"
assert img.self_link.startswith(
"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/"
)
def test_get_image():
images = list_images("debian-cloud")
image = next(iter(images))
image2 = get_image("debian-cloud", image.name)
assert image == image2
|
googleapis/python-compute
|
samples/snippets/tests/test_sample_images.py
|
Python
|
apache-2.0
| 1,097
|
package com.suscipio_solutions.consecro_mud.MOBS;
/*
Copyright 2000-2014 Mike Rundell
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.
*/
public class GreenDragon extends Dragon
{
@Override public String ID(){return "GreenDragon";}
public GreenDragon()
{
// ===== call the super class constructor
super(GREEN);
}
}
|
ConsecroMUD/ConsecroMUD
|
com/suscipio_solutions/consecro_mud/MOBS/GreenDragon.java
|
Java
|
apache-2.0
| 829
|
# Cephaelis hoffmannseggiana Willd. ex Schult. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Syst. veg. 5:214. 1819
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Psychotria/Psychotria hoffmannseggiana/ Syn. Cephaelis hoffmannseggiana/README.md
|
Markdown
|
apache-2.0
| 219
|
#pragma once
#include <string>
#include "envoy/server/filter_config.h"
#include "common/config/well_known_names.h"
namespace Envoy {
namespace Server {
namespace Configuration {
/**
* Config registration for the cors filter. @see NamedHttpFilterConfigFactory.
*/
class CorsFilterConfig : public NamedHttpFilterConfigFactory {
public:
HttpFilterFactoryCb createFilterFactory(const Json::Object& json_config,
const std::string& stats_prefix,
FactoryContext& context) override;
std::string name() override { return Config::HttpFilterNames::get().CORS; }
};
} // namespace Configuration
} // namespace Server
} // namespace Envoy
|
tdmackey/envoy
|
source/server/config/http/cors.h
|
C
|
apache-2.0
| 722
|
package com.idiot.rudra.std;
/******************************************************************************
* Compilation: javac StdIn.java
* Execution: java StdIn (interactive test of basic functionality)
* Dependencies: none
*
* Reads in data of various types from standard input.
*
******************************************************************************/
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* The {@code StdIn} class provides static methods for reading strings
* and numbers from standard input.
* These functions fall into one of four categories:
* <ul>
* <li>those for reading individual tokens from standard input, one at a time,
* and converting each to a number, string, or boolean
* <li>those for reading characters from standard input, one at a time
* <li>those for reading lines from standard input, one at a time
* <li>those for reading a sequence of values of the same type from standard input,
* and returning the values in an array
* </ul>
* <p>
* Generally, it is best not to mix functions from the different
* categories in the same program.
* <p>
* <b>Reading tokens from standard input one at a time,
* and converting to numbers and strings.</b>
* You can use the following methods to read numbers, strings, and booleans
* from standard input:
* <ul>
* <li> {@link #readInt()}
* <li> {@link #readDouble()}
* <li> {@link #readString()}
* <li> {@link #readBoolean()}
* <li> {@link #readShort()}
* <li> {@link #readLong()}
* <li> {@link #readFloat()}
* <li> {@link #readByte()}
* </ul>
* <p>
* Each method skips over any input that is whitespace. Then, it reads
* the next token and attempts to convert it into a value of the specified
* type. If it succeeds, it returns that value; otherwise, it
* throws a {@link InputMismatchException}.
* <p>
* <em>Whitespace</em> includes spaces, tabs, and newlines; the full definition
* is inherited from {@link Character#isWhitespace(char)}.
* A <em>token</em> is a maximal sequence of non-whitespace characters.
* The precise rules for describing which tokens can be converted to
* integers and floating-point numbers are inherited from
* <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#number-syntax">Scanner</a>,
* using the locale {@link Locale#US}; the rules
* for floating-point numbers are slightly different
* from those in {@link Double#valueOf(String)},
* but unlikely to be of concern to most programmers.
* <p>
* <b>Reading characters from standard input, one at a time.</b>
* You can use the following two methods to read characters from standard input:
* <ul>
* <li> {@link #hasNextChar()}
* <li> {@link #readChar()}
* </ul>
* <p>
* The first method returns true if standard input has more input (including whitespace).
* The second method reads and returns the next character of input on standard
* input (possibly a whitespace character).
* <p>
* As an example, the following code fragment reads characters from standard input,
* one character at a time, and prints it to standard output.
* <pre>
* while (StdIn.hasNextChar()) {
* char c = StdIn.readChar();
* StdOut.print(c);
* }
* </pre>
* <p>
* <b>Reading lines from standard input, one at a time.</b>
* You can use the following two methods to read lines from standard input:
* <ul>
* <li> {@link #hasNextLine()}
* <li> {@link #readLine()}
* </ul>
* <p>
* The first method returns true if standard input has more input (including whitespace).
* The second method reads and returns the remaining portion of
* the next line of input on standard input (possibly whitespace),
* discarding the trailing line separator.
* <p>
* A <em>line separator</em> is defined to be one of the following strings:
* {@code \n} (Linux), {@code \r} (old Macintosh),
* {@code \r\n} (Windows),
* {@code \u2028}, {@code \u2029}, or {@code \u0085}.
* <p>
* As an example, the following code fragment reads text from standard input,
* one line at a time, and prints it to standard output.
* <pre>
* while (StdIn.hasNextLine()) {
* String line = StdIn.readLine();
* StdOut.println(line);
* }
* </pre>
* <p>
* <b>Reading a sequence of values of the same type from standard input.</b>
* You can use the following methods to read a sequence numbers, strings,
* or booleans (all of the same type) from standard input:
* <ul>
* <li> {@link #readAllDoubles()}
* <li> {@link #readAllInts()}
* <li> {@link #readAllLongs()}
* <li> {@link #readAllStrings()}
* <li> {@link #readAllLines()}
* <li> {@link #readAll()}
* </ul>
* <p>
* The first three methods read of all of remaining token on standard input
* and dconverts the tokens to values of
* the specified type, as in the corresponding
* {@code readDouble}, {@code readInt}, and {@code readString()} methods.
* The {@code readAllLines()} method reads all remaining lines on standard
* input and returns them as an array of strings.
* The {@code readAll()} method reads all remaining input on standard
* input and returns it as a string.
* <p>
* As an example, the following code fragment reads all of the remaining
* tokens from standard input and returns them as an array of strings.
* <pre>
* String[] words = StdIn.readAllStrings();
* </pre>
* <p>
* <b>Differences with Scanner.</b>
* {@code StdIn} and {@link Scanner} are both designed to parse
* tokens and convert them to primitive types and strings.
* Some of the main differences are summarized below:
* <ul>
* <li> {@code StdIn} is a set of static methods and reads
* reads input from only standard input. It is suitable for use before
* a programmer knows about objects.
* See {@link In} for an object-oriented version that handles
* input from files, URLs,
* and sockets.
* <li> {@code StdIn} uses whitespace as the delimiter between tokens.
* <li> {@code StdIn} coerces the character-set encoding to UTF-8,
* which is a standard character encoding for Unicode.
* <li> {@code StdIn} coerces the locale to {@link Locale#US},
* for consistency with {@link StdOut}, {@link Double#parseDouble(String)},
* and floating-point literals.
* <li> {@code StdIn} has convenient methods for reading a single
* character; reading in sequences of integers, doubles, or strings;
* and reading in all of the remaining input.
* </ul>
* <p>
* Historical note: {@code StdIn} preceded {@code Scanner}; when
* {@code Scanner} was introduced, this class was reimplemented to use {@code Scanner}.
* <p>
* <b>Using standard input.</b>
* Standard input is fundamental operating system abstraction, on Mac OS X,
* Windows, and Linux.
* The methods in {@code StdIn} are <em>blocking</em>, which means that they
* will wait until you enter input on standard input.
* If your program has a loop that repeats until standard input is empty,
* you must signal that the input is finished.
* To do so, depending on your operating system and IDE,
* use either {@code <Ctrl-d>} or {@code <Ctrl-z>}, on its own line.
* If you are redirecting standard input from a file, you will not need
* to do anything to signal that the input is finished.
* <p>
* <b>Known bugs.</b>
* Java's UTF-8 encoding does not recognize the optional
* <a href = "http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058">byte-order mask</a>.
* If the input begins with the optional byte-order mask, {@code StdIn}
* will have an extra character {@code \uFEFF} at the beginning.
* <p>
* <b>Reference.</b>
* For additional documentation,
* see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <em>Introduction to Programming in Java: An Interdisciplinary Approach</em>
* by Robert Sedgewick and Kevin Wayne.
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdIn {
/*** begin: section (1 of 2) of code duplicated from In to StdIn. */
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace significant
private static final Pattern EMPTY_PATTERN = Pattern.compile("");
// used to read the entire input
private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn. */
private static Scanner scanner;
// it doesn't make sense to instantiate this class
private StdIn() { }
//// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static"
/**
* Returns true if standard input is empty (except possibly for whitespace).
* Use this method to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return {@code true} if standard input is empty (except possibly
* for whitespace); {@code false} otherwise
*/
public static boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Returns true if standard input has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return {@code true} if standard input is empty;
* {@code false} otherwise
*/
public static boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Returns true if standard input has more inputy (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return {@code true} if standard input has more input (including whitespace);
* {@code false} otherwise
*/
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line, excluding the line separator if present.
*
* @return the next line, excluding the line separator if present;
* {@code null} if no such line
*/
public static String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character.
*
* @return the next character
* @throws NoSuchElementException if standard input is empty
*/
public static char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Reads and returns the remainder of the input, as a string.
*
* @return the remainder of the input, as a string
* @throws NoSuchElementException if standard input is empty
*/
public static String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token and returns the {@code String}.
*
* @return the next {@code String}
* @throws NoSuchElementException if standard input is empty
*/
public static String readString() {
return scanner.next();
}
/**
* Reads the next token from standard input, parses it as an integer, and returns the integer.
*
* @return the next integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as an {@code int}
*/
public static int readInt() {
return scanner.nextInt();
}
/**
* Reads the next token from standard input, parses it as a double, and returns the double.
*
* @return the next double on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code double}
*/
public static double readDouble() {
return scanner.nextDouble();
}
/**
* Reads the next token from standard input, parses it as a float, and returns the float.
*
* @return the next float on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code float}
*/
public static float readFloat() {
return scanner.nextFloat();
}
/**
* Reads the next token from standard input, parses it as a long integer, and returns the long integer.
*
* @return the next long integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code long}
*/
public static long readLong() {
return scanner.nextLong();
}
/**
* Reads the next token from standard input, parses it as a short integer, and returns the short integer.
*
* @return the next short integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code short}
*/
public static short readShort() {
return scanner.nextShort();
}
/**
* Reads the next token from standard input, parses it as a byte, and returns the byte.
*
* @return the next byte on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code byte}
*/
public static byte readByte() {
return scanner.nextByte();
}
/**
* Reads the next token from standard input, parses it as a boolean,
* and returns the boolean.
*
* @return the next boolean on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}:
* {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false,
* ignoring case
*/
public static boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
/**
* Reads all remaining tokens from standard input and returns them as an array of strings.
*
* @return all remaining tokens on standard input, as an array of strings
*/
public static String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// because trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
// don't include first token if it is leading whitespace
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length - 1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from standard input and returns them as an array of strings.
* @return all remaining lines on standard input, as an array of strings
*/
public static String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
}
/**
* Reads all remaining tokens from standard input, parses them as integers, and returns
* them as an array of integers.
* @return all remaining integers on standard input, as an array
* @throws InputMismatchException if any token cannot be parsed as an {@code int}
*/
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from standard input, parses them as longs, and returns
* them as an array of longs.
* @return all remaining longs on standard input, as an array
* @throws InputMismatchException if any token cannot be parsed as a {@code long}
*/
public static long[] readAllLongs() {
String[] fields = readAllStrings();
long[] vals = new long[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Long.parseLong(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from standard input, parses them as doubles, and returns
* them as an array of doubles.
* @return all remaining doubles on standard input, as an array
* @throws InputMismatchException if any token cannot be parsed as a {@code double}
*/
public static double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
//// end: section (2 of 2) of code duplicated from In to StdIn
// do this once when StdIn is initialized
static {
resync();
}
/**
* If StdIn changes, use this to reinitialize the scanner.
*/
private static void resync() {
setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME));
}
private static void setScanner(Scanner scanner) {
StdIn.scanner = scanner;
StdIn.scanner.useLocale(LOCALE);
}
/**
* Reads all remaining tokens, parses them as integers, and returns
* them as an array of integers.
* @return all remaining integers, as an array
* @throws InputMismatchException if any token cannot be parsed as an {@code int}
* @deprecated Replaced by {@link #readAllInts()}.
*/
@Deprecated
public static int[] readInts() {
return readAllInts();
}
/**
* Reads all remaining tokens, parses them as doubles, and returns
* them as an array of doubles.
* @return all remaining doubles, as an array
* @throws InputMismatchException if any token cannot be parsed as a {@code double}
* @deprecated Replaced by {@link #readAllDoubles()}.
*/
@Deprecated
public static double[] readDoubles() {
return readAllDoubles();
}
/**
* Reads all remaining tokens and returns them as an array of strings.
* @return all remaining tokens, as an array of strings
* @deprecated Replaced by {@link #readAllStrings()}.
*/
@Deprecated
public static String[] readStrings() {
return readAllStrings();
}
/**
* Interactive test of basic functionality.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
StdOut.print("Type a string: ");
String s = StdIn.readString();
StdOut.println("Your string was: " + s);
StdOut.println();
StdOut.print("Type an int: ");
int a = StdIn.readInt();
StdOut.println("Your int was: " + a);
StdOut.println();
StdOut.print("Type a boolean: ");
boolean b = StdIn.readBoolean();
StdOut.println("Your boolean was: " + b);
StdOut.println();
StdOut.print("Type a double: ");
double c = StdIn.readDouble();
StdOut.println("Your double was: " + c);
StdOut.println();
}
}
|
idiotrudra/projects
|
algo/src/main/java/com/idiot/rudra/std/StdIn.java
|
Java
|
apache-2.0
| 21,681
|
# Archangiopteris Christ & Giesenh. GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Marattiopsida/Marattiales/Angiopteridaceae/Archangiopteris/README.md
|
Markdown
|
apache-2.0
| 189
|
# Config Sync
Redis does not replicate configuration changes made via the `CONFIG SET`
command. Nor does Sentinel. This is a small tool which is meant to
reside on a sentinel to read it's config and synchronize all monitored
slaves with their master's for a list of configuration directives.
# Configuration
The configuration options currently available are telling configsync
where to find the Sentinel config file and what directives to
synchronize. By default it will look to `/etc/redis/sentinel.conf`, but
this can be changed via the environment variable
`CONFIGSYNC_SENTINELCONFIGFILE`.
Likewise `CONFIGSYNC_SYNCABLEDIRECTIVELIST` can be a single directive or
a comma separated list of directives to synchronize to the slave(s).
If you want to run it in "pretend" mode: `CONFIGSYNC_PRETENDONLY=true`
# Anticipated Usage
Generally this is expected to be put into a cron table to run
perodically. It has been tested running against a sentinel with 100
monitored pods and runs in under half a second, so should be safe to run
every minute if desired.
|
therealbill/configsync
|
README.md
|
Markdown
|
apache-2.0
| 1,061
|
package folioxml.css;
import folioxml.core.InvalidMarkupException;
import folioxml.slx.SlxRecord;
import folioxml.slx.SlxToken;
/**
* Operates on SLX valid only (that has been CssClassCleaner proccessed inside SlxTransformer)
*
* @author nathanael
*/
public class StylesheetBuilder {
private SlxRecord root = null;
public StylesheetBuilder(SlxRecord root) {
this.root = root;
}
public static final String DEFAULT_FONT_SIZE = "12pt";
private void getDefaultCss(String applySelector, StringBuilder sb) {
sb.append("a.folio_pagination_link {display:block; margin:1em;}\n");
sb.append(applySelector + "td p:first {margin:0 0 0 0;}\n"); //The first P tag shouldn't have margins...
sb.append(applySelector + "th p:first {margin:0 0 0 0;}\n"); //The first P tag shouldn't have margins...
sb.append(applySelector + "p {margin:0; margin-top:0.2em;} p._empty{ padding-top:1em; }\n"); //Empty paragraphs get padding to mimic folio model.
//Set the default font size and face. Folio uses TimesNewRoman 12
//white-space-collapse: preserve; - Tries to maintain compatibility with Folio's treatment of whitespace.
//font-weight: bolder; text-align: center
// margin:30px;
sb.append(applySelector.length() == 0 ? "body" : applySelector + " {font-family: \"Times New Roman\"; font-size:" + DEFAULT_FONT_SIZE + "; line-height:1.0em; white-space-collapse: preserve; white-space:pre-wrap;}\n");
sb.append(applySelector + "th {font-weight:auto;text-align:auto;}\n"); //Reset to act like td - what is folio behavior?
//Add faux-tabulation rules. Remove width restriction since faux-tabs can make it bigger.
sb.append(applySelector + "p.faux_tabulation {white-space: pre-wrap; white-space-collapse: preserve; font-family: \"Courier New\", monospace; width:auto !important; }\n");
}
public String getCss(String applySelector, boolean selectorIsRecordDiv) throws InvalidMarkupException {
StringBuilder sb = new StringBuilder();
if (applySelector == null) applySelector = "";
if (applySelector.length() > 0 && !applySelector.endsWith(" ")) applySelector += " ";
if (applySelector.isEmpty()) selectorIsRecordDiv = false;
getDefaultCss(applySelector, sb);
StringBuilder replace_underline = new StringBuilder(applySelector + ".replace_underline, ");
String text_underline = "text-decoration:underline;";
for (SlxToken t : root.getTokens()) {
if (t.matches("style-def")) {
String cls = t.get("class");
String style = t.get("style");
String type = t.get("type");
if (cls != null && style != null) {
String selector = "";
/* style-def types: level, highlighter, character-style, paragraph, link, field */
if (type.equalsIgnoreCase("level")) selector = "div";
if (type.equalsIgnoreCase("paragraph")) selector = "p";
if (type.equalsIgnoreCase("link")) selector = "a";
if (selector.length() == 0) selector = "span";
if (type.equalsIgnoreCase("level") && selectorIsRecordDiv) {
selector = applySelector.trim() + "." + cls; //the selector for level styles applies to the same div; not a child!
} else {
selector = applySelector + selector + "." + cls;
}
//Factor out non-link underlines into a single rule.
if (!type.equalsIgnoreCase("link") && style.indexOf(text_underline, 0) >= 0) {
replace_underline.append(selector);
replace_underline.append(", ");
style = style.replace(text_underline, "");
}
sb.append(selector + " {\n ");
sb.append(style.replace(";", ";\n "));
sb.append("}\n");
}
}
}
//Write underlining rule last
sb.append(replace_underline.toString().replaceFirst(", \\Z", ""));
sb.append("{\n ");
sb.append(text_underline);
sb.append("\n}\n");
return sb.toString();
}
public String getCssAndStyleTags() throws InvalidMarkupException {
return "<style type=\"text/css\">\n" + getCss(null, false) + "</style>";
}
}
/* Default stylesheet for HTML 4 - we have to modify things so they mimic folio behavior...
*
* html, address,
blockquote,
body, dd, div,
dl, dt, fieldset, form,
frame, frameset,
h1, h2, h3, h4,
h5, h6, noframes,
ol, p, ul, center,
dir, hr, menu, pre { display: block }
li { display: list-item }
head { display: none }
table { display: table }
tr { display: table-row }
thead { display: table-header-group }
tbody { display: table-row-group }
tfoot { display: table-footer-group }
col { display: table-column }
colgroup { display: table-column-group }
td, th { display: table-cell }
caption { display: table-caption }
th { font-weight: bolder; text-align: center }
caption { text-align: center }
body { margin: 8px }
h1 { font-size: 2em; margin: .67em 0 }
h2 { font-size: 1.5em; margin: .75em 0 }
h3 { font-size: 1.17em; margin: .83em 0 }
h4, p,
blockquote, ul,
fieldset, form,
ol, dl, dir,
menu { margin: 1.12em 0 }
h5 { font-size: .83em; margin: 1.5em 0 }
h6 { font-size: .75em; margin: 1.67em 0 }
h1, h2, h3, h4,
h5, h6, b,
strong { font-weight: bolder }
blockquote { margin-left: 40px; margin-right: 40px }
i, cite, em,
var, address { font-style: italic }
pre, tt, code,
kbd, samp { font-family: monospace }
pre { white-space: pre }
button, textarea,
input, select { display: inline-block }
big { font-size: 1.17em }
small, sub, sup { font-size: .83em }
sub { vertical-align: sub }
sup { vertical-align: super }
table { border-spacing: 2px; }
thead, tbody,
tfoot { vertical-align: middle }
td, th, tr { vertical-align: inherit }
s, strike, del { text-decoration: line-through }
hr { border: 1px inset }
ol, ul, dir,
menu, dd { margin-left: 40px }
ol { list-style-type: decimal }
ol ul, ul ol,
ul ul, ol ol { margin-top: 0; margin-bottom: 0 }
u, ins { text-decoration: underline }
br:before { content: "\A"; white-space: pre-line }
center { text-align: center }
:link, :visited { text-decoration: underline }
:focus { outline: thin dotted invert }
Begin bidirectionality settings (do not change)
BDO[DIR="ltr"] { direction: ltr; unicode-bidi: bidi-override }
BDO[DIR="rtl"] { direction: rtl; unicode-bidi: bidi-override }
*[DIR="ltr"] { direction: ltr; unicode-bidi: embed }
*[DIR="rtl"] { direction: rtl; unicode-bidi: embed }
@media print {
h1 { page-break-before: always }
h1, h2, h3,
h4, h5, h6 { page-break-after: avoid }
ul, ol, dl { page-break-before: avoid }
}
*/
|
imazen/folioxml
|
core/folioxml/src/folioxml/css/StylesheetBuilder.java
|
Java
|
apache-2.0
| 7,315
|
# Clitocybe macromphala Mont. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Clitocybe macromphala Mont.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Tricholomataceae/Clitocybe/Clitocybe macromphala/README.md
|
Markdown
|
apache-2.0
| 183
|
/**
* SVPAlib
* transducers.sst
* Apr 21, 2015
* @author Loris D'Antoni
*/
package transducers.sst;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import theory.BooleanAlgebraSubst;
/**
* A variable assignment. A function mapping each variable to its current value
* @param <S>
* The domain of the Boolean algebra
*/
public class VariableAssignment<S> {
ArrayList<List<S>> variableAssignments;
public VariableAssignment(ArrayList<List<S>> variableAssignments) {
super();
this.variableAssignments = variableAssignments;
}
/**
* Value of the first variable at index 0
* @return
*/
public List<S> outputVariableValue(){
return variableAssignments.get(0);
}
/**
* Value of the first variable at index 0
* @return
*/
public List<S> variableValue(int index){
return variableAssignments.get(index);
}
/**
* returns number of variables
*/
public int numVars(){
return variableAssignments.size();
}
/**
* returns an initialize assignment to epsilon
* @param varsLength
* @param ba
* @return
*/
public static <S1, F1, P1> VariableAssignment<S1> MkInitialValue(
int varsLength,
BooleanAlgebraSubst<P1, F1, S1> ba
){
ArrayList<List<S1>> emptyVariableAssignment = new ArrayList<List<S1>>(varsLength);
for(int variable = 0; variable<varsLength; variable++)
emptyVariableAssignment.add(new LinkedList<S1>());
return new VariableAssignment<S1>(emptyVariableAssignment);
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for(List<S> ass : variableAssignments){
for(S v : ass){
sb.append(v.toString());
}
sb.append(';');
}
return sb.toString();
}
}
|
lorisdanto/symbolicautomata
|
models/src/main/java/transducers/sst/VariableAssignment.java
|
Java
|
apache-2.0
| 1,734
|
/**
* Copyright 2013 Jim Burton.
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* 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.google.litecoin.crypto;
import java.util.Arrays;
/**
* <p>An EncryptedPrivateKey contains the information produced after encrypting the private key bytes of an ECKey.</p>
*
* <p>It contains two member variables - initialisationVector and encryptedPrivateBytes. The initialisationVector is
* a randomly chosen list of bytes that were used to initialise the AES block cipher when the private key bytes were encrypted.
* You need these for decryption. The encryptedPrivateBytes are the result of AES encrypting the private keys using
* an AES key that is derived from a user entered password. You need the password to recreate the AES key in order
* to decrypt these bytes.</p>
*/
public class EncryptedPrivateKey {
private byte[] initialisationVector = null;
private byte[] encryptedPrivateBytes = null;
/**
* Cloning constructor.
* @param encryptedPrivateKey EncryptedPrivateKey to clone.
*/
public EncryptedPrivateKey(EncryptedPrivateKey encryptedPrivateKey) {
setInitialisationVector(encryptedPrivateKey.getInitialisationVector());
setEncryptedPrivateBytes(encryptedPrivateKey.getEncryptedBytes());
}
/**
* @param iv
* @param encryptedPrivateKeys
*/
public EncryptedPrivateKey(byte[] initialisationVector, byte[] encryptedPrivateKeys) {
setInitialisationVector(initialisationVector);
setEncryptedPrivateBytes(encryptedPrivateKeys);
}
public byte[] getInitialisationVector() {
return initialisationVector;
}
/**
* Set the initialisationVector, cloning the bytes.
*
* @param initialisationVector
*/
public void setInitialisationVector(byte[] initialisationVector) {
if (initialisationVector == null) {
this.initialisationVector = null;
return;
}
byte[] cloneIV = new byte[initialisationVector.length];
System.arraycopy(initialisationVector, 0, cloneIV, 0, initialisationVector.length);
this.initialisationVector = cloneIV;
}
public byte[] getEncryptedBytes() {
return encryptedPrivateBytes;
}
/**
* Set the encrypted private key bytes, cloning them.
*
* @param encryptedPrivateBytes
*/
public void setEncryptedPrivateBytes(byte[] encryptedPrivateBytes) {
if (encryptedPrivateBytes == null) {
this.encryptedPrivateBytes = null;
return;
}
this.encryptedPrivateBytes = Arrays.copyOf(encryptedPrivateBytes, encryptedPrivateBytes.length);
}
@Override
public EncryptedPrivateKey clone() {
return new EncryptedPrivateKey(getInitialisationVector(), getEncryptedBytes());
}
@Override
public int hashCode() {
return com.google.common.base.Objects.hashCode(encryptedPrivateBytes, initialisationVector);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final EncryptedPrivateKey other = (EncryptedPrivateKey) obj;
return com.google.common.base.Objects.equal(this.initialisationVector, other.initialisationVector)
&& com.google.common.base.Objects.equal(this.encryptedPrivateBytes, other.encryptedPrivateBytes);
}
@Override
public String toString() {
return "EncryptedPrivateKey [initialisationVector=" + Arrays.toString(initialisationVector) + ", encryptedPrivateKey=" + Arrays.toString(encryptedPrivateBytes) + "]";
}
/**
* Clears all the EncryptedPrivateKey contents from memory (overwriting all data including PRIVATE KEYS).
* WARNING - this method irreversibly deletes the private key information.
*/
public void clear() {
if (encryptedPrivateBytes != null) {
Arrays.fill(encryptedPrivateBytes, (byte)0);
}
if (initialisationVector != null) {
Arrays.fill(initialisationVector, (byte)0);
}
}
}
|
hank/litecoinj-new
|
core/src/main/java/com/google/litecoin/crypto/EncryptedPrivateKey.java
|
Java
|
apache-2.0
| 4,636
|
<script src="assets/lib/lesson.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/lesson.css">
<script>
var wordList=["an", "ans", "auch", "auf", "Ausflug", "Ausflüge", "ausfüllen", "ausgefüllt", "baden", "Bergen", "bringen", "Broschüren", "dein", "den", "fahren", "Ferien", "gefahren", "gegessen", "geholfen", "gemacht", "gestellt", "gestern", "guten Morgen", "guten Tag", "helfen", "heute", "Hilfe", "Ihnen", "in", "Informationen", "ins", "lange", "machen", "mein", "Morgen", "müde", "nein", "noch", "reservieren", "reserviert", "Rezeptionist", "schon", "Schweiz", "sein-possessiv", "stellen", "Stunde", "verbringen", "weil", "weit", "Wochen"]
</script>
<p>Lesen Sie die folgenden Wörter auf Schweizerdeutsch, indem Sie die Umformungsregeln anwenden.
<br>Wenn Sie das Schweizerdeutsche Wort hören wollen, klicken Sie darauf.</p>
<p class="wrap" id="play_all" onclick="playAudioAll(this, wordList)">
<button class="gcb-button-speaker">
<img id="play-all-button-img" src="assets/img/ic_play_black_24dp.png" style="vertical-align:middle">
</button>
</p>
<audio id="chd-wort" src=""></audio><div style="border:solid windowtext 1.0pt; padding:1.0pt 4.0pt 1.0pt 4.0pt" class="yui-wk-div"><table style="width:100%;border:0"><tbody>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="an" onclick="playAudio(this)"><span>a<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="ans" onclick="playAudio(this)"><span>a<span style='background:orange'>n</span>s</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="auch" onclick="playAudio(this)"><span>au<span style='background:orange'>ch</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="auf" onclick="playAudio(this)"><span style="background:orange">au</span><span>f</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="Ausflug" onclick="playAudio(this)"><span style="background:orange">Au</span><span>sflug</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Ausflüge" onclick="playAudio(this)"><span style="background:orange">Au</span><span>sflüg<span style='background:orange'>e</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="ausfüllen" onclick="playAudio(this)"><span style="background:orange">au</span><span>sfülle<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="ausgefüllt" onclick="playAudio(this)"><span style="background:orange">au</span><span>sg<span style='background:orange'>e</span>füllt</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="baden" onclick="playAudio(this)"><span>bade<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Bergen" onclick="playAudio(this)"><span>Berge<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="bringen" onclick="playAudio(this)"><span>bringe<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Broschüren" onclick="playAudio(this)"><span>Broschüre<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="dein" onclick="playAudio(this)"><span>d<span style='background:orange'>ei</span>n</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="den" onclick="playAudio(this)"><span>de<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="fahren" onclick="playAudio(this)"><span>fahre<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Ferien" onclick="playAudio(this)"><span>Ferie<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="gefahren" onclick="playAudio(this)"><span>g<span style='background:orange'>e</span>fahre<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="gegessen" onclick="playAudio(this)"><span>g<span style='background:orange'>e</span>gesse<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="geholfen" onclick="playAudio(this)"><span>g<span style='background:orange'>e</span>holfe<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="gemacht" onclick="playAudio(this)"><span>g<span style='background:orange'>e</span>macht</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="gestellt" onclick="playAudio(this)"><span>g<span style='background:orange'>e</span>stellt</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="gestern" onclick="playAudio(this)"><span>ge<span style='background:orange'>s</span>ter<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="guten Morgen" onclick="playAudio(this)"><span>g<span style='background:orange'>u</span>te<span style='background:orange'>n</span> Morge<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="guten Tag" onclick="playAudio(this)">
g<span style="background:orange">u</span>te<span style="background:orange">n</span> Tag
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p>
</td></tr><tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="helfen" onclick="playAudio(this)"><span>helfe<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="heute" onclick="playAudio(this)"><span>h<span style='background:orange'>eu</span>t<span style='background:orange'>e</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="Hilfe" onclick="playAudio(this)"><span>Hilf<span style='background:orange'>e</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Ihnen" onclick="playAudio(this)"><span>Ihne<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="in" onclick="playAudio(this)"><span>i<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Informationen" onclick="playAudio(this)"><span>Informatione<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="ins" onclick="playAudio(this)"><span>i<span style='background:orange'>n</span>s</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="lange" onclick="playAudio(this)"><span>lang<span style='background:orange'>e</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="machen" onclick="playAudio(this)"><span>mache<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="mein" onclick="playAudio(this)"><span>m<span style='background:orange'>ei</span>n</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="Morgen" onclick="playAudio(this)"><span>Morge<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="müde" onclick="playAudio(this)"><span>m<span style='background:orange'>ü</span>d<span style='background:orange'>e</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="nein" onclick="playAudio(this)"><span>nei<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="noch" onclick="playAudio(this)"><span>no<span style='background:orange'>ch</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="reservieren" onclick="playAudio(this)"><span>reserv<span style='background:orange'>ie</span>re<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="reserviert" onclick="playAudio(this)"><span>reserv<span style='background:orange'>ie</span>rt</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="Rezeptionist" onclick="playAudio(this)"><span>Rezeptioni<span style='background:orange'>s</span>t</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="schon" onclick="playAudio(this)"><span>scho<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="Schweiz" onclick="playAudio(this)"><span>Schw<span style='background:orange'>ei</span>z</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="sein-possessiv" onclick="playAudio(this)"><span>s<span style='background:orange'>ei</span>n (possessiv)</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="stellen" onclick="playAudio(this)"><span>stelle<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Stunde" onclick="playAudio(this)"><span>Stund<span style='background:orange'>e</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="verbringen" onclick="playAudio(this)"><span>verbringe<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="weil" onclick="playAudio(this)"><span>w<span style='background:orange'>ei</span>l</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr>
<tr id = "de">
<td style="width:50%;border:0"><p><span class="wrap" id="weit" onclick="playAudio(this)"><span>w<span style='background:orange'>ei</span>t</span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td>
<td style="width:50%;border:0"><p><span class="wrap" id="Wochen" onclick="playAudio(this)"><span>Woche<span style='background:orange'>n</span></span>
<button style="float:right" class="gcb-button-speaker noshow">
<img style="vertical-align:middle" src="assets/img/speaker_icon16.png">
</button>
</p></td></tr></tbody></table></div>
|
danieldanciu/schoggi
|
assets/html/laute16A.html
|
HTML
|
apache-2.0
| 17,955
|
# Cattleya labiata var. purpureostriata VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Cattleya/Cattleya labiata/ Syn. Cattleya labiata purpureostriata/README.md
|
Markdown
|
apache-2.0
| 194
|
package history
import (
"bytes"
"encoding/json"
"fmt"
"os"
"sync"
"github.com/admpub/spider/app/downloader/request"
"github.com/admpub/spider/common/mgo"
"github.com/admpub/spider/common/mysql"
"github.com/admpub/spider/common/pool"
"github.com/admpub/spider/config"
)
type Failure struct {
tabName string
fileName string
list map[string]*request.Request //key:url
inheritable bool
sync.RWMutex
}
func (self *Failure) PullFailure() map[string]*request.Request {
list := self.list
self.list = make(map[string]*request.Request)
return list
}
// 更新或加入失败记录,
// 对比是否已存在,不存在就记录,
// 返回值表示是否有插入操作。
func (self *Failure) UpsertFailure(req *request.Request) bool {
self.RWMutex.Lock()
defer self.RWMutex.Unlock()
if self.list[req.Unique()] != nil {
return false
}
self.list[req.Unique()] = req
return true
}
// 删除失败记录
func (self *Failure) DeleteFailure(req *request.Request) {
self.RWMutex.Lock()
delete(self.list, req.Unique())
self.RWMutex.Unlock()
}
// 先清空历史失败记录再更新
func (self *Failure) flush(provider string) (fLen int, err error) {
self.RWMutex.Lock()
defer self.RWMutex.Unlock()
fLen = len(self.list)
switch provider {
case "mgo":
if mgo.Error() != nil {
err = fmt.Errorf(" * Fail [添加失败记录][mgo]: %v 条 [ERROR] %v\n", fLen, mgo.Error())
return
}
mgo.Call(func(src pool.Src) error {
c := src.(*mgo.MgoSrc).DB(config.DB_NAME).C(self.tabName)
// 删除失败记录文件
c.DropCollection()
if fLen == 0 {
return nil
}
var docs = []interface{}{}
for key, req := range self.list {
docs = append(docs, map[string]interface{}{"_id": key, "failure": req.Serialize()})
}
c.Insert(docs...)
return nil
})
case "mysql":
_, err := mysql.DB()
if err != nil {
return fLen, fmt.Errorf(" * Fail [添加失败记录][mysql]: %v 条 [PING] %v\n", fLen, err)
}
table, ok := getWriteMysqlTable(self.tabName)
if !ok {
table = mysql.New()
table.SetTableName(self.tabName).CustomPrimaryKey(`id VARCHAR(255) NOT NULL PRIMARY KEY`).AddColumn(`failure MEDIUMTEXT`)
setWriteMysqlTable(self.tabName, table)
// 创建失败记录表
err = table.Create()
if err != nil {
return fLen, fmt.Errorf(" * Fail [添加失败记录][mysql]: %v 条 [CREATE] %v\n", fLen, err)
}
} else {
// 清空失败记录表
err = table.Truncate()
if err != nil {
return fLen, fmt.Errorf(" * Fail [添加失败记录][mysql]: %v 条 [TRUNCATE] %v\n", fLen, err)
}
}
// 添加失败记录
for key, req := range self.list {
table.AutoInsert([]string{key, req.Serialize()})
err = table.FlushInsert()
if err != nil {
fLen--
}
}
default:
// 删除失败记录文件
os.Remove(self.fileName)
if fLen == 0 {
return
}
f, _ := os.OpenFile(self.fileName, os.O_CREATE|os.O_WRONLY, 0777)
docs := make(map[string]string, len(self.list))
for key, req := range self.list {
docs[key] = req.Serialize()
}
b, _ := json.Marshal(docs)
b = bytes.Replace(b, []byte(`\u0026`), []byte(`&`), -1)
f.Write(b)
f.Close()
}
return
}
|
admpub/spider
|
app/aid/history/failure.go
|
GO
|
apache-2.0
| 3,222
|
---
author: leifmadsen
comments: true
date: 2010-02-19 14:39:35+00:00
layout: post
slug: update-on-tfot-v3-progress
title: Update on TFoT v3 Progress
wordpress_id: 166
categories:
- Asterisk
- Musings
tags:
- Asterisk
- asterisk book
- TFoT
- writing
---
Just another quick update on the progress of the 3rd edition of the Asterisk book. It's been a bit slow coming, but Jim and I have renewed vigor and vigilance to be productive and get things done. Since the last update, there was a period of time where nothing got done unfortunately. We did get a lot done in the week off I took to focus on the book (I think we ended up writing about 2-3 new chapters, and updated a lot of the old ones), but then of course work got in the way.
This has really been the problem the whole time, or else we'd be working on the 4th edition at this point. So instead of dreaming about having more time to work on the book, and for that time to be allocated all chaotic and patchy, we've come up with a new method. Each morning we're getting together for an hour between 8am and 9am where the amount of distractions is low, and the amount of energy is high. This way, we can get in a good 5 hours each week on the book, plus any additional time either of us is able to work on it separately.
It may not be the quickest way to get a book done, but we both have worked well in the past together on the other two editions and have always gotten lots accomplished, so we're going to try this method out for a couple months and see how it goes. After a week of using it and not missing any time we've already gotten through 3 chapters of review and additional content. The method seems to be working, and is giving us some renewed energy to keep plugging away, hoping to have the book ready to launch along with Asterisk 1.8.0.
More information to come in the coming months.
|
leifmadsen/blog
|
content/post/2010-02-19-update-on-tfot-v3-progress.markdown
|
Markdown
|
apache-2.0
| 1,860
|
using YAF.Lucene.Net.Analysis.Util;
using System.Collections.Generic;
namespace YAF.Lucene.Net.Analysis.Fa
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Factory for <see cref="PersianNormalizationFilter"/>.
/// <code>
/// <fieldType name="text_fanormal" class="solr.TextField" positionIncrementGap="100">
/// <analyzer>
/// <charFilter class="solr.PersianCharFilterFactory"/>
/// <tokenizer class="solr.StandardTokenizerFactory"/>
/// <filter class="solr.PersianNormalizationFilterFactory"/>
/// </analyzer>
/// </fieldType></code>
/// </summary>
public class PersianNormalizationFilterFactory : TokenFilterFactory, IMultiTermAwareComponent
{
/// <summary>
/// Creates a new <see cref="PersianNormalizationFilterFactory"/> </summary>
public PersianNormalizationFilterFactory(IDictionary<string, string> args) : base(args)
{
if (args.Count > 0)
{
throw new System.ArgumentException("Unknown parameters: " + args);
}
}
public override TokenStream Create(TokenStream input)
{
return new PersianNormalizationFilter(input);
}
public virtual AbstractAnalysisFactory GetMultiTermComponent()
{
return this;
}
}
}
|
Pathfinder-Fr/YAFNET
|
yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/Fa/PersianNormalizationFilterFactory.cs
|
C#
|
apache-2.0
| 2,184
|
#
# Cookbook Name:: php-fpm
# Recipe:: default
#
# Copyright 2015, E Source Companies, LLC
#
# Downloading the Webtatic repository.
remote_file "#{Chef::Config[:file_cache_path]}/webtatic_repo_latest.rpm" do
source "https://mirror.webtatic.com/yum/el7/webtatic-release.rpm"
action :create
end
# Installing Webtatic repository.
rpm_package "php56-rpm" do
source "#{Chef::Config[:file_cache_path]}/webtatic_repo_latest.rpm"
action :install
end
# Installing PHP 5.6.
package node['php-fpm']['package-list'] do
action :install
end
# Creating the PHP configuration.
template "/etc/php.ini" do
source "php.ini.erb"
owner "root"
group "root"
mode "0644"
end
# Creating the www pool configuration.
template "/etc/php-fpm.d/www.conf" do
source "www.conf.erb"
owner "root"
group "root"
mode "0644"
end
# Starting PHP-FPM and enabling it on boot.
service 'php-fpm' do
supports :restart => true, :reload => true
action [ :enable, :start ]
end
|
ESourceDevOps/vagrantbox
|
chef-repo/cookbooks/php-fpm/recipes/default.rb
|
Ruby
|
apache-2.0
| 987
|
package cn.edu.hpu.yuan.yuannews.user.register;
import dagger.Module;
import dagger.Provides;
/**
* Created by yuan on 16-5-12.
*/
@Module
public class RegisterModule {
protected RegisterContancts.RegisterCOntanctsView registerCOntanctsView;
public RegisterModule(RegisterContancts.RegisterCOntanctsView registerCOntanctsView) {
this.registerCOntanctsView = registerCOntanctsView;
}
public RegisterModule() {
}
@Provides
RegisterFragment provideRegisterFragment(){
return new RegisterFragment();
}
@Provides
RegisterContancts.RegisterContanctsPresenter provideRegsiterPresenter(){
return new RegisterPresenter(registerCOntanctsView);
}
}
|
LABELNET/YuanNewsForAndroid
|
yuannews/src/main/java/cn/edu/hpu/yuan/yuannews/user/register/RegisterModule.java
|
Java
|
apache-2.0
| 720
|
/**
*
*/
/**
* 配置相关的包
* @author Raye
* @since 2016年10月7日17:14:42
*/
package wang.raye.admin.config;
|
thikill/ace-boot-02
|
src/main/java/wang/raye/admin/config/package-info.java
|
Java
|
apache-2.0
| 124
|
////////////////////////////////////////////////////////////////////////////////////////////////////
/// This file is part of Quark-Engine, licensed under the Apache 2.0 License.
///
/// Copyright (c) 2015-2016 - Quark-Engine developers <https://github.com/QuarkEngine/QuarkEngine>.
///
/// 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.
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <type_traits>
namespace std
{
template<class E>
class hash
{
using sfinae = typename std::enable_if<std::is_enum<E>::value>::type;
public:
size_t operator()(const E& e) const
{
return std::hash<typename std::underlying_type_t<E>>()(e);
}
};
}
|
QuarkEngine/QuarkEngine
|
Quark-API/Util/HashHelper.hpp
|
C++
|
apache-2.0
| 1,234
|
#pragma once
#include <nstd/Base.hpp>
class Math
{
public:
template<typename T> static const T& max(const T& a, const T& b) {return a > b ? a : b;}
template<typename T> static const T& min(const T& a, const T& b) {return a < b ? a : b;}
template<typename T> static const T abs(const T& v) {return v < 0 ? -v : v;} // TODO: fast abs for double/float
static double floor(double v); // TODO: inline this
static float floor(float v); // TODO: inline this
static double ceil(double v); // TODO: inline this
static float ceil(float v); // TODO: inline this
static double exp(double v); // TODO: inline this
static float exp(float v); // TODO: inline this
static uint random(); // TODO: inline this
static uint random(uint seed);
static const usize randomMax;
};
|
craflin/libnstd
|
include/nstd/Math.hpp
|
C++
|
apache-2.0
| 786
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<title>io.thesis.collector.manager - start</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link th:href="@{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}"
href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet" media="screen"/>
</head>
<body>
<div class="container">
<h3>collector-client-manager</h3>
<p th:text="'manager time: ' + ${indexPage.serverTime} + ' | ' +
'manager host: ' + ${indexPage.serverHostName} + ' | ' +
'manager address: ' + ${indexPage.serverAddress}">time</p>
<hr/>
<table class="table table-hover">
<thead>
<tr>
<th>application</th>
<th>address</th>
<th>port</th>
<th>url</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr th:each="collectorClient : ${indexPage.clientInstanceList}">
<td th:text="${collectorClient.serviceId}">service id</td>
<td><a th:text="${collectorClient.address}"
th:href="@{'/' + ${collectorClient.address} + '/' + ${collectorClient.port}}"
href="client-details.html">12.34.56.78</a></td>
<td th:text="${collectorClient.port}">port</td>
<td th:text="${collectorClient.uri}">uri</td>
<td><a th:text="status" th:href="@{${collectorClient.uri} + '/health'}" href="#"></a></td>
</tr>
</tbody>
</table>
</div>
<script src="http://cdn.jsdelivr.net/webjars/jquery/2.2.4/jquery.min.js"
th:src="@{/webjars/jquery/2.2.4/jquery.min.js}"></script>
<script src="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.6/js/bootstrap.min.js"
th:src="@{/webjars/bootstrap/3.3.6/js/bootstrap.min.js}"></script>
</body>
</html>
|
markuslamm/io.thesis
|
collector-manager/collector-manager-app/src/main/resources/templates/index.html
|
HTML
|
apache-2.0
| 1,918
|
require 'test_helper'
class ImporterTest< Minitest::Test
def setup
@db = Mongoid.default_session
@bundle_root = File.join("test","fixtures","bundles")
@b_2_0_1 = File.join(@bundle_root,"bundle_version_2.0.1.zip")
@b_2_0_2 = File.join(@bundle_root,"bundle_version_2.0.2.zip")
@b_no_version = File.join(@bundle_root,"bundle_no_version.zip")
dump_database
assert_clean_db
end
def after_tests
dump_database
collection_fixtures('records', '_id')
collection_fixtures('health_data_standards_svs_value_sets', '_id')
collection_fixtures('measures')
end
def assert_clean_db
["records","measures","bundles","patient_cache","query_cache"].each do |collection|
assert_equal 0, @db[collection].where({}).count , "Should be 0 #{collection} in the db"
end
end
def test_no_version
loader = HealthDataStandards::Import::Bundle::Importer
begin
bundle = loader.import(File.new(@b_no_version), {delete_existing: false})
assert false, "Should have thrown exception for bundle with no version info"
rescue
end
end
def test_load_same_version_no_delete
loader = HealthDataStandards::Import::Bundle::Importer
begin
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: false})
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: false})
assert false, "Should have thrown exception attempting to version of bundle already loaded"
rescue
end
end
def test_load_same_version_with_delete
loader = HealthDataStandards::Import::Bundle::Importer
begin
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: true})
m_count = HealthDataStandards::CQM::Measure.count
r_count = Record.count
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: true})
assert_equal 1, HealthDataStandards::CQM::Bundle.count, "Should only be 1 bundle in the db "
assert_equal m_count, bundle.measures.count, "Only the measures loaded in the last bundle should be available"
assert_equal r_count, bundle.records.count, "Only the records loaded in the last bundle should be available"
rescue
puts $!
assert false, "Should not have errored attempting to load db with same version of bundle with delete existing"
end
end
def test_load_with_update
loader = HealthDataStandards::Import::Bundle::Importer
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: false})
measure = bundle.measures.where({:nqf_id => "0002"}).first
assert measure["name"] != "Name: 0002", "Measure name should not be Name: 0002"
bundle2 = loader.import(File.new(@b_2_0_2), {update_measures: true})
measure = bundle.measures.where({:nqf_id => "0002"}).first
measure.reload
assert_equal "Name: 0002", measure["name"] , "Measure name should be Name: 0002"
end
def test_load_without_update
assert_clean_db
loader = HealthDataStandards::Import::Bundle::Importer
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: false})
measure = bundle.measures.where({:nqf_id => "0002"}).first
name = measure["name"]
assert measure["name"] != "Name: 0002", "Measure name should not be Name: 0002"
bundle2 = loader.import(File.new(@b_2_0_2), {update_measures: false})
measure = bundle.measures.where({:nqf_id => "0002"}).first
measure.reload
assert_equal name , measure["name"] , "Measure name #{name} should equal #{measure.name} and should not have been updated"
end
def test_load
loader = HealthDataStandards::Import::Bundle::Importer
bundle = loader.import(File.new(@b_2_0_1), {delete_existing: false})
assert_equal 1, HealthDataStandards::CQM::Bundle.count , "Should be 1 bundle in the db"
assert_equal 2, HealthDataStandards::CQM::Measure.count , "Should be 12 measure in the db"
assert_equal HealthDataStandards::CQM::Measure.count, bundle.measures.count, "Number of measures total measures should equal number of measures in the db"
assert_equal 57 ,Record.count , "Should be 0 records in the db"
assert_equal 4780, @db["patient_cache"].where({}).count , "Should be 0 entries in the patient_cache "
#assert_equal 0, @db["query_cache"].where({}).count ,"Should be 0 entries in the query_cache "
bundle2 = loader.import(File.new(@b_2_0_2),{delete_existing: false})
assert_equal 2 , HealthDataStandards::CQM::Bundle.count , "Should be 2 bundle in the db"
assert_equal 5, HealthDataStandards::CQM::Measure.count , "Should be 4 measure in the db"
assert_equal 114, Record.count , "Should be 114 records in the db"
assert_equal 4780*2 , @db["patient_cache"].where({}).count , "Should be 0 entries in the patient_cache "
assert @db["query_cache"].where({}).count > 0 ,"Should be 0 more than entries in the query_cache "
measure_0002 = HealthDataStandards::CQM::Measure.where({"nqf_id" => "0002"})
assert_equal 2, measure_0002.count, "There should be 2 instances of measure 0002 in the db. One for each bundle"
measure_0003 = HealthDataStandards::CQM::Measure.where({"nqf_id" => "0003"})
assert_equal 2,measure_0003.count , "There should only be 2 measure 0003 in the db"
measure_0004 = HealthDataStandards::CQM::Measure.where({"nqf_id" => "0004"})
assert_equal 1,measure_0004.count , "There should only be 1 measure 0004 in the db"
assert_equal bundle2.id, measure_0004.first["bundle_id"], "Measure 0003 bundle should equal the bundle it was loaded from"
end
end
|
Xodarap/health-data-standards
|
test/unit/import/bundle/importer_test.rb
|
Ruby
|
apache-2.0
| 5,496
|
phantomjs CHANGELOG
===================
v1.0.1
------
- **CHANGELOG is deprecated - see [releases](https://github.com/customink-webops/phantomjs/releases)**
v1.0.0
------
- Added support for Windows
- Added tests and refactored code
v0.0.6
-------
- Initial CHANGELOG created
|
locomote-cookbooks/phantomjs
|
CHANGELOG.md
|
Markdown
|
apache-2.0
| 278
|
from functools import wraps
from itertools import chain
from django.db.models import Prefetch, Q
from django.urls import Resolver404, resolve
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, ParseError, PermissionDenied, ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, ViewSet
from shapely import prepared
from shapely.ops import cascaded_union
from c3nav.api.utils import get_api_post_data
from c3nav.editor.forms import ChangeSetForm, RejectForm
from c3nav.editor.models import ChangeSet
from c3nav.editor.utils import LevelChildEditUtils, SpaceChildEditUtils
from c3nav.editor.views.base import etag_func
from c3nav.mapdata.api import api_etag
from c3nav.mapdata.models import Area, MapUpdate, Source
from c3nav.mapdata.models.geometry.space import POI
from c3nav.mapdata.utils.user import can_access_editor
class EditorViewSetMixin(ViewSet):
def initial(self, request, *args, **kwargs):
if not can_access_editor(request):
raise PermissionDenied
return super().initial(request, *args, **kwargs)
def api_etag_with_update_cache_key(**outkwargs):
outkwargs.setdefault('cache_kwargs', {})['update_cache_key_match'] = bool
def wrapper(func):
func = api_etag(**outkwargs)(func)
@wraps(func)
def wrapped_func(self, request, *args, **kwargs):
try:
changeset = request.changeset
except AttributeError:
changeset = ChangeSet.get_for_request(request)
request.changeset = changeset
update_cache_key = request.changeset.raw_cache_key_without_changes
update_cache_key_match = request.GET.get('update_cache_key') == update_cache_key
return func(self, request, *args,
update_cache_key=update_cache_key, update_cache_key_match=update_cache_key_match,
**kwargs)
return wrapped_func
return wrapper
class EditorViewSet(EditorViewSetMixin, ViewSet):
"""
Editor API
/geometries/ returns a list of geojson features, you have to specify ?level=<id> or ?space=<id>
/geometrystyles/ returns styling information for all geometry types
/bounds/ returns the maximum bounds of the map
/{path}/ insert an editor path to get an API represantation of it. POST requests on forms are possible as well
"""
lookup_field = 'path'
lookup_value_regex = r'.+'
@staticmethod
def _get_level_geometries(level):
buildings = level.buildings.all()
buildings_geom = cascaded_union([building.geometry for building in buildings])
spaces = {space.pk: space for space in level.spaces.all()}
holes_geom = []
for space in spaces.values():
if space.outside:
space.geometry = space.geometry.difference(buildings_geom)
columns = [column.geometry for column in space.columns.all()]
if columns:
columns_geom = cascaded_union([column.geometry for column in space.columns.all()])
space.geometry = space.geometry.difference(columns_geom)
holes = [hole.geometry for hole in space.holes.all()]
if holes:
space_holes_geom = cascaded_union(holes)
holes_geom.append(space_holes_geom.intersection(space.geometry))
space.geometry = space.geometry.difference(space_holes_geom)
for building in buildings:
building.original_geometry = building.geometry
if holes_geom:
holes_geom = cascaded_union(holes_geom)
holes_geom_prep = prepared.prep(holes_geom)
for obj in buildings:
if holes_geom_prep.intersects(obj.geometry):
obj.geometry = obj.geometry.difference(holes_geom)
results = []
results.extend(buildings)
for door in level.doors.all():
results.append(door)
results.extend(spaces.values())
return results
@staticmethod
def _get_levels_pk(request, level):
# noinspection PyPep8Naming
Level = request.changeset.wrap_model('Level')
levels_under = ()
levels_on_top = ()
lower_level = level.lower(Level).first()
primary_levels = (level,) + ((lower_level,) if lower_level else ())
secondary_levels = Level.objects.filter(on_top_of__in=primary_levels).values_list('pk', 'on_top_of')
if lower_level:
levels_under = tuple(pk for pk, on_top_of in secondary_levels if on_top_of == lower_level.pk)
if True:
levels_on_top = tuple(pk for pk, on_top_of in secondary_levels if on_top_of == level.pk)
levels = chain([level.pk], levels_under, levels_on_top)
return levels, levels_on_top, levels_under
@staticmethod
def area_sorting_func(area):
groups = tuple(area.groups.all())
if not groups:
return (0, 0, 0)
return (1, groups[0].category.priority, groups[0].hierarchy, groups[0].priority)
# noinspection PyPep8Naming
@action(detail=False, methods=['get'])
@api_etag_with_update_cache_key(etag_func=etag_func, cache_parameters={'level': str, 'space': str})
def geometries(self, request, update_cache_key, update_cache_key_match, *args, **kwargs):
Level = request.changeset.wrap_model('Level')
Space = request.changeset.wrap_model('Space')
Column = request.changeset.wrap_model('Column')
Hole = request.changeset.wrap_model('Hole')
AltitudeMarker = request.changeset.wrap_model('AltitudeMarker')
Building = request.changeset.wrap_model('Building')
Door = request.changeset.wrap_model('Door')
LocationGroup = request.changeset.wrap_model('LocationGroup')
WifiMeasurement = request.changeset.wrap_model('WifiMeasurement')
level = request.GET.get('level')
space = request.GET.get('space')
if level is not None:
if space is not None:
raise ValidationError('Only level or space can be specified.')
level = get_object_or_404(Level.objects.filter(Level.q_for_request(request)), pk=level)
edit_utils = LevelChildEditUtils(level, request)
if not edit_utils.can_access_child_base_mapdata:
raise PermissionDenied
levels, levels_on_top, levels_under = self._get_levels_pk(request, level)
# don't prefetch groups for now as changesets do not yet work with m2m-prefetches
levels = Level.objects.filter(pk__in=levels).filter(Level.q_for_request(request))
# graphnodes_qs = request.changeset.wrap_model('GraphNode').objects.all()
levels = levels.prefetch_related(
Prefetch('spaces', Space.objects.filter(Space.q_for_request(request)).only(
'geometry', 'level', 'outside'
)),
Prefetch('doors', Door.objects.filter(Door.q_for_request(request)).only('geometry', 'level')),
Prefetch('spaces__columns', Column.objects.filter(
Q(access_restriction__isnull=True) | ~Column.q_for_request(request)
).only('geometry', 'space')),
Prefetch('spaces__groups', LocationGroup.objects.only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_spaces'
)),
Prefetch('buildings', Building.objects.only('geometry', 'level')),
Prefetch('spaces__holes', Hole.objects.only('geometry', 'space')),
Prefetch('spaces__altitudemarkers', AltitudeMarker.objects.only('geometry', 'space')),
Prefetch('spaces__wifi_measurements', WifiMeasurement.objects.only('geometry', 'space')),
# Prefetch('spaces__graphnodes', graphnodes_qs)
)
levels = {s.pk: s for s in levels}
level = levels[level.pk]
levels_under = [levels[pk] for pk in levels_under]
levels_on_top = [levels[pk] for pk in levels_on_top]
# todo: permissions
# graphnodes = tuple(chain(*(space.graphnodes.all()
# for space in chain(*(level.spaces.all() for level in levels.values())))))
# graphnodes_lookup = {node.pk: node for node in graphnodes}
# graphedges = request.changeset.wrap_model('GraphEdge').objects.all()
# graphedges = graphedges.filter(Q(from_node__in=graphnodes) | Q(to_node__in=graphnodes))
# graphedges = graphedges.select_related('waytype')
# this is faster because we only deserialize graphnode geometries once
# missing_graphnodes = graphnodes_qs.filter(pk__in=set(chain(*((edge.from_node_id, edge.to_node_id)
# for edge in graphedges))))
# graphnodes_lookup.update({node.pk: node for node in missing_graphnodes})
# for edge in graphedges:
# edge._from_node_cache = graphnodes_lookup[edge.from_node_id]
# edge._to_node_cache = graphnodes_lookup[edge.to_node_id]
# graphedges = [edge for edge in graphedges if edge.from_node.space_id != edge.to_node.space_id]
results = chain(
*(self._get_level_geometries(l) for l in levels_under),
self._get_level_geometries(level),
*(self._get_level_geometries(l) for l in levels_on_top),
*(space.altitudemarkers.all() for space in level.spaces.all()),
*(space.wifi_measurements.all() for space in level.spaces.all())
# graphedges,
# graphnodes,
)
elif space is not None:
space_q_for_request = Space.q_for_request(request)
qs = Space.objects.filter(space_q_for_request)
space = get_object_or_404(qs.select_related('level', 'level__on_top_of'), pk=space)
level = space.level
edit_utils = SpaceChildEditUtils(space, request)
if not edit_utils.can_access_child_base_mapdata:
raise PermissionDenied
if request.user_permissions.can_access_base_mapdata:
doors = [door for door in level.doors.filter(Door.q_for_request(request)).all()
if door.geometry.intersects(space.geometry)]
doors_space_geom = cascaded_union([door.geometry for door in doors]+[space.geometry])
levels, levels_on_top, levels_under = self._get_levels_pk(request, level.primary_level)
if level.on_top_of_id is not None:
levels = chain([level.pk], levels_on_top)
other_spaces = Space.objects.filter(space_q_for_request, level__pk__in=levels).only(
'geometry', 'level'
).prefetch_related(
Prefetch('groups', LocationGroup.objects.only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_spaces'
).filter(color__isnull=False))
)
space = next(s for s in other_spaces if s.pk == space.pk)
other_spaces = [s for s in other_spaces
if s.geometry.intersects(doors_space_geom) and s.pk != space.pk]
all_other_spaces = other_spaces
if level.on_top_of_id is None:
other_spaces_lower = [s for s in other_spaces if s.level_id in levels_under]
other_spaces_upper = [s for s in other_spaces if s.level_id in levels_on_top]
else:
other_spaces_lower = [s for s in other_spaces if s.level_id == level.on_top_of_id]
other_spaces_upper = []
other_spaces = [s for s in other_spaces if s.level_id == level.pk]
space.bounds = True
# deactivated for performance reasons
buildings = level.buildings.all()
# buildings_geom = cascaded_union([building.geometry for building in buildings])
# for other_space in other_spaces:
# if other_space.outside:
# other_space.geometry = other_space.geometry.difference(buildings_geom)
for other_space in chain(other_spaces, other_spaces_lower, other_spaces_upper):
other_space.opacity = 0.4
other_space.color = '#ffffff'
for building in buildings:
building.opacity = 0.5
else:
buildings = []
doors = []
other_spaces = []
other_spaces_lower = []
other_spaces_upper = []
all_other_spaces = []
# todo: permissions
if request.user_permissions.can_access_base_mapdata:
graphnodes = request.changeset.wrap_model('GraphNode').objects.all()
graphnodes = graphnodes.filter((Q(space__in=all_other_spaces)) | Q(space__pk=space.pk))
space_graphnodes = tuple(node for node in graphnodes if node.space_id == space.pk)
graphedges = request.changeset.wrap_model('GraphEdge').objects.all()
space_graphnodes_ids = tuple(node.pk for node in space_graphnodes)
graphedges = graphedges.filter(Q(from_node__pk__in=space_graphnodes_ids) |
Q(to_node__pk__in=space_graphnodes_ids))
graphedges = graphedges.select_related('from_node', 'to_node', 'waytype').only(
'from_node__geometry', 'to_node__geometry', 'waytype__color'
)
else:
graphnodes = []
graphedges = []
areas = space.areas.filter(Area.q_for_request(request)).only(
'geometry', 'space'
).prefetch_related(
Prefetch('groups', LocationGroup.objects.order_by(
'-category__priority', '-hierarchy', '-priority'
).only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_areas'
))
)
for area in areas:
area.opacity = 0.5
areas = sorted(areas, key=self.area_sorting_func)
results = chain(
buildings,
other_spaces_lower,
doors,
other_spaces,
[space],
areas,
space.holes.all().only('geometry', 'space'),
space.stairs.all().only('geometry', 'space'),
space.ramps.all().only('geometry', 'space'),
space.obstacles.all().only('geometry', 'space', 'color'),
space.lineobstacles.all().only('geometry', 'width', 'space', 'color'),
space.columns.all().only('geometry', 'space'),
space.altitudemarkers.all().only('geometry', 'space'),
space.wifi_measurements.all().only('geometry', 'space'),
space.pois.filter(POI.q_for_request(request)).only('geometry', 'space').prefetch_related(
Prefetch('groups', LocationGroup.objects.only(
'color', 'category', 'priority', 'hierarchy', 'category__priority', 'category__allow_pois'
).filter(color__isnull=False))
),
other_spaces_upper,
graphedges,
graphnodes
)
else:
raise ValidationError('No level or space specified.')
return Response(list(chain(
[('update_cache_key', update_cache_key)],
(self.conditional_geojson(obj, update_cache_key_match) for obj in results)
)))
def conditional_geojson(self, obj, update_cache_key_match):
if update_cache_key_match and not obj._affected_by_changeset:
return obj.get_geojson_key()
result = obj.to_geojson(instance=obj)
result['properties']['changed'] = obj._affected_by_changeset
return result
@action(detail=False, methods=['get'])
@api_etag(etag_func=MapUpdate.current_cache_key, cache_parameters={})
def geometrystyles(self, request, *args, **kwargs):
return Response({
'building': '#aaaaaa',
'space': '#eeeeee',
'hole': 'rgba(255, 0, 0, 0.3)',
'door': '#ffffff',
'area': '#55aaff',
'stair': '#a000a0',
'ramp': 'rgba(160, 0, 160, 0.2)',
'obstacle': '#999999',
'lineobstacle': '#999999',
'column': 'rgba(0, 0, 50, 0.3)',
'poi': '#4488cc',
'shadow': '#000000',
'graphnode': '#009900',
'graphedge': '#00CC00',
'altitudemarker': '#0000FF',
'wifimeasurement': '#DDDD00',
})
@action(detail=False, methods=['get'])
@api_etag(etag_func=etag_func, cache_parameters={})
def bounds(self, request, *args, **kwargs):
return Response({
'bounds': Source.max_bounds(),
})
def __getattr__(self, name):
# allow POST and DELETE methods for the editor API
if getattr(self, 'get', None).__name__ in ('list', 'retrieve'):
if name == 'post' and (self.resolved.url_name.endswith('.create') or
self.resolved.url_name.endswith('.edit')):
return self.post_or_delete
if name == 'delete' and self.resolved.url_name.endswith('.edit'):
return self.post_or_delete
raise AttributeError
def post_or_delete(self, request, *args, **kwargs):
# django-rest-framework doesn't automatically do this for logged out requests
SessionAuthentication().enforce_csrf(request)
return self.retrieve(request, *args, **kwargs)
def list(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
@cached_property
def resolved(self):
resolved = None
path = self.kwargs.get('path', '')
if path:
try:
resolved = resolve('/editor/'+path+'/')
except Resolver404:
pass
if not resolved:
try:
resolved = resolve('/editor/'+path)
except Resolver404:
pass
self.request.sub_resolver_match = resolved
return resolved
def retrieve(self, request, *args, **kwargs):
resolved = self.resolved
if not resolved:
raise NotFound(_('No matching editor view endpoint found.'))
if not getattr(resolved.func, 'api_hybrid', False):
raise NotFound(_('Matching editor view point does not provide an API.'))
get_api_post_data(request)
response = resolved.func(request, api=True, *resolved.args, **resolved.kwargs)
return response
class ChangeSetViewSet(EditorViewSetMixin, ReadOnlyModelViewSet):
"""
List and manipulate changesets. All lists are ordered by last update descending. Use ?offset= to specify an offset.
Don't forget to set X-Csrftoken for POST requests!
/ lists all changesets this user can see.
/user/ lists changesets by this user
/reviewing/ lists changesets this user is currently reviewing.
/pending_review/ lists changesets this user can review.
/current/ returns the current changeset.
/direct_editing/ POST to activate direct editing (if available).
/deactive/ POST to deactivate current changeset or deactivate direct editing
/{id}/changes/ list all changes of a given changeset.
/{id}/activate/ POST to activate given changeset.
/{id}/edit/ POST to edit given changeset (provide title and description in POST data).
/{id}/restore_object/ POST to restore an object deleted by this changeset (provide change id as id in POST data).
/{id}/delete/ POST to delete given changeset.
/{id}/propose/ POST to propose given changeset.
/{id}/unpropose/ POST to unpropose given changeset.
/{id}/review/ POST to review given changeset.
/{id}/reject/ POST to reject given changeset (provide reject=1 in POST data for final rejection).
/{id}/unreject/ POST to unreject given changeset.
/{id}/apply/ POST to accept and apply given changeset.
"""
queryset = ChangeSet.objects.all()
def get_queryset(self):
return ChangeSet.qs_for_request(self.request).select_related('last_update', 'last_state_update', 'last_change')
def _list(self, request, qs):
offset = 0
if 'offset' in request.GET:
if not request.GET['offset'].isdigit():
raise ParseError('offset has to be a positive integer.')
offset = int(request.GET['offset'])
return Response([obj.serialize() for obj in qs.order_by('-last_update')[offset:offset+20]])
def list(self, request, *args, **kwargs):
return self._list(request, self.get_queryset())
@action(detail=False, methods=['get'])
def user(self, request, *args, **kwargs):
return self._list(request, self.get_queryset().filter(author=request.user))
@action(detail=False, methods=['get'])
def reviewing(self, request, *args, **kwargs):
return self._list(request, self.get_queryset().filter(
assigned_to=request.user, state='review'
))
@action(detail=False, methods=['get'])
def pending_review(self, request, *args, **kwargs):
return self._list(request, self.get_queryset().filter(
state__in=('proposed', 'reproposed'),
))
def retrieve(self, request, *args, **kwargs):
return Response(self.get_object().serialize())
@action(detail=False, methods=['get'])
def current(self, request, *args, **kwargs):
changeset = ChangeSet.get_for_request(request)
return Response({
'direct_editing': changeset.direct_editing,
'changeset': changeset.serialize() if changeset.pk else None,
})
@action(detail=False, methods=['post'])
def direct_editing(self, request, *args, **kwargs):
# django-rest-framework doesn't automatically do this for logged out requests
SessionAuthentication().enforce_csrf(request)
if not ChangeSet.can_direct_edit(request):
raise PermissionDenied(_('You don\'t have the permission to activate direct editing.'))
changeset = ChangeSet.get_for_request(request)
if changeset.pk is not None:
raise PermissionDenied(_('You cannot activate direct editing if you have an active changeset.'))
request.session['direct_editing'] = True
return Response({
'success': True,
})
@action(detail=False, methods=['post'])
def deactivate(self, request, *args, **kwargs):
# django-rest-framework doesn't automatically do this for logged out requests
SessionAuthentication().enforce_csrf(request)
request.session.pop('changeset', None)
request.session['direct_editing'] = False
return Response({
'success': True,
})
@action(detail=True, methods=['get'])
def changes(self, request, *args, **kwargs):
changeset = self.get_object()
changeset.fill_changes_cache()
return Response([obj.serialize() for obj in changeset.iter_changed_objects()])
@action(detail=True, methods=['post'])
def activate(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_activate(request):
raise PermissionDenied(_('You can not activate this change set.'))
changeset.activate(request)
return Response({'success': True})
@action(detail=True, methods=['post'])
def edit(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_edit(request):
raise PermissionDenied(_('You cannot edit this change set.'))
form = ChangeSetForm(instance=changeset, data=get_api_post_data(request))
if not form.is_valid():
raise ParseError(form.errors)
changeset = form.instance
update = changeset.updates.create(user=request.user,
title=changeset.title, description=changeset.description)
changeset.last_update = update
changeset.save()
return Response({'success': True})
@action(detail=True, methods=['post'])
def restore_object(self, request, *args, **kwargs):
data = get_api_post_data(request)
if 'id' not in data:
raise ParseError('Missing id.')
restore_id = data['id']
if isinstance(restore_id, str) and restore_id.isdigit():
restore_id = int(restore_id)
if not isinstance(restore_id, int):
raise ParseError('id needs to be an integer.')
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_edit(request):
raise PermissionDenied(_('You can not edit changes on this change set.'))
try:
changed_object = changeset.changed_objects_set.get(pk=restore_id)
except Exception:
raise NotFound('could not find object.')
try:
changed_object.restore()
except PermissionError:
raise PermissionDenied(_('You cannot restore this object, because it depends on '
'a deleted object or it would violate a unique contraint.'))
return Response({'success': True})
@action(detail=True, methods=['post'])
def propose(self, request, *args, **kwargs):
if not request.user.is_authenticated:
raise PermissionDenied(_('You need to log in to propose changes.'))
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.title or not changeset.description:
raise PermissionDenied(_('You need to add a title an a description to propose this change set.'))
if not changeset.can_propose(request):
raise PermissionDenied(_('You cannot propose this change set.'))
changeset.propose(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def unpropose(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_unpropose(request):
raise PermissionDenied(_('You cannot unpropose this change set.'))
changeset.unpropose(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def review(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_start_review(request):
raise PermissionDenied(_('You cannot review these changes.'))
changeset.start_review(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def reject(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not not changeset.can_end_review(request):
raise PermissionDenied(_('You cannot reject these changes.'))
form = RejectForm(get_api_post_data(request))
if not form.is_valid():
raise ParseError(form.errors)
changeset.reject(request.user, form.cleaned_data['comment'], form.cleaned_data['final'])
return Response({'success': True})
@action(detail=True, methods=['post'])
def unreject(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_unreject(request):
raise PermissionDenied(_('You cannot unreject these changes.'))
changeset.unreject(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def apply(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_end_review(request):
raise PermissionDenied(_('You cannot accept and apply these changes.'))
changeset.apply(request.user)
return Response({'success': True})
@action(detail=True, methods=['post'])
def delete(self, request, *args, **kwargs):
changeset = self.get_object()
with changeset.lock_to_edit(request) as changeset:
if not changeset.can_delete(request):
raise PermissionDenied(_('You cannot delete this change set.'))
changeset.delete()
return Response({'success': True})
|
c3nav/c3nav
|
src/c3nav/editor/api.py
|
Python
|
apache-2.0
| 29,810
|
using NMF.Collections.Generic;
using NMF.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
namespace NMF.Expressions
{
internal abstract class ModelExpressionVisitorBase<TState> : ExpressionVisitorBase
{
public abstract class PropertyChainNode
{
public abstract ParameterExpression Parameter { get; }
public abstract bool ContainsCrossReference();
public abstract PropertyChainNode Rebase(PropertyChainNode newBase);
public abstract Type Type { get; }
public abstract PropertyChainNode Base { get; }
}
public class ParameterReference : PropertyChainNode
{
private ParameterExpression parameter;
public ParameterReference(ParameterExpression parameter)
{
this.parameter = parameter;
}
public override PropertyChainNode Base
{
get
{
return null;
}
}
public override ParameterExpression Parameter
{
get
{
return parameter;
}
}
public override Type Type
{
get
{
return parameter.Type;
}
}
public override bool ContainsCrossReference()
{
return false;
}
public override PropertyChainNode Rebase(PropertyChainNode newBase)
{
return newBase;
}
}
public class PropertyAccess : PropertyChainNode
{
public PropertyAccess(PropertyChainNode baseNode, PropertyInfo property, bool isCrossReference)
{
this.baseNode = baseNode;
Property = property;
IsCrossReference = isCrossReference;
}
private PropertyChainNode baseNode;
public override PropertyChainNode Base
{
get
{
return baseNode;
}
}
public override ParameterExpression Parameter
{
get
{
return Base.Parameter;
}
}
public PropertyInfo Property { get; private set; }
public string PropertyName
{
get
{
return Property.Name;
}
}
public bool IsCrossReference { get; private set; }
public override Type Type
{
get
{
var collectionType = FindEnumerableExpressionType(Property.PropertyType);
if (collectionType != null)
{
return collectionType.GetGenericArguments()[0];
}
else
{
return Property.PropertyType;
}
}
}
public Type Anchor
{
get
{
var anchorAttributes = Property.GetCustomAttributes(typeof(AnchorAttribute), true);
if (anchorAttributes != null && anchorAttributes.Length > 0)
{
return ((AnchorAttribute)anchorAttributes[0]).AnchorType;
}
else
{
return null;
}
}
}
public bool IsAnchorEffective(Type anchor)
{
if (anchor != null)
{
var current = Base;
while (current != null)
{
if (anchor.IsAssignableFrom(current.Type))
{
return false;
}
current = current.Base;
}
}
return true;
}
public override bool ContainsCrossReference()
{
if (IsCrossReference)
{
var anchor = Anchor;
if (anchor == null || !IsAnchorEffective(anchor))
{
return true;
}
}
return Base.ContainsCrossReference();
}
public override PropertyChainNode Rebase(PropertyChainNode newBase)
{
return new PropertyAccess(Base.Rebase(newBase), Property, IsCrossReference);
}
}
public List<ParameterExpression> ListParameters()
{
return propertyAccesses.Select(a => a.Parameter).Distinct().ToList();
}
private readonly LooselyLinkedList<PropertyChainNode> propertyAccesses = new LooselyLinkedList<PropertyChainNode>();
protected ICollection<PropertyChainNode> PropertyAccesses
{
get
{
return propertyAccesses;
}
}
private static bool IsImmutableMethod(MethodInfo method)
{
var immutableMethodAttributes = method.GetCustomAttributes(typeof(ImmutableMethodAttribute), true);
if (immutableMethodAttributes != null && immutableMethodAttributes.Length > 0) return true;
return IsOnlyImmutableTypesAsArguments(method) || IsCollectionMethod(method);
}
private static bool IsCollectionMethod(MethodInfo method)
{
var type = method.DeclaringType;
if (!type.IsGenericType) return false;
type = type.GetGenericTypeDefinition();
return type == typeof(ICollection<>) || type == typeof(IList<>);
}
private static bool IsOnlyImmutableTypesAsArguments(MethodInfo method)
{
if (!method.IsStatic && !IsImmutableType(method.DeclaringType)) return false;
var parameters = method.GetParameters();
if (parameters != null)
{
for (int i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
if (parameter.IsOut) return false;
if (!IsImmutableType(parameter.ParameterType)) return false;
}
}
return true;
}
private static bool IsImmutableType(Type type)
{
if (type.IsValueType || type == typeof(string) || type == typeof(Uri)) return true;
var immutableObjectAttributes = type.GetCustomAttributes(typeof(ImmutableObjectAttribute), false);
if (immutableObjectAttributes != null && immutableObjectAttributes.Length > 0)
{
var immutable = (ImmutableObjectAttribute)immutableObjectAttributes[0];
return immutable.Immutable;
}
var generatedTypeAttributes = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false);
if (generatedTypeAttributes != null && generatedTypeAttributes.Length > 0)
{
// Compiler-generated classes (especially used for LINQ) are treated as immutable as they are
// usually taking inputs as constructor arguments
return true;
}
return false;
}
private static bool IsContainmentProperty(PropertyInfo property)
{
if (property.DeclaringType.IsValueType) return true;
return HasAttribute(property, typeof(ContainmentAttribute), true);
}
private static bool HasAttribute(MemberInfo member, Type attributeType, bool inherit)
{
var attributes = member.GetCustomAttributes(attributeType, inherit);
return attributes != null && attributes.Length > 0;
}
protected override Expression VisitMember(MemberExpression node)
{
var property = node.Member as PropertyInfo;
if (property != null && IsModelProperty(property))
{
var newExpression = Visit(node.Expression);
var isContainment = IsContainmentProperty(property);
var isCrossReference = !isContainment && typeof(IModelElement).IsAssignableFrom(property.PropertyType);
foreach (var propertyAccess in propertyAccesses.Nodes)
{
var parameter = propertyAccess.Value.Parameter;
if (propertyAccess.Value.ContainsCrossReference() && node.Expression != parameter)
{
Expression returnVal;
if (ResetForCrossReference(node.Expression, property, isCrossReference, out returnVal))
{
return returnVal;
}
}
propertyAccess.Value = new PropertyAccess(propertyAccess.Value, property, isCrossReference);
}
if (newExpression != node.Expression)
{
return node.Update(newExpression);
}
return node;
}
else
{
return base.VisitMember(node);
}
}
protected abstract bool ResetForCrossReference(Expression targetExpression, PropertyInfo property, bool isCrossReference, out Expression returnValue);
protected abstract bool ResetForLambdaExpression(TState state, MethodCallExpression methodCall, LambdaExpression lambda, out Expression returnValue);
protected virtual bool IsModelProperty(PropertyInfo property)
{
if (property == null) throw new ArgumentNullException("property");
return typeof(IModelElement).IsAssignableFrom(property.DeclaringType);
}
private static bool IsGenericEnumerableExpression(Type type)
{
return type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerableExpression<>);
}
private static Type FindEnumerableExpressionType(Type type)
{
// Could be generic enumerable expression itself
if (IsGenericEnumerableExpression(type))
{
return type;
}
// Otherwise, IEnumerableExpression is one of its implemented interfaces
return type.GetInterfaces().FirstOrDefault(IsGenericEnumerableExpression);
}
protected override Expression VisitConditional(ConditionalExpression node)
{
var test = Visit(node.Test);
var testPropertyAccesses = propertyAccesses.First.Next;
propertyAccesses.Clear();
var ifTrue = Visit(node.IfTrue);
var truePropertyAccesses = propertyAccesses.First.Next;
var ifFalse = Visit(node.IfFalse);
if (truePropertyAccesses != null) propertyAccesses.AddFirst(truePropertyAccesses);
if (testPropertyAccesses != null) propertyAccesses.AddFirst(testPropertyAccesses);
if (test != node.Test || ifTrue != node.IfTrue || ifFalse != node.IfFalse)
{
return node.Update(test, ifTrue, ifFalse);
}
return node;
}
protected override Expression VisitBinary(BinaryExpression node)
{
var right = Visit(node.Right);
var rightPropertyAccesses = propertyAccesses.First.Next;
propertyAccesses.Clear();
var left = Visit(node.Left);
var leftPropertyAccesses = propertyAccesses.First.Next;
propertyAccesses.Clear();
var conversion = node.Conversion != null ? Visit(node.Conversion) : null;
if (leftPropertyAccesses != null) propertyAccesses.AddFirst(leftPropertyAccesses);
if (rightPropertyAccesses != null) propertyAccesses.AddFirst(rightPropertyAccesses);
if (left != node.Left || right != node.Right || conversion != node.Conversion)
{
return node.Update(left, node.Conversion, right);
}
return node;
}
protected override Expression VisitParameter(ParameterExpression node)
{
propertyAccesses.Add(new ParameterReference(node));
return base.VisitParameter(node);
}
protected abstract TState SaveState();
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var state = SaveState();
var remaps = ReflectionHelper.GetCustomAttributes<ParameterDataflowAttribute>(node.Method, true);
var method = node.Method;
var methodParameters = method.GetParameters();
var changed = false;
var arguments = new Expression[node.Arguments.Count];
var propertyAccessArray = new LooselyLinkedListNode<PropertyChainNode>[node.Arguments.Count];
var ghostAccessArray = new LooselyLinkedListNode<PropertyChainNode>[node.Arguments.Count];
for (int i = 0; i < node.Arguments.Count; i++)
{
var arg = node.Arguments[i];
var argument = Visit(arg);
arguments[i] = argument;
changed |= argument != arg;
propertyAccessArray[i] = propertyAccesses.First.Next;
propertyAccesses.Clear();
}
Expression obj = node.Object;
if (obj != null)
{
obj = Visit(node.Object);
changed |= obj != node.Object;
}
var objectPropertyAccesses = propertyAccesses.First.Next;
propertyAccesses.Clear();
var defaultList = Enumerable.Range(0, node.Arguments.Count).ToList();
for (int i = 0; i < node.Arguments.Count; i++)
{
if (propertyAccessArray[i] == null) continue;
defaultList[i] = -2;
var lambda = FindLambdaExpression(node.Arguments[i]);
if (lambda != null)
{
var remapsforLambda = remaps.Where(a => a.FunctionIndex == i);
var argumentMaps = new List<int>[lambda.Parameters.Count];
foreach (var remap in remapsforLambda)
{
List<int> remapForArgument = argumentMaps[remap.SourceIndex];
if (remapForArgument == null)
{
remapForArgument = new List<int>();
argumentMaps[remap.SourceIndex] = remapForArgument;
}
remapForArgument.Add(remap.FunctionParameterIndex);
}
for (int j = 0; j < lambda.Parameters.Count; j++)
{
var parameter = lambda.Parameters[j];
var dependencies = argumentMaps[j] ?? defaultList;
var dummy = LooselyLinkedListNode<PropertyChainNode>.CreateDummyFor(propertyAccessArray[i]);
var ghostDummy = LooselyLinkedListNode<PropertyChainNode>.CreateDummyFor(ghostAccessArray[i]);
var current = dummy;
var currentGhost = ghostDummy;
while (current.Next != null)
{
if (current.Next.Value.Parameter == parameter)
{
var access = current.Next.Value;
current.CutNext();
foreach (var dependency in dependencies)
{
if (dependency == -2) continue;
PropagatePropertyAccesses(propertyAccessArray, objectPropertyAccesses, ref current, ref currentGhost, access, dependency);
PropagatePropertyAccesses(ghostAccessArray, null, ref current, ref currentGhost, access, dependency);
}
}
else
{
current = current.Next;
}
}
propertyAccessArray[i] = dummy.Next;
}
Expression returnValue;
if (ResetForLambdaExpression(state, node, lambda, out returnValue))
{
return returnValue;
}
}
defaultList[i] = i;
}
if (objectPropertyAccesses != null)
{
propertyAccesses.AddFirst(objectPropertyAccesses);
}
for (int i = node.Arguments.Count - 1; i >= 0; i--)
{
if (propertyAccessArray[i] != null)
{
propertyAccesses.AddFirst(propertyAccessArray[i]);
}
}
if (changed)
{
return node.Update(obj, arguments);
}
return node;
}
protected override Expression VisitNew(NewExpression node)
{
var state = SaveState();
var method = node.Constructor;
var methodParameters = method.GetParameters();
var changed = false;
var arguments = new Expression[node.Arguments.Count];
var propertyAccessArray = new LooselyLinkedListNode<PropertyChainNode>[node.Arguments.Count];
var ghostAccessArray = new LooselyLinkedListNode<PropertyChainNode>[node.Arguments.Count];
for (int i = 0; i < node.Arguments.Count; i++)
{
var arg = node.Arguments[i];
var argument = Visit(arg);
arguments[i] = argument;
changed |= argument != arg;
propertyAccessArray[i] = propertyAccesses.First.Next;
propertyAccesses.Clear();
}
var defaultList = Enumerable.Range(0, node.Arguments.Count).ToList();
for (int i = 0; i < node.Arguments.Count; i++)
{
if (propertyAccessArray[i] == null) continue;
defaultList[i] = -2;
var lambda = FindLambdaExpression(node.Arguments[i]);
if (lambda != null)
{
for (int j = 0; j < lambda.Parameters.Count; j++)
{
var parameter = lambda.Parameters[j];
var dependencies = defaultList;
var dummy = LooselyLinkedListNode<PropertyChainNode>.CreateDummyFor(propertyAccessArray[i]);
var ghostDummy = LooselyLinkedListNode<PropertyChainNode>.CreateDummyFor(ghostAccessArray[i]);
var current = dummy;
var currentGhost = ghostDummy;
while (current.Next != null)
{
if (current.Next.Value.Parameter == parameter)
{
var access = current.Next.Value;
current.CutNext();
foreach (var dependency in dependencies)
{
if (dependency == -2) continue;
PropagatePropertyAccesses(propertyAccessArray, null, ref current, ref currentGhost, access, dependency);
PropagatePropertyAccesses(ghostAccessArray, null, ref current, ref currentGhost, access, dependency);
}
}
else
{
current = current.Next;
}
}
propertyAccessArray[i] = dummy.Next;
}
}
defaultList[i] = i;
}
for (int i = node.Arguments.Count - 1; i >= 0; i--)
{
if (propertyAccessArray[i] != null)
{
propertyAccesses.AddFirst(propertyAccessArray[i]);
}
}
if (changed)
{
return node.Update(arguments);
}
return node;
}
private void PropagatePropertyAccesses(LooselyLinkedListNode<PropertyChainNode>[] propertyAccessArray, LooselyLinkedListNode<PropertyChainNode> objectPropertyAccesses, ref LooselyLinkedListNode<PropertyChainNode> current, ref LooselyLinkedListNode<PropertyChainNode> currentGhost, PropertyChainNode access, int dependency)
{
LooselyLinkedListNode<PropertyChainNode> dependentParameters;
if (dependency == ParameterDataflowAttribute.TargetObjectIndex)
{
dependentParameters = objectPropertyAccesses;
}
else
{
dependentParameters = propertyAccessArray[dependency];
}
if (dependentParameters == null) return;
foreach (var p in dependentParameters.FromHere)
{
var rebased = access.Rebase(p);
var newNode = new LooselyLinkedListNode<PropertyChainNode>(rebased);
if (rebased != access)
{
propertyAccesses.AddAfter(current, newNode);
current = newNode;
}
else
{
propertyAccesses.AddAfter(currentGhost, newNode);
currentGhost = newNode;
}
}
}
private LambdaExpression FindLambdaExpression(Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Lambda:
return (LambdaExpression)expression;
case ExpressionType.Quote:
var quote = (UnaryExpression)expression;
while (quote.Operand.NodeType == ExpressionType.Quote)
{
quote = (UnaryExpression)quote.Operand;
}
return (LambdaExpression)quote.Operand;
default:
return null;
}
}
}
}
|
georghinkel/NMF
|
Expressions/Models.Expressions/ModelExpressionVisitorBase.cs
|
C#
|
apache-2.0
| 23,129
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Sep 03 20:00:47 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>AccessControlProtos.RevokeRequestOrBuilder (HBase 0.98.6-hadoop2 API)</title>
<meta name="date" content="2014-09-03">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="AccessControlProtos.RevokeRequestOrBuilder (HBase 0.98.6-hadoop2 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AccessControlProtos.RevokeRequestOrBuilder.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequestOrBuilder.html" target="_top">Frames</a></li>
<li><a href="AccessControlProtos.RevokeRequestOrBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.hadoop.hbase.protobuf.generated</div>
<h2 title="Interface AccessControlProtos.RevokeRequestOrBuilder" class="title">Interface AccessControlProtos.RevokeRequestOrBuilder</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd>com.google.protobuf.MessageLiteOrBuilder, com.google.protobuf.MessageOrBuilder</dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos.RevokeRequest</a>, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos.RevokeRequest.Builder</a></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos</a></dd>
</dl>
<hr>
<br>
<pre>public static interface <span class="strong">AccessControlProtos.RevokeRequestOrBuilder</span>
extends com.google.protobuf.MessageOrBuilder</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.UserPermission.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos.UserPermission</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequestOrBuilder.html#getUserPermission()">getUserPermission</a></strong>()</code>
<div class="block"><code>required .UserPermission user_permission = 1;</code></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.UserPermissionOrBuilder.html" title="interface in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos.UserPermissionOrBuilder</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequestOrBuilder.html#getUserPermissionOrBuilder()">getUserPermissionOrBuilder</a></strong>()</code>
<div class="block"><code>required .UserPermission user_permission = 1;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequestOrBuilder.html#hasUserPermission()">hasUserPermission</a></strong>()</code>
<div class="block"><code>required .UserPermission user_permission = 1;</code></div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageOrBuilder">
<!-- -->
</a>
<h3>Methods inherited from interface com.google.protobuf.MessageOrBuilder</h3>
<code>findInitializationErrors, getAllFields, getDefaultInstanceForType, getDescriptorForType, getField, getInitializationErrorString, getRepeatedField, getRepeatedFieldCount, getUnknownFields, hasField</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageLiteOrBuilder">
<!-- -->
</a>
<h3>Methods inherited from interface com.google.protobuf.MessageLiteOrBuilder</h3>
<code>isInitialized</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="hasUserPermission()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasUserPermission</h4>
<pre>boolean hasUserPermission()</pre>
<div class="block"><code>required .UserPermission user_permission = 1;</code></div>
</li>
</ul>
<a name="getUserPermission()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getUserPermission</h4>
<pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.UserPermission.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos.UserPermission</a> getUserPermission()</pre>
<div class="block"><code>required .UserPermission user_permission = 1;</code></div>
</li>
</ul>
<a name="getUserPermissionOrBuilder()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getUserPermissionOrBuilder</h4>
<pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.UserPermissionOrBuilder.html" title="interface in org.apache.hadoop.hbase.protobuf.generated">AccessControlProtos.UserPermissionOrBuilder</a> getUserPermissionOrBuilder()</pre>
<div class="block"><code>required .UserPermission user_permission = 1;</code></div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AccessControlProtos.RevokeRequestOrBuilder.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequestOrBuilder.html" target="_top">Frames</a></li>
<li><a href="AccessControlProtos.RevokeRequestOrBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
|
lshain/hbase-0.98.6-hadoop2
|
docs/devapidocs/org/apache/hadoop/hbase/protobuf/generated/AccessControlProtos.RevokeRequestOrBuilder.html
|
HTML
|
apache-2.0
| 11,633
|
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedProductBiddingCategoryConstantServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetProductBiddingCategoryConstantRequestObject()
{
moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient> mockGrpcClient = new moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient>(moq::MockBehavior.Strict);
GetProductBiddingCategoryConstantRequest request = new GetProductBiddingCategoryConstantRequest
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
};
gagvr::ProductBiddingCategoryConstant expectedResponse = new gagvr::ProductBiddingCategoryConstant
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
Level = gagve::ProductBiddingCategoryLevelEnum.Types.ProductBiddingCategoryLevel.Unknown,
Status = gagve::ProductBiddingCategoryStatusEnum.Types.ProductBiddingCategoryStatus.Active,
Id = -6774108720365892680L,
CountryCode = "country_code8debec55",
ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
LanguageCode = "language_code2f6c7160",
LocalizedName = "localized_namefc402dfa",
};
mockGrpcClient.Setup(x => x.GetProductBiddingCategoryConstant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProductBiddingCategoryConstantServiceClient client = new ProductBiddingCategoryConstantServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ProductBiddingCategoryConstant response = client.GetProductBiddingCategoryConstant(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetProductBiddingCategoryConstantRequestObjectAsync()
{
moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient> mockGrpcClient = new moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient>(moq::MockBehavior.Strict);
GetProductBiddingCategoryConstantRequest request = new GetProductBiddingCategoryConstantRequest
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
};
gagvr::ProductBiddingCategoryConstant expectedResponse = new gagvr::ProductBiddingCategoryConstant
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
Level = gagve::ProductBiddingCategoryLevelEnum.Types.ProductBiddingCategoryLevel.Unknown,
Status = gagve::ProductBiddingCategoryStatusEnum.Types.ProductBiddingCategoryStatus.Active,
Id = -6774108720365892680L,
CountryCode = "country_code8debec55",
ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
LanguageCode = "language_code2f6c7160",
LocalizedName = "localized_namefc402dfa",
};
mockGrpcClient.Setup(x => x.GetProductBiddingCategoryConstantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ProductBiddingCategoryConstant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProductBiddingCategoryConstantServiceClient client = new ProductBiddingCategoryConstantServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ProductBiddingCategoryConstant responseCallSettings = await client.GetProductBiddingCategoryConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::ProductBiddingCategoryConstant responseCancellationToken = await client.GetProductBiddingCategoryConstantAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetProductBiddingCategoryConstant()
{
moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient> mockGrpcClient = new moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient>(moq::MockBehavior.Strict);
GetProductBiddingCategoryConstantRequest request = new GetProductBiddingCategoryConstantRequest
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
};
gagvr::ProductBiddingCategoryConstant expectedResponse = new gagvr::ProductBiddingCategoryConstant
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
Level = gagve::ProductBiddingCategoryLevelEnum.Types.ProductBiddingCategoryLevel.Unknown,
Status = gagve::ProductBiddingCategoryStatusEnum.Types.ProductBiddingCategoryStatus.Active,
Id = -6774108720365892680L,
CountryCode = "country_code8debec55",
ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
LanguageCode = "language_code2f6c7160",
LocalizedName = "localized_namefc402dfa",
};
mockGrpcClient.Setup(x => x.GetProductBiddingCategoryConstant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProductBiddingCategoryConstantServiceClient client = new ProductBiddingCategoryConstantServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ProductBiddingCategoryConstant response = client.GetProductBiddingCategoryConstant(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetProductBiddingCategoryConstantAsync()
{
moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient> mockGrpcClient = new moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient>(moq::MockBehavior.Strict);
GetProductBiddingCategoryConstantRequest request = new GetProductBiddingCategoryConstantRequest
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
};
gagvr::ProductBiddingCategoryConstant expectedResponse = new gagvr::ProductBiddingCategoryConstant
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
Level = gagve::ProductBiddingCategoryLevelEnum.Types.ProductBiddingCategoryLevel.Unknown,
Status = gagve::ProductBiddingCategoryStatusEnum.Types.ProductBiddingCategoryStatus.Active,
Id = -6774108720365892680L,
CountryCode = "country_code8debec55",
ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
LanguageCode = "language_code2f6c7160",
LocalizedName = "localized_namefc402dfa",
};
mockGrpcClient.Setup(x => x.GetProductBiddingCategoryConstantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ProductBiddingCategoryConstant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProductBiddingCategoryConstantServiceClient client = new ProductBiddingCategoryConstantServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ProductBiddingCategoryConstant responseCallSettings = await client.GetProductBiddingCategoryConstantAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::ProductBiddingCategoryConstant responseCancellationToken = await client.GetProductBiddingCategoryConstantAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetProductBiddingCategoryConstantResourceNames()
{
moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient> mockGrpcClient = new moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient>(moq::MockBehavior.Strict);
GetProductBiddingCategoryConstantRequest request = new GetProductBiddingCategoryConstantRequest
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
};
gagvr::ProductBiddingCategoryConstant expectedResponse = new gagvr::ProductBiddingCategoryConstant
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
Level = gagve::ProductBiddingCategoryLevelEnum.Types.ProductBiddingCategoryLevel.Unknown,
Status = gagve::ProductBiddingCategoryStatusEnum.Types.ProductBiddingCategoryStatus.Active,
Id = -6774108720365892680L,
CountryCode = "country_code8debec55",
ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
LanguageCode = "language_code2f6c7160",
LocalizedName = "localized_namefc402dfa",
};
mockGrpcClient.Setup(x => x.GetProductBiddingCategoryConstant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ProductBiddingCategoryConstantServiceClient client = new ProductBiddingCategoryConstantServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ProductBiddingCategoryConstant response = client.GetProductBiddingCategoryConstant(request.ResourceNameAsProductBiddingCategoryConstantName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetProductBiddingCategoryConstantResourceNamesAsync()
{
moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient> mockGrpcClient = new moq::Mock<ProductBiddingCategoryConstantService.ProductBiddingCategoryConstantServiceClient>(moq::MockBehavior.Strict);
GetProductBiddingCategoryConstantRequest request = new GetProductBiddingCategoryConstantRequest
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
};
gagvr::ProductBiddingCategoryConstant expectedResponse = new gagvr::ProductBiddingCategoryConstant
{
ResourceNameAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
Level = gagve::ProductBiddingCategoryLevelEnum.Types.ProductBiddingCategoryLevel.Unknown,
Status = gagve::ProductBiddingCategoryStatusEnum.Types.ProductBiddingCategoryStatus.Active,
Id = -6774108720365892680L,
CountryCode = "country_code8debec55",
ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName = gagvr::ProductBiddingCategoryConstantName.FromCountryCodeLevelId("[COUNTRY_CODE]", "[LEVEL]", "[ID]"),
LanguageCode = "language_code2f6c7160",
LocalizedName = "localized_namefc402dfa",
};
mockGrpcClient.Setup(x => x.GetProductBiddingCategoryConstantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ProductBiddingCategoryConstant>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ProductBiddingCategoryConstantServiceClient client = new ProductBiddingCategoryConstantServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ProductBiddingCategoryConstant responseCallSettings = await client.GetProductBiddingCategoryConstantAsync(request.ResourceNameAsProductBiddingCategoryConstantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::ProductBiddingCategoryConstant responseCancellationToken = await client.GetProductBiddingCategoryConstantAsync(request.ResourceNameAsProductBiddingCategoryConstantName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
|
googleads/google-ads-dotnet
|
tests/V9/Services/ProductBiddingCategoryConstantServiceClientTest.g.cs
|
C#
|
apache-2.0
| 15,471
|
var interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry =
[
[ "setBytes", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#abcee4c5061efc787a287d076123efd1d", null ],
[ "setLastSeen", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#acb36228a788838ba7138144b79c4aa68", null ],
[ "setLife", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#a420b51bf06d87a3aca3a78a7256176e9", null ],
[ "setPackets", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#aec00b06ee9dc6adf1ce4f841e11713b4", null ],
[ "setState", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#aa3ec6f5b30996739a2541dceb76c6f75", null ]
];
|
onosfw/apis
|
onos/apis/interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.js
|
JavaScript
|
apache-2.0
| 725
|
[org.apache.struts.tiles](../../../../org/apache/struts/tiles/package-summary.html.md)
|---------------------------------------------------------------------------------------|
| Classes
[CustomI18nFactorySet](CustomI18nFactorySet.html.md "class in org.apache.struts.tiles")
[TestTilesPlugin](TestTilesPlugin.html.md "class in org.apache.struts.tiles") |
|
ExclamationLabs/struts-1.3.10_docs
|
struts-tiles/testapidocs/org/apache/struts/tiles/package-frame.html.md
|
Markdown
|
apache-2.0
| 454
|
#!/bin/bash
# $1 -> Job workspace
WORKSPACE=$1
# Disable IPv6 in the test machines
var=' # Disable IPv6\n - lineinfile: dest=/etc/sysctl.conf regexp="{{ item }}" line="{{ item }} = 1"\n with_items:\n - 'net.ipv6.conf.all.disable_ipv6'\n - 'net.ipv6.conf.default.disable_ipv6'\n - 'net.ipv6.conf.lo.disable_ipv6'\n ignore_errors: yes\n - shell: sysctl -p\n ignore_errors: yes\n'
sed -i "/tasks/a $var" $WORKSPACE/contextualization/conf-ansible.yml
|
grycap/jenkins
|
config-scripts/im/disable-ipv6-ansible.sh
|
Shell
|
apache-2.0
| 491
|
# Polytaenium chlorosporum (Mickel & Beitel) E.H.Crane SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Vittariaceae/Polytaenium/Polytaenium chlorosporum/README.md
|
Markdown
|
apache-2.0
| 202
|
<?php
/**
* Created by JetBrains PhpStorm.
* User: occul_000
* Date: 04/03/13
* Time: 00:18
* To change this template use File | Settings | File Templates.
*/
require_once('../controller/PDOUserManager.php');
session_start();
$PDOUserManager = new PDOUserManager();
$PDOUserManager->deleteUser($_SESSION['email']);
|
GuillaumeOcculy/anfshift_paris
|
view/delete_account.php
|
PHP
|
apache-2.0
| 337
|
cosu-vim
========
my own vim config as a vundle plugin
|
cosu/cosu-vim
|
Readme.md
|
Markdown
|
apache-2.0
| 55
|
package org.n52.v3d.worldviz.projections.dymaxion;
/**
* Implementation helper class
*
* @author Benno Schmidt
*
*/
public class InfoObj {
public int tri;
public int hlcd;
}
|
nuest/worldviz
|
src/main/java/org/n52/v3d/worldviz/projections/dymaxion/InfoObj.java
|
Java
|
apache-2.0
| 183
|
<?php $this->load->view('admin/_header'); ?>
<header class="Hui-header cl"> <a class="Hui-logo l" title="H-ui.admin v2.3" href="/">AWZ-admin</a> <a class="Hui-logo-m l" href="/" title="H-ui.admin">H-ui</a> <span class="Hui-subtitle l">V1.0</span>
<nav class="mainnav cl" id="Hui-nav">
<ul>
<li class="dropDown dropDown_click"><a href="javascript:;" aria-expanded="true" aria-haspopup="true" data-toggle="dropdown" class="dropDown_A"><i class="Hui-iconfont"></i> 新增 <i class="Hui-iconfont"></i></a>
<ul class="dropDown-menu radius box-shadow">
<li><a href="javascript:;" onclick="article_add('添加资讯','article-add.html')"><i class="Hui-iconfont"></i> 资讯</a></li>
<li><a href="javascript:;" onclick="picture_add('添加资讯','picture-add.html')"><i class="Hui-iconfont"></i> 图片</a></li>
<li><a href="javascript:;" onclick="product_add('添加资讯','product-add.html')"><i class="Hui-iconfont"></i> 产品</a></li>
<li><a href="javascript:;" onclick="member_add('添加用户','member-add.html','','510')"><i class="Hui-iconfont"></i> 用户</a></li>
</ul>
</li>
</ul>
</nav>
<ul class="Hui-userbar">
<li>超级管理员</li>
<li class="dropDown dropDown_hover"><a href="#" class="dropDown_A">admin <i class="Hui-iconfont"></i></a>
<ul class="dropDown-menu radius box-shadow">
<li><a href="#">个人信息</a></li>
<li><a href="#">切换账户</a></li>
<li><a href="#">退出</a></li>
</ul>
</li>
<li id="Hui-msg"> <a href="#" title="消息"><span class="badge badge-danger">1</span><i class="Hui-iconfont" style="font-size:18px"></i></a> </li>
<li id="Hui-skin" class="dropDown right dropDown_hover"><a href="javascript:;" title="换肤"><i class="Hui-iconfont" style="font-size:18px"></i></a>
<ul class="dropDown-menu radius box-shadow">
<li><a href="javascript:;" data-val="default" title="默认(黑色)">默认(黑色)</a></li>
<li><a href="javascript:;" data-val="blue" title="蓝色">蓝色</a></li>
<li><a href="javascript:;" data-val="green" title="绿色">绿色</a></li>
<li><a href="javascript:;" data-val="red" title="红色">红色</a></li>
<li><a href="javascript:;" data-val="yellow" title="黄色">黄色</a></li>
<li><a href="javascript:;" data-val="orange" title="绿色">橙色</a></li>
</ul>
</li>
</ul>
<a href="javascript:;" class="Hui-nav-toggle Hui-iconfont" aria-hidden="false"></a> </header>
<aside class="Hui-aside">
<input runat="server" id="divScrollValue" type="hidden" value="" />
<div class="menu_dropdown bk_2">
<dl id="menu-article">
<dt><i class="Hui-iconfont"></i> 资讯管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="article-list.html" data-title="资讯管理" href="javascript:void(0)">资讯管理</a></li>
</ul>
</dd>
</dl>
<dl id="menu-picture">
<dt><i class="Hui-iconfont"></i> 图片管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="picture-list.html" data-title="图片管理" href="javascript:void(0)">图片管理</a></li>
</ul>
</dd>
</dl>
<dl id="menu-product">
<dt><i class="Hui-iconfont"></i> 产品管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="product-brand.html" data-title="品牌管理" href="javascript:void(0)">品牌管理</a></li>
<li><a _href="product-category.html" data-title="分类管理" href="javascript:void(0)">分类管理</a></li>
<li><a _href="product-list.html" data-title="产品管理" href="javascript:void(0)">产品管理</a></li>
</ul>
</dd>
</dl>
<!--<dl id="menu-page">
<dt><i class="Hui-iconfont"></i> 页面管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="page-home.html" href="javascript:void(0)">首页管理</a></li>
<li><a _href="page-flinks.html" href="javascript:void(0)">友情链接</a></li>
</ul>
</dd>
</dl>-->
<dl id="menu-comments">
<dt><i class="Hui-iconfont"></i> 评论管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="http://h-ui.duoshuo.com/admin/" data-title="评论列表" href="javascript:;">评论列表</a></li>
<li><a _href="feedback-list.html" data-title="意见反馈" href="javascript:void(0)">意见反馈</a></li>
</ul>
</dd>
</dl>
<!--<dl id="menu-order">
<dt><i class="Hui-iconfont"></i> 财务管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="order-list.html" href="javascript:void(0)">订单列表</a></li>
<li><a _href="recharge-list.html" href="javascript:void(0)">充值管理</a></li>
<li><a _href="invoice-list.html" href="javascript:void(0)">发票管理</a></li>
</ul>
</dd>
</dl>-->
<dl id="menu-member">
<dt><i class="Hui-iconfont"></i> 会员管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="/admin/member/member_list.html" data-title="会员列表" href="javascript:;">会员列表</a></li>
<li><a _href="/admin/member/member_stop.html" data-title="停用的会员" href="javascript:;">停用会员</a></li>
<li><a _href="/admin/member/member_level.html" data-title="等级管理" href="javascript:;">等级管理</a></li>
<li><a _href="/admin/member/member_integral.html" data-title="积分管理" href="javascript:;">积分管理</a></li>
<li><a _href="/admin/member/member_browse.html" data-title="浏览记录" href="javascript:void(0)">浏览记录</a></li>
<li><a _href="/admin/member/member_download.html" data-title="下载记录" href="javascript:void(0)">下载记录</a></li>
<li><a _href="/admin/member/member_share.html" data-title="分享记录" href="javascript:void(0)">分享记录</a></li>
</ul>
</dd>
</dl>
<dl id="menu-admin">
<dt><i class="Hui-iconfont"></i> 管理员管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="/admin/index/admin_role.html" data-title="角色管理" href="javascript:void(0)">角色管理</a></li>
<li><a _href="/admin/index/permission.html" data-title="权限管理" href="javascript:void(0)">权限管理</a></li>
<li><a _href="/admin/index/admin-list.html" data-title="管理员列表" href="javascript:void(0)">管理员列表</a></li>
</ul>
</dd>
</dl>
<dl id="menu-tongji">
<dt><i class="Hui-iconfont"></i> 系统统计<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="charts-1.html" data-title="折线图" href="javascript:void(0)">折线图</a></li>
<li><a _href="charts-2.html" data-title="时间轴折线图" href="javascript:void(0)">时间轴折线图</a></li>
<li><a _href="charts-3.html" data-title="区域图" href="javascript:void(0)">区域图</a></li>
<li><a _href="charts-4.html" data-title="柱状图" href="javascript:void(0)">柱状图</a></li>
<li><a _href="charts-5.html" data-title="饼状图" href="javascript:void(0)">饼状图</a></li>
<li><a _href="charts-6.html" data-title="3D柱状图" href="javascript:void(0)">3D柱状图</a></li>
<li><a _href="charts-7.html" data-title="3D饼状图" href="javascript:void(0)">3D饼状图</a></li>
</ul>
</dd>
</dl>
<dl id="menu-system">
<dt><i class="Hui-iconfont"></i> 系统管理<i class="Hui-iconfont menu_dropdown-arrow"></i></dt>
<dd>
<ul>
<li><a _href="system-base.html" data-title="系统设置" href="javascript:void(0)">系统设置</a></li>
<li><a _href="system-category.html" data-title="栏目管理" href="javascript:void(0)">栏目管理</a></li>
<li><a _href="system-data.html" data-title="数据字典" href="javascript:void(0)">数据字典</a></li>
<li><a _href="system-shielding.html" data-title="屏蔽词" href="javascript:void(0)">屏蔽词</a></li>
<li><a _href="system-log.html" data-title="系统日志" href="javascript:void(0)">系统日志</a></li>
</ul>
</dd>
</dl>
</div>
</aside>
<div class="dislpayArrow"><a class="pngfix" href="javascript:void(0);" onClick="displaynavbar(this)"></a></div>
<section class="Hui-article-box">
<div id="Hui-tabNav" class="Hui-tabNav">
<div class="Hui-tabNav-wp">
<ul id="min_title_list" class="acrossTab cl">
<li class="active"><span title="我的桌面" data-href="welcome.php">我的桌面</span><em></em></li>
</ul>
</div>
<div class="Hui-tabNav-more btn-group"><a id="js-tabNav-prev" class="btn radius btn-default size-S" href="javascript:;"><i class="Hui-iconfont"></i></a><a id="js-tabNav-next" class="btn radius btn-default size-S" href="javascript:;"><i class="Hui-iconfont"></i></a></div>
</div>
<div id="iframe_box" class="Hui-article">
<div class="show_iframe">
<div style="display:none" class="loading"></div>
<iframe scrolling="yes" frameborder="0" src="welcome.html"></iframe>
</div>
</div>
</section>
<script type="text/javascript" src="/public/lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="/public/lib/layer/2.1/layer.js"></script>
<script type="text/javascript" src="/public/js/H-ui.js"></script>
<script type="text/javascript" src="/public/js/H-ui.admin.js"></script>
<script type="text/javascript">
/*资讯-添加*/
function article_add(title,url){
var index = layer.open({
type: 2,
title: title,
content: url
});
layer.full(index);
}
/*图片-添加*/
function picture_add(title,url){
var index = layer.open({
type: 2,
title: title,
content: url
});
layer.full(index);
}
/*产品-添加*/
function product_add(title,url){
var index = layer.open({
type: 2,
title: title,
content: url
});
layer.full(index);
}
/*用户-添加*/
function member_add(title,url,w,h){
layer_show(title,url,w,h);
}
</script>
</body>
</html>
|
yuncopy/AWZ
|
application/views/admin/index.php
|
PHP
|
apache-2.0
| 10,111
|
/**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.dyno.jedis;
import com.netflix.dyno.connectionpool.*;
import com.netflix.dyno.connectionpool.exception.DynoException;
import com.netflix.dyno.connectionpool.impl.ConnectionContextImpl;
import com.netflix.dyno.connectionpool.impl.OperationResultImpl;
import com.netflix.dyno.connectionpool.impl.utils.ZipUtils;
import com.netflix.dyno.connectionpool.TokenRackMapper;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import redis.clients.jedis.Jedis;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when;
public class UnitTestConnectionPoolForCompression implements ConnectionPool<Jedis> {
Map<String, String> redis_data;
@Mock
Jedis client;
@Mock
Connection<Jedis> connection;
private final ConnectionPoolConfiguration config;
private final ConnectionContextImpl context = new ConnectionContextImpl();
private final OperationMonitor opMonitor;
public UnitTestConnectionPoolForCompression(ConnectionPoolConfiguration config, OperationMonitor opMonitor) {
MockitoAnnotations.initMocks(this);
this.config = config;
this.opMonitor = opMonitor;
this.redis_data = new HashMap<String, String>();
when(client.set(anyString(), anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
String key = (String)invocation.getArguments()[0];
String value = (String)invocation.getArguments()[1];
redis_data.put(key, value);
return value;
}
});
when(client.get(CompressionTest.VALUE_1KB)).thenReturn(CompressionTest.VALUE_1KB);
when(client.get(CompressionTest.KEY_3KB)).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return ZipUtils.compressStringToBase64String(CompressionTest.VALUE_3KB);
}
});
when(client.get(CompressionTest.KEY_1KB)).thenReturn(CompressionTest.VALUE_1KB);
when(client.hmset(anyString(), anyMap())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Map<String, String> map = (Map<String, String>) invocation.getArguments()[1];
if (map != null) {
if (map.containsKey(CompressionTest.KEY_3KB)) {
if (ZipUtils.isCompressed(map.get(CompressionTest.KEY_3KB))) {
return "OK";
} else {
throw new RuntimeException("Value was not compressed");
}
}
} else {
throw new RuntimeException("Map is NULL");
}
return "OK";
}
});
when(client.mget(Matchers.<String>anyVararg())).thenAnswer (new Answer<List<String>>() {
@Override
public List<String> answer(InvocationOnMock invocation) throws Throwable {
// Get the keys passed
Object[] keys = invocation.getArguments();
List<String> values = new ArrayList<String>(10);
for (int i = 0; i < keys.length; i++) {
// get the ith key, find the value in redis_data
// if found, return that else return nil
String key = (String)keys[i];
String value = redis_data.get(key);
values.add(i, value);
}
return values;
}
});
}
@Override
public boolean addHost(Host host) {
return true;
}
@Override
public boolean removeHost(Host host) {
return true;
}
@Override
public boolean isHostUp(Host host) {
return false;
}
@Override
public boolean hasHost(Host host) {
return false;
}
@Override
public List<HostConnectionPool<Jedis>> getActivePools() {
return null;
}
@Override
public List<HostConnectionPool<Jedis>> getPools() {
return null;
}
@Override
public HostConnectionPool<Jedis> getHostPool(Host host) {
return null;
}
@Override
public <R> Collection<OperationResult<R>> executeWithRing(TokenRackMapper tokenRackMapper, Operation<Jedis, R> op) throws DynoException {
return null;
}
@Override
public <R> ListenableFuture<OperationResult<R>> executeAsync(AsyncOperation<Jedis, R> op) throws DynoException {
return null;
}
@Override
public <R> OperationResult<R> executeWithFailover(Operation<Jedis, R> op) throws DynoException {
try {
R r = op.execute(client, context);
if (context.hasMetadata("compression") || context.hasMetadata("decompression")) {
opMonitor.recordSuccess(op.getName(), true);
} else {
opMonitor.recordSuccess(op.getName());
}
return new OperationResultImpl<R>("Test", r, null);
} finally {
context.reset();
}
}
@Override
public void shutdown() {
}
@Override
public Future<Boolean> start() throws DynoException {
return new Future<Boolean>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public Boolean get() throws InterruptedException, ExecutionException {
return true;
}
@Override
public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return true;
}
};
}
@Override
public void idle() {
}
@Override
public ConnectionPoolConfiguration getConfiguration() {
return config;
}
@Override
public HealthTracker<Jedis> getHealthTracker() {
return null;
}
@Override
public boolean isIdle() {
return false;
}
@Override
public Future<Boolean> updateHosts(Collection activeHosts, Collection inactiveHosts) {
return null;
}
}
|
balajivenki/dyno
|
dyno-jedis/src/test/java/com/netflix/dyno/jedis/UnitTestConnectionPoolForCompression.java
|
Java
|
apache-2.0
| 7,523
|
# Puccinia leontodontis var. leontodontis VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Composit. Puccin. 75 (1899)
#### Original name
Puccinia leontodontis var. leontodontis
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Puccinia/Puccinia punctiformis/Puccinia hieracii hieracii/Puccinia leontodontis leontodontis/README.md
|
Markdown
|
apache-2.0
| 230
|
// test for comments in templates
test('comments', 8, function() {
var template = '{!this won\'t show up!}';
equal(whiskers.render(template, {}), '')
var template = '{!!}';
equal(whiskers.render(template, {}), '')
var template = '{!this won\'t show up\neither!}';
equal(whiskers.render(template, {}), '')
var template = '{!this won\'t {show} up!}';
equal(whiskers.render(template, {}), '')
var template = '\\{!this will show up!}';
equal(whiskers.render(template, {}), '{!this will show up!}')
var template = '{!this will also show up}';
equal(whiskers.render(template, {}), '{!this will also show up}')
var template = '{!this won\'t, but!}this part will show up!}';
equal(whiskers.render(template, {}), 'this part will show up!}')
var template = '{also, {!this} part won\'t show up!}';
equal(whiskers.render(template, {}), '{also, ')
});
|
brad-langshaw/project2
|
node_modules/whiskers/test/browser/test-comments.js
|
JavaScript
|
apache-2.0
| 879
|
#
# 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.
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
class QoSPolicy(neutron.NeutronResource):
"""A resource for Neutron QoS Policy.
This QoS policy can be associated with neutron resources,
such as port and network, to provide QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
NAME, DESCRIPTION, SHARED, TENANT_ID,
) = (
'name', 'description', 'shared', 'tenant_id',
)
ATTRIBUTES = (
RULES_ATTR,
) = (
'rules',
)
properties_schema = {
NAME: properties.Schema(
properties.Schema.STRING,
_('The name for the QoS policy.'),
required=True,
update_allowed=True
),
DESCRIPTION: properties.Schema(
properties.Schema.STRING,
_('The description for the QoS policy.'),
update_allowed=True
),
SHARED: properties.Schema(
properties.Schema.BOOLEAN,
_('Whether this QoS policy should be shared to other tenants.'),
default=False,
update_allowed=True
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this QoS policy.')
),
}
attributes_schema = {
RULES_ATTR: attributes.Schema(
_("A list of all rules for the QoS policy."),
type=attributes.Schema.LIST
)
}
def handle_create(self):
props = self.prepare_properties(
self.properties,
self.physical_resource_name())
policy = self.client().create_qos_policy({'policy': props})['policy']
self.resource_id_set(policy['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_qos_policy(self.resource_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.prepare_update_properties(prop_diff)
self.client().update_qos_policy(
self.resource_id,
{'policy': prop_diff})
def _show_resource(self):
return self.client().show_qos_policy(
self.resource_id)['policy']
class QoSRule(neutron.NeutronResource):
"""A resource for Neutron QoS base rule."""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
POLICY, TENANT_ID,
) = (
'policy', 'tenant_id',
)
properties_schema = {
POLICY: properties.Schema(
properties.Schema.STRING,
_('ID or name of the QoS policy.'),
required=True,
constraints=[constraints.CustomConstraint('neutron.qos_policy')]
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this rule.')
),
}
def __init__(self, name, json_snippet, stack):
super(QoSRule, self).__init__(name, json_snippet, stack)
self._policy_id = None
@property
def policy_id(self):
if not self._policy_id:
self._policy_id = self.client_plugin().get_qos_policy_id(
self.properties[self.POLICY])
return self._policy_id
class QoSBandwidthLimitRule(QoSRule):
"""A resource for Neutron QoS bandwidth limit rule.
This rule can be associated with QoS policy, and then the policy
can be used by neutron port and network, to provide bandwidth limit
QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
PROPERTIES = (
MAX_BANDWIDTH, MAX_BURST_BANDWIDTH,
) = (
'max_kbps', 'max_burst_kbps',
)
properties_schema = {
MAX_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max bandwidth in kbps.'),
required=True,
update_allowed=True,
constraints=[
constraints.Range(min=0)
]
),
MAX_BURST_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max burst bandwidth in kbps.'),
update_allowed=True,
constraints=[
constraints.Range(min=0)
],
default=0
)
}
properties_schema.update(QoSRule.properties_schema)
def handle_create(self):
props = self.prepare_properties(self.properties,
self.physical_resource_name())
props.pop(self.POLICY)
rule = self.client().create_bandwidth_limit_rule(
self.policy_id,
{'bandwidth_limit_rule': props})['bandwidth_limit_rule']
self.resource_id_set(rule['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_bandwidth_limit_rule(
self.resource_id, self.policy_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.client().update_bandwidth_limit_rule(
self.resource_id,
self.policy_id,
{'bandwidth_limit_rule': prop_diff})
def _show_resource(self):
return self.client().show_bandwidth_limit_rule(
self.resource_id, self.policy_id)['bandwidth_limit_rule']
def resource_mapping():
return {
'OS::Neutron::QoSPolicy': QoSPolicy,
'OS::Neutron::QoSBandwidthLimitRule': QoSBandwidthLimitRule
}
|
dims/heat
|
heat/engine/resources/openstack/neutron/qos.py
|
Python
|
apache-2.0
| 6,587
|
//
// KeyboardBar.h
// IB Checker
//
// Created by Thanh on 5/18/15.
// Copyright (c) 2015 Puganda_Mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface KeyboardBar : UIView
@property (strong, nonatomic) UITextView *textView;
@end
|
Thanhktm/IBChecker
|
Transaction/KeyboardBar.h
|
C
|
apache-2.0
| 250
|
package gov.nasa.jpl.labcas.data_access_api.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Response;
/**
* Service used to create list of files to be downloaded.
*
* @author Luca Cinquini
*
*/
public interface ListService {
/**
* Method to list all files belonging to collections that match some query criteria.
*
* @param httpRequest
* @param q
* @param fq
* @param start
* @param rows
* @param sort
* @return
*/
public Response listCollections(HttpServletRequest httpRequest, ContainerRequestContext requestContext, String q, List<String> fq, int start, int rows);
/**
* Method to list all files belonging to datasets that match some query criteria.
*
* @param httpRequest
* @param q
* @param fq
* @param start
* @param rows
* @param sort
* @return
*/
public Response listDatasets(HttpServletRequest httpRequest, ContainerRequestContext requestContext, String q, List<String> fq, int start, int rows);
/**
* Method to list all files matching some query criteria.
*
* @param httpRequest
* @param q
* @param fq
* @param start
* @param rows
* @param sort
* @return
*/
public Response listFiles(HttpServletRequest httpRequest, ContainerRequestContext requestContext, String q, List<String> fq, int start, int rows);
}
|
EDRN/labcas-backend
|
data-access-api/src/gov/nasa/jpl/labcas/data_access_api/service/ListService.java
|
Java
|
apache-2.0
| 1,410
|
---
author: lixing123
comments: true
date: 2013-04-05 17:20:24+00:00
layout: post
link: http://127.0.0.1/lixing123.com/?p=56
slug: '%e5%8f%b0%e7%90%83%ef%bc%8c%e6%9c%80%e5%b8%85%e7%9a%84%e8%bf%90%e5%8a%a8'
title: 台球,最帅的运动
wordpress_id: 56
---
每次到台球室,总会感觉,里面的每个人,动作都很优雅,男的帅,女的靓;无论是认真地瞄杆,还是寻找容易进的球;无论是在旁边围观,还是坐在椅子上休息,那一举一动,都因这运动,而笼上一层迷人的色彩。
<!-- more -->
记得最早打桌球,已经是高一或者高二了。那时候,每周日中午2小时的放风时间,是我们最high的时候。那时候,我开始跑网吧,申请了自己的QQ号,也开始逛桌球。第一次,是在超的带领下进入我一直认为“只有坏孩子才进”的桌球室。第一次的感觉并不太好,因为他一直在认真地跟别人打球,不太理会我的疑问。
即使如此,我仍然深深地被这项优雅的运动迷住了。我开始找时间跟同学出去打桌球,苦练自己的技术,幻想着有一天能够在桌球室里叱咤风云。可惜的是,我的水平虽然在一点一点提高着,但始终没有达到我认为的NB水平。直到大学。
上了大学之后,很幸运,我们宿舍几个哥们都喜欢玩桌球,而且大家的水平也都差不多。于是在大一、大二的时候,经常去玩。也许是我的天分稍微好一点,也许是量变终于引发了质变,我的技术在很短的时间里,大概一两个月吧,突然提高地非常快,以至于最后有一次,在我的央求下,舍友跟我出去玩,居然被我连虐了10局。。。
自此之后很长时间,都不怎么玩了,因为在熟悉的朋友里,找不到对手。
最近,大四的下学期,又开始玩桌球了。第一次,由于好长时间没玩了,水平特别菜,也舍友也就半斤八两。第二次,也就是今天晚上这一次,又找到了之前的感觉,总共4个人,总共打了10局,又是10局全胜。很高兴,找回了自信,对付一般的高手,至少也不会输掉裤子了吧。而且如果以后有机会教MM玩,也有了底气!哈!
就写到这里吧。一般不喜欢在电脑上打字,不如手写舒服。这篇文章还会抄到日记本里。
|
lixing123/lixing123.github.io
|
_posts/2013-04-05-e58fb0e79083efbc8ce69c80e5b885e79a84e8bf90e58aa8.markdown
|
Markdown
|
apache-2.0
| 2,377
|
// Copyright 2013 Serilog Contributors
//
// 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Sinks.PeriodicBatching;
namespace Serilog.Sinks.CouchDB
{
/// <summary>
/// Writes log events as documents to a CouchDB database.
/// </summary>
public class CouchDBSink : PeriodicBatchingSink
{
readonly IFormatProvider _formatProvider;
readonly HttpClient _httpClient;
const string BulkUploadResource = "_bulk_docs";
/// <summary>
/// A reasonable default for the number of events posted in
/// each batch.
/// </summary>
public const int DefaultBatchPostingLimit = 50;
/// <summary>
/// A reasonable default time to wait between checking for event batches.
/// </summary>
public static readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(2);
/// <summary>
/// Construct a sink posting to the specified database.
/// </summary>
/// <param name="databaseUrl">The URL of a CouchDB database.</param>
/// <param name="batchPostingLimit">The maximium number of events to post in a single batch.</param>
/// <param name="period">The time to wait between checking for event batches.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
public CouchDBSink(string databaseUrl, int batchPostingLimit, TimeSpan period, IFormatProvider formatProvider)
: base(batchPostingLimit, period)
{
if (databaseUrl == null) throw new ArgumentNullException("databaseUrl");
var baseAddress = databaseUrl;
if (!databaseUrl.EndsWith("/"))
baseAddress += "/";
_formatProvider = formatProvider;
_httpClient = new HttpClient { BaseAddress = new Uri(baseAddress) };
}
/// <summary>
/// Free resources held by the sink.
/// </summary>
/// <param name="disposing">If true, called because the object is being disposed; if false,
/// the object is being disposed from the finalizer.</param>
protected override void Dispose(bool disposing)
{
// First flush the buffer
base.Dispose(disposing);
if (disposing)
_httpClient.Dispose();
}
/// <summary>
/// Emit a batch of log events, running asynchronously.
/// </summary>
/// <param name="events">The events to emit.</param>
/// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>,
/// not both.</remarks>
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
var payload = new StringWriter();
payload.Write("{\"docs\":[");
var formatter = new JsonFormatter(true);
var delimStart = "{";
foreach (var logEvent in events)
{
payload.Write(delimStart);
formatter.Format(logEvent, payload);
var renderedMessage = logEvent.RenderMessage(_formatProvider);
payload.Write(",\"UtcTimestamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}",
logEvent.Timestamp.ToUniversalTime().DateTime,
JsonFormatter.Escape(renderedMessage));
delimStart = ",{";
}
payload.Write("]}");
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
var result = await _httpClient.PostAsync(BulkUploadResource, content);
if (!result.IsSuccessStatusCode)
SelfLog.WriteLine("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result);
}
}
}
|
paulcbetts/serilog
|
src/Serilog.Sinks.CouchDB/Sinks/CouchDB/CouchDBSink.cs
|
C#
|
apache-2.0
| 4,618
|
/* Copyright 2004-2005 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 org.codehaus.groovy.grails.web.taglib;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException;
import grails.util.GrailsUtil;
/**
* Allows defining of variables within the page context
*
* @author Graeme Rocher
* @since 23-Feb-2006
*/
public class GroovyDefTag extends GroovySyntaxTag {
public static final String TAG_NAME = "def";
private static final String ATTRIBUTE_VALUE = "value";
public void doStartTag() {
String expr = (String) attributes.get(ATTRIBUTE_VALUE);
String var = (String) attributes.get(ATTRIBUTE_VAR);
if(StringUtils.isBlank(var))
throw new GrailsTagException("Tag ["+TAG_NAME+"] missing required attribute ["+ATTRIBUTE_VAR+"]");
if(StringUtils.isBlank(expr))
throw new GrailsTagException("Tag ["+TAG_NAME+"] missing required attribute ["+ATTRIBUTE_VALUE +"]");
GrailsUtil.deprecated("The tag <g:def> is deprecated and will be removed in a future release. Use <g:set> instead.");
out.print("def ");
out.print(var.substring(1,var.length() -1));
out.print('=');
out.println(expr);
}
public void doEndTag() {
// do nothing
}
public String getName() {
return TAG_NAME;
}
public boolean isBufferWhiteSpace() {
return false;
}
public boolean hasPrecedingContent() {
return true;
}
}
|
lpicanco/grails
|
src/web/org/codehaus/groovy/grails/web/taglib/GroovyDefTag.java
|
Java
|
apache-2.0
| 2,080
|
# C examples
This directory contains example benchmarks written in C.
|
delcypher/svcomp-build-mockup
|
benchmarks/c/examples/README.md
|
Markdown
|
apache-2.0
| 71
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using Weiz.TaskManager.Models;
using Weiz.TaskManager.Common;
using Weiz.TaskManager.DBUtility;
namespace Weiz.TaskManager.DAL
{
public class TaskDAL
{
/// <summary>
/// 获取任务列表
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public PageOf<TaskModel> GetTaskList(int pageIndex, int pageSize)
{
var QUERY_SQL = @"( SELECT TaskID,TaskName,TaskParam,CronExpressionString,AssemblyName,ClassName,Status,IsDelete,CreatedTime,ModifyTime,RecentRunTime,NextFireTime,CronRemark,Remark
FROM p_Task(nolock)
WHERE IsDelete=0 ";
QUERY_SQL += ") pp ";
string SQL = string.Format(@" select * from (select ROW_NUMBER() OVER(order by pp.ModifyTime desc) AS RowNum,* from {0}
) as A where A.RowNum BETWEEN (@PageIndex-1)* @PageSize+1 AND @PageIndex*@PageSize ORDER BY RowNum;",
QUERY_SQL);
SQL += string.Format(@" SELECT COUNT(1) FROM {0};", QUERY_SQL);
object param = new { pageIndex = pageIndex, pageSize = pageSize };
DataSet ds = SQLHelper.FillDataSet(SQL, param);
return new PageOf<TaskModel>()
{
PageIndex = pageIndex,
PageSize = pageSize,
Total = Convert.ToInt32(ds.Tables[1].Rows[0][0]),
Items = DataMapHelper.DataSetToList<TaskModel>(ds)
};
}
/// <summary>
/// 读取数据库中全部的任务
/// </summary>
/// <returns></returns>
public List<TaskModel> GetAllTaskList()
{
var sql = @"SELECT TaskID,TaskName,TaskParam,CronExpressionString,AssemblyName,ClassName,Status,IsDelete,CreatedTime,ModifyTime,RecentRunTime,NextFireTime,CronRemark,Remark
FROM p_Task(nolock)
WHERE IsDelete=0 and Status =1";
var result = SQLHelper.ToList<TaskModel>(sql);
return result;
}
/// <summary>
/// 删除任务
/// </summary>
/// <param name="taskId"></param>
/// <returns></returns>
public bool UpdateTaskStatus(string taskId, int status)
{
var sql = @" UPDATE p_Task
SET Status = @Status
WHERE TaskID=@TaskID
";
object param = new { TaskID = taskId, Status = status };
return SQLHelper.ExecuteNonQuery(sql, param) > 0;
}
/// <summary>
/// 修改任务的下次启动时间
/// </summary>
/// <param name="taskId"></param>
/// <param name="nextFireTime"></param>
/// <returns></returns>
public bool UpdateNextFireTime(string taskId, DateTime nextFireTime)
{
var sql = @" UPDATE p_Task
SET NextFireTime = @NextFireTime
,ModifyTime = GETDATE()
WHERE TaskID=@TaskID
";
object param = new { TaskID = taskId, NextFireTime = nextFireTime };
return SQLHelper.ExecuteNonQuery(sql, param) > 0;
}
/// <summary>
/// 根据任务Id 修改 上次运行时间
/// </summary>
/// <param name="taskId"></param>
/// <param name="recentRunTime"></param>
/// <returns></returns>
public bool UpdateRecentRunTime(string taskId, DateTime recentRunTime)
{
var sql = @" UPDATE p_Task
SET RecentRunTime = @RecentRunTime
,ModifyTime = GETDATE()
WHERE TaskID=@TaskID
";
object param = new { TaskID = taskId, RecentRunTime = recentRunTime };
return SQLHelper.ExecuteNonQuery(sql, param) > 0;
}
/// <summary>
/// 根据任务Id 获取任务
/// </summary>
/// <param name="taskId"></param>
/// <returns></returns>
public TaskModel GetTaskById(string taskId)
{
var sql = @"SELECT TaskID,TaskName,TaskParam,CronExpressionString,AssemblyName,ClassName,Status,IsDelete,CreatedTime,ModifyTime,RecentRunTime,NextFireTime,CronRemark,Remark
FROM p_Task(nolock)
WHERE TaskID=@TaskID";
object param = new { TaskID = taskId };
var result = SQLHelper.Single<TaskModel>(sql, param);
return result;
}
/// <summary>
/// 添加任务
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
public bool Add(TaskModel task)
{
var sql = @" INSERT INTO p_Task
(TaskID,TaskName,TaskParam,CronExpressionString,AssemblyName,ClassName,Status,IsDelete,CreatedTime,ModifyTime,CronRemark,Remark)
VALUES
(@TaskID ,@TaskName,@TaskParam,@CronExpressionString,@AssemblyName,@ClassName,@Status,0,getdate(),getdate(),@CronRemark,@Remark)";
object param = new
{
TaskID = task.TaskID,
TaskName = task.TaskName,
TaskParam = task.TaskParam,
CronExpressionString = task.CronExpressionString,
AssemblyName = task.AssemblyName,
ClassName = task.ClassName,
Status = task.Status,
CronRemark = task.CronRemark,
Remark = task.Remark
};
return SQLHelper.ExecuteNonQuery(sql, param) > 0;
}
/// <summary>
/// 修改任务
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
public bool Edit(TaskModel task)
{
var sql = @" UPDATE p_Task
SET TaskName = @TaskName,TaskParam = @TaskParam,CronExpressionString = @CronExpressionString,AssemblyName = @AssemblyName,ClassName = @ClassName,
Status = @Status,IsDelete = 0,ModifyTime =getdate() ,CronRemark = @CronRemark,Remark = @Remark
WHERE TaskID = @TaskID";
object param = new
{
TaskID = task.TaskID,
TaskName = task.TaskName,
TaskParam = task.TaskParam,
CronExpressionString = task.CronExpressionString,
AssemblyName = task.AssemblyName,
ClassName = task.ClassName,
Status = task.Status,
CronRemark = task.CronRemark,
Remark = task.Remark
};
return SQLHelper.ExecuteNonQuery(sql, param) > 0;
}
}
}
|
weizhong1988/Weiz.TaskManager
|
Weiz.TaskManager.DAL/TaskDAL.cs
|
C#
|
apache-2.0
| 7,073
|
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Alkaid;
public enum NetCtr
{
Lobby = 1,
Room,
}
public class Rosetta : Singleton<Rosetta>, Lifecycle
{
public bool Init()
{
// 文件位置
if (Application.isEditor)
{
Framework.Instance.SetWritableRootDir(Application.temporaryCachePath);
Framework.Instance.SetStreamAssetsRootDir(Application.streamingAssetsPath);
}
else
{
Framework.Instance.SetWritableRootDir(Application.temporaryCachePath);
Framework.Instance.SetStreamAssetsRootDir(Application.streamingAssetsPath);
}
// console输出
LoggerSystem.Instance.SetConsoleLogger(new Alkaid.Logger(UnityEngine.Debug.Log));
// 网络
PacketFormat pf = new PacketFormat();
PacketHandlerManager pm = new PacketHandlerManager();
NetSystem.Instance.RegisterConnector((int)NetCtr.Lobby, ConnectionType.TCP, pf, pm, ConnectedCallback, null, DisConnectedCallback, null);
// NetSystem.Instance.RegisterConnector((int)NetCtr.Room, ConnectionType.TCP, pf, pm, conne)
return Framework.Instance.Init();
}
public void Tick(float interval)
{
Framework.Instance.Tick(interval);
}
public void Destroy()
{
Framework.Instance.Destroy();
}
private void ConnectedCallback(bool status)
{
//EventSystem.Instance.FireEvent("network", "testwindow", status);
EventSystem2.Instance.FireEvent ((int)EventId.Network, status);
}
private void DisConnectedCallback()
{
//EventSystem.Instance.FireEvent("network", "testwindow", false);
EventSystem2.Instance.FireEvent ((int)EventId.Network, false);
}
public IEnumerator ConnectLobby(string ip, int port)
{
NetSystem.Instance.Connect((int)NetCtr.Lobby, ip, port);
while(!NetSystem.Instance.GetConnector((int)NetCtr.Lobby).IsConnected())
yield return 1;
}
public void DisconnectLobby()
{
NetSystem.Instance.GetConnector((int)NetCtr.Lobby).DisConnect();
}
public void Ping()
{
NetPacket pa = new NetPacket(PacketType.CS_Ping);
XMessage.CS_Ping proto = new XMessage.CS_Ping();
proto.Timestamp = DateTime.Now.ToBinary();
pa.Proto = proto;
NetSystem.Instance.Send((int)NetCtr.Lobby, pa);
}
}
|
AlkaidFang/Rosetta
|
Unity/Assets/Scripts/Rosetta/Rosetta.cs
|
C#
|
apache-2.0
| 2,442
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Sun Mar 17 11:03:39 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.management.security_realm.PlugInAuthorization (BOM: * : All 2.4.0.Final API)</title>
<meta name="date" content="2019-03-17">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.management.security_realm.PlugInAuthorization (BOM: * : All 2.4.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.4.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/PlugInAuthorization.html" target="_top">Frames</a></li>
<li><a href="PlugInAuthorization.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.management.security_realm.PlugInAuthorization" class="title">Uses of Class<br>org.wildfly.swarm.config.management.security_realm.PlugInAuthorization</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management.security_realm">org.wildfly.swarm.config.management.security_realm</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.management">org.wildfly.swarm.management</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> that return <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></code></td>
<td class="colLast"><span class="typeNameLabel">SecurityRealm.SecurityRealmResources.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.SecurityRealmResources.html#plugInAuthorization--">plugInAuthorization</a></span>()</code>
<div class="block">Configuration of a user store plug-in for use by the realm.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html" title="type parameter in SecurityRealm">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">SecurityRealm.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html#plugInAuthorization-org.wildfly.swarm.config.management.security_realm.PlugInAuthorization-">plugInAuthorization</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a> value)</code>
<div class="block">Configuration of a user store plug-in for use by the realm.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.management.security_realm">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a> with type parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a><T extends <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a><T>></span></code>
<div class="block">Configuration of a user store plug-in for use by the realm.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorizationConsumer.html" title="interface in org.wildfly.swarm.config.management.security_realm">PlugInAuthorizationConsumer</a><T extends <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorizationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">PlugInAuthorizationSupplier</a><T extends <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a> that return <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></code></td>
<td class="colLast"><span class="typeNameLabel">PlugInAuthorizationSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorizationSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of PlugInAuthorization resource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.management">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a> in <a href="../../../../../../../org/wildfly/swarm/management/package-summary.html">org.wildfly.swarm.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../../org/wildfly/swarm/management/package-summary.html">org.wildfly.swarm.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/management/InMemoryAuthorization.html#InMemoryAuthorization-org.wildfly.swarm.config.management.security_realm.PlugInAuthorization-">InMemoryAuthorization</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthorization</a> plugin)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthorization.html" title="class in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.4.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/PlugInAuthorization.html" target="_top">Frames</a></li>
<li><a href="PlugInAuthorization.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2.4.0.Final/apidocs/org/wildfly/swarm/config/management/security_realm/class-use/PlugInAuthorization.html
|
HTML
|
apache-2.0
| 15,712
|
var platform = require('platformSupport');
var alloyAnimation = require('alloy/animation');
var screenWidth ;
if(OS_IOS){
screenWidth = platform.getScreenWidth();
}else{
screenWidth = platform.convertDptoPx(platform.getScreenWidth());
}
var screenHeight ;
if(OS_IOS){
screenHeight = platform.getScreenHeight();
}else{
screenHeight = platform.convertDptoPx(platform.getScreenHeight());
}
//alert(screenWidth);
exports.in = function(form){
form.left = screenWidth;
form.right = -(screenWidth);
form.opacity = 0;
form.open();
form.animate({
left : screenWidth,
right : -(screenWidth),
duration : 1
}, function() {
form.opacity = 1;
form.animate({
left : 0,
right : 0,
duration : 200
});
});
};
exports.inAndClose = function(form, closeForm){
form.left = screenWidth;
form.right = -(screenWidth);
form.opacity = 0;
form.open();
form.animate({
left : screenWidth,
right : -(screenWidth),
duration : 1
}, function() {
form.opacity = 1;
form.animate({
left : 0,
right : 0,
duration : 200
}, function(){
closeForm.close();
});
});
};
exports.out = function(form){
form.animate({
left : screenWidth,
right : -(screenWidth),
duration : 200
}, function() {
form.close();
});
};
exports.slowlyAppear = function(obj){
obj.animate({
opacity : 0,
duration : 20
},function(){
obj.animate({
opacity : 1,
duration : 2000
});
});
};
exports.appearFromLeft = function(obj) {
obj.animate({
opacity : 0,
left : obj.left + 8,
duration : 20
}, function() {
obj.animate({
left : obj.left,
opacity : 1,
duration : 1000
});
});
};
exports.inShake = function(form){
form.left = screenWidth;
form.right = -(screenWidth);
form.opacity = 0;
form.open();
form.animate({
left : screenWidth,
right : -(screenWidth),
duration : 2
}, function() {
form.animate({
left : 0,
right : 0,
duration : 200
}, function() {
alloyAnimation.shake(form, 200, null);
form.opacity = 1;
});
});
};
|
Plexsim/citytourApps
|
app/lib/animation.js
|
JavaScript
|
apache-2.0
| 2,022
|
/*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {ErrorsJSON} from "models/mixins/errors";
export interface MaterialJSON {
type: string;
attributes: MaterialAttributesJSON;
}
export interface BaseAttributesJSON {
name: string;
auto_update: boolean;
errors?: ErrorsJSON;
}
export interface UsernamePasswordJSON {
username?: string;
password?: string;
encrypted_password?: string;
}
export interface ScmAttributesJSON extends BaseAttributesJSON, UsernamePasswordJSON {
destination?: string;
}
export interface GitMaterialAttributesJSON extends ScmAttributesJSON {
url: string;
branch: string;
}
export interface SvnMaterialAttributesJSON extends ScmAttributesJSON {
url: string;
check_externals: boolean;
}
export interface HgMaterialAttributesJSON extends ScmAttributesJSON {
url: string;
}
export interface P4MaterialAttributesJSON extends ScmAttributesJSON {
port: string;
use_tickets: boolean;
view: string;
}
export interface TfsMaterialAttributesJSON extends ScmAttributesJSON {
url: string;
domain: string;
project_path: string;
}
export interface DependencyMaterialAttributesJSON extends BaseAttributesJSON {
pipeline: string;
stage: string;
}
export type MaterialAttributesJSON =
GitMaterialAttributesJSON
| SvnMaterialAttributesJSON
| HgMaterialAttributesJSON
| P4MaterialAttributesJSON
| TfsMaterialAttributesJSON
| DependencyMaterialAttributesJSON;
|
ind9/gocd
|
server/webapp/WEB-INF/rails/webpack/models/materials/serialization.ts
|
TypeScript
|
apache-2.0
| 1,987
|
#!/usr/bin/python3.7
import ssl
import remi.gui as gui
from remi import start, App
class Camera(App):
def __init__(self, *args, **kwargs):
super(Camera, self).__init__(*args)
def video_widgets(self):
width = '300'
height = '300'
self.video = gui.Widget(_type='video')
self.video.style['overflow'] = 'hidden'
self.video.attributes['autoplay'] = 'true'
self.video.attributes['width'] = width
self.video.attributes['height'] = height
def video_start(self, widget, callback_function):
self.execute_javascript("""
var params={};
var frame = 0;
document.video_stop = false;
const video = document.querySelector('video');
video.setAttribute("playsinline", true);
const canvas = document.createElement('canvas');
navigator.mediaDevices.getUserMedia({video: { facingMode: { ideal: "environment" } }, audio: false}).
then((stream) => {video.srcObject = stream});
const render = () => {
if (document.video_stop) { return; }
if (frame==30) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
params['image']=canvas.toDataURL()
remi.sendCallbackParam('%(id)s','%(callback_function)s',params)
frame = 0;
}
frame+=1;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
"""%{'id':str(id(self)), 'callback_function': str(callback_function)})
def video_stop(self, widget):
self.execute_javascript("""
document.video_stop = true;
const video = document.querySelector('video');
video.srcObject.getTracks()[0].stop();
""")
def process_image(self, **kwargs):
image = kwargs['image']
print('I am here')
### Do whatever you want with the image here
return
def main(self):
self.video_widgets()
screen = [self.video]
start_button = gui.Button('Start Video')
start_button.onclick.do(self.video_start, 'process_image')
screen.append(start_button)
stop_button = gui.Button('Stop Video')
stop_button.onclick.do(self.video_stop)
screen.append(stop_button)
return gui.VBox(children=screen)
if __name__ == "__main__":
start(Camera,
address='0.0.0.0',
port=2020,
multiple_instance=True,
enable_file_cache=True,
start_browser=False,
debug=False)
# certfile='./ssl_keys/fullchain.pem',
# keyfile='./ssl_keys/privkey.pem',
# ssl_version=ssl.PROTOCOL_TLSv1_2,
|
dddomodossola/remi
|
examples/examples_from_contributors/camera.py
|
Python
|
apache-2.0
| 2,815
|
package com.pungwe.cms.core.annotations.util;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to define a hook implementation. This can be applied directly to methods on any class. When a hook is being executed
* methods with this annotation will be found on the class path (provided they are in modules that are enabled) and executed.
* <p>
* Created by ian on 07/12/2015.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Hook {
String value();
}
|
thunderbird/pungwecms
|
core/src/main/java/com/pungwe/cms/core/annotations/util/Hook.java
|
Java
|
apache-2.0
| 680
|
/**
* Copyright (C) 2013
* by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* info@52north.org
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without the implied
* WARRANTY OF MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sensorweb.wdc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.Set;
import java.util.Timer;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WeatherDataCollector {
private static final String DATA_INTERVAL_MIN = "DATA_INTERVAL_MIN";
private static final long delay = 1000;
private static final String EXTERNAL_FILE_PATH = System.getProperty("user.home") + File.separator + ".WeatherDataCollector" + File.separator;
private static final String FILE_NAME = "config.properties";
private static final String INTERNAL_FILE_PATH = "/";
private static final String COLLECTOR_IMPLEMENTATION = "COLLECTOR_IMPLEMENTATION";
private static Logger LOG = LoggerFactory.getLogger(WeatherDataCollector.class);
private final Properties props = new Properties();
public void init() {
loadProperties();
final Timer timer = new Timer("52n-wdc-timer");
final DataCollector collector;
try{
collector = DataCollector.class.cast(Class.forName(props.getProperty(COLLECTOR_IMPLEMENTATION)).newInstance());
} catch(final InstantiationException e){
throw new IllegalStateException(e);
} catch(final IllegalAccessException e){
throw new IllegalStateException(e);
} catch(final ClassNotFoundException e){
throw new IllegalStateException(e);
}
collector.setProperties(props);
collector.init();
timer.scheduleAtFixedRate(new DataCollectionTask(collector),
delay,
getPeriod(props));
LOG.info("*** Initialized WeatherDataCollector ***");
}
private int getPeriod(final Properties props) {
try {
final int periodInMinutes = Integer.parseInt(props.getProperty(DATA_INTERVAL_MIN, "4"));
final int periodInMillis = 1000 * 60 * periodInMinutes;
LOG.debug("Period: {}m ({}ms)",periodInMinutes,periodInMillis);
return periodInMillis;
} catch (final NumberFormatException nfe) {
LOG.error("Could not read property '{}'. Please provide a valid number!",DATA_INTERVAL_MIN);
throw nfe;
}
}
private void loadProperties() {
try {
InputStream is;
String filePath = EXTERNAL_FILE_PATH + FILE_NAME;
final File file = new File(filePath);
if (!file.exists()) {
LOG.info("Load default settings from jar file");
filePath = INTERNAL_FILE_PATH + FILE_NAME;
is = getClass().getResourceAsStream(filePath);
} else if (!file.canRead()) {
LOG.warn("Could not load settings.");
LOG.warn("No reading permissions for " + file);
LOG.info("Load default settings from jar file");
filePath = INTERNAL_FILE_PATH + FILE_NAME;
is = getClass().getResourceAsStream(filePath);
} else {
LOG.info("Load settings from " + file);
is = new FileInputStream(file);
}
props .load(is);
} catch (final FileNotFoundException e) {
LOG.error("WeatherDataCollector settings not found.", e);
System.exit(1);
} catch (final IOException e) {
LOG.error("WeatherDataCollector settings not readable.", e);
System.exit(1);
}
// try storing properties in user.home
final File folder = new File(EXTERNAL_FILE_PATH);
if (!folder.exists()) {
final boolean successful = folder.mkdir();
if (!successful) {
LOG.warn("WeatherDataCollector settings could not be saved.");
LOG.warn("No writing permissions at " + folder);
return;
}
}
final File file = new File(EXTERNAL_FILE_PATH + FILE_NAME);
LOG.info("Save settings at " + file.getAbsolutePath());
try { //save properties
final OutputStream os = new FileOutputStream(file);
props.store(os, null);
} catch (final IOException e) {
LOG.error("WeatherDataCollector settings could not be saved.", e);
}
}
public static void main(final String[] args) {
logApplicationMetadata();
new WeatherDataCollector().init();
}
/**
* Method print all available information from the jar's manifest file.
*/
private static void logApplicationMetadata() {
LOG.trace("logApplicationMetadata()");
InputStream manifestStream;
String logMessage;
//
logMessage = "Application started";
manifestStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/MANIFEST.MF");
try {
final Manifest manifest = new Manifest(manifestStream);
final Attributes attributes = manifest.getMainAttributes();
final Set<Object> keys = attributes.keySet();
for (final Object object : keys) {
if (object instanceof Name) {
final Name key = (Name) object;
logMessage += String.format("\n\t\t%s: %s",key,attributes.getValue(key));
}
}
// add heap information
logMessage += "\n\t\t" + heapSizeInformation();
}
catch(final IOException ex) {
LOG.warn("Error while reading manifest file from application jar file: " + ex.getMessage());
}
LOG.info(logMessage);
}
protected static String heapSizeInformation() {
final long mb = 1024 * 1024;
final Runtime rt = Runtime.getRuntime();
final long maxMemoryMB = rt.maxMemory() / mb;
final long totalMemoryMB = rt.totalMemory() / mb;
final long freeMemoryMB = rt.freeMemory() / mb;
final long usedMemoryMB = (rt.totalMemory() - rt.freeMemory()) / mb;
return String.format("HeapSize Information: max: %sMB; total now: %sMB; free now: %sMB; used now: %sMB",
maxMemoryMB,
totalMemoryMB,
freeMemoryMB,
usedMemoryMB);
}
}
|
52North/WeatherDataCollector
|
src/main/java/org/n52/sensorweb/wdc/WeatherDataCollector.java
|
Java
|
apache-2.0
| 6,741
|
package br.com.controle.util.dao;
import br.com.controle.util.modelo.Horario;
/**
*
* @author Otavio Costa
*/
public class HorarioDAO extends DAOGenerico<Horario> {
}
|
OtavioCostaLima/ControleDeNotas
|
src/br/com/controle/util/dao/HorarioDAO.java
|
Java
|
apache-2.0
| 187
|
// Lucene version compatibility level 4.8.1
#if FEATURE_BREAKITERATOR
using ICU4N.Support.Text;
using YAF.Lucene.Net.Support;
using System;
using System.Diagnostics.CodeAnalysis;
namespace YAF.Lucene.Net.Analysis.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A CharacterIterator used internally for use with <see cref="ICU4N.Text.BreakIterator"/>
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class CharArrayIterator : CharacterIterator
{
private char[] array;
private int start;
private int index;
private int length;
private int limit;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual char[] Text => array;
public virtual int Start => start;
public virtual int Length => length;
/// <summary>
/// Set a new region of text to be examined by this iterator
/// </summary>
/// <param name="array"> text buffer to examine </param>
/// <param name="start"> offset into buffer </param>
/// <param name="length"> maximum length to examine </param>
public virtual void SetText(char[] array, int start, int length)
{
this.array = array;
this.start = start;
this.index = start;
this.length = length;
this.limit = start + length;
}
public override char Current => (index == limit) ? Done : array[index];
protected abstract char JreBugWorkaround(char ch);
public override char First()
{
index = start;
return Current;
}
public override int BeginIndex => 0;
public override int EndIndex => length;
public override int Index => index - start;
public override char Last()
{
index = (limit == start) ? limit : limit - 1;
return Current;
}
public override char Next()
{
if (++index >= limit)
{
index = limit;
return Done;
}
else
{
return Current;
}
}
public override char Previous()
{
if (--index < start)
{
index = start;
return Done;
}
else
{
return Current;
}
}
public override char SetIndex(int position)
{
if (position < BeginIndex || position > EndIndex)
{
throw new ArgumentException("Illegal Position: " + position);
}
index = start + position;
return Current;
}
public override object Clone()
{
return this.MemberwiseClone();
}
/// <summary>
/// Create a new <see cref="CharArrayIterator"/> that works around JRE bugs
/// in a manner suitable for <see cref="ICU4N.Text.BreakIterator.GetSentenceInstance()"/>.
/// </summary>
public static CharArrayIterator NewSentenceInstance()
{
return new CharArrayIteratorAnonymousClass2();
}
private class CharArrayIteratorAnonymousClass2 : CharArrayIterator
{
// no bugs
protected override char JreBugWorkaround(char ch)
{
return ch;
}
}
/// <summary>
/// Create a new <see cref="CharArrayIterator"/> that works around JRE bugs
/// in a manner suitable for <see cref="ICU4N.Text.BreakIterator.GetWordInstance()"/>.
/// </summary>
public static CharArrayIterator NewWordInstance()
{
return new CharArrayIteratorAnonymousClass4();
}
private class CharArrayIteratorAnonymousClass4 : CharArrayIterator
{
// no bugs
protected override char JreBugWorkaround(char ch)
{
return ch;
}
}
}
}
#endif
|
YAFNET/YAFNET
|
yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/Util/CharArrayIterator.cs
|
C#
|
apache-2.0
| 5,034
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (10.0.1) on Tue Aug 21 17:44:24 AEST 2018 -->
<title>Timer (acceloapi 0.0.1-SNAPSHOT API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="date" content="2018-08-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Timer (acceloapi 0.0.1-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Timer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../au/com/noojee/acceloapi/entities/TimeAllocation.html" title="class in au.com.noojee.acceloapi.entities"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../au/com/noojee/acceloapi/entities/Type.html" title="class in au.com.noojee.acceloapi.entities"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?au/com/noojee/acceloapi/entities/Timer.html" target="_top">Frames</a></li>
<li><a href="Timer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="../../../../../au/com/noojee/acceloapi/entities/package-summary.html">au.com.noojee.acceloapi.entities</a></div>
<h2 title="Class Timer" class="title">Class Timer</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>au.com.noojee.acceloapi.entities.Timer</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<pre>public class <span class="typeNameLabel">Timer</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Constructor</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr class="altColor">
<th class="colConstructorName" scope="row"><code><span class="memberNameLink"><a href="../../../../../au/com/noojee/acceloapi/entities/Timer.html#Timer--">Timer</a></span>()</code></th>
<td class="colLast"> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Timer--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Timer</h4>
<pre>public Timer()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Timer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../au/com/noojee/acceloapi/entities/TimeAllocation.html" title="class in au.com.noojee.acceloapi.entities"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../au/com/noojee/acceloapi/entities/Type.html" title="class in au.com.noojee.acceloapi.entities"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?au/com/noojee/acceloapi/entities/Timer.html" target="_top">Frames</a></li>
<li><a href="Timer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018. All rights reserved.</small></p>
</body>
</html>
|
bsutton/acceloapi
|
docs/au/com/noojee/acceloapi/entities/Timer.html
|
HTML
|
apache-2.0
| 9,216
|
# Beaucarnea longifolia (Karw. ex Schult. & Schult.f.) Baker SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Nolina/Nolina longifolia/ Syn. Beaucarnea longifolia/README.md
|
Markdown
|
apache-2.0
| 215
|
#!/bin/bash
WGET='/usr/bin/wget -q'
MD5SUM='/usr/bin/md5sum'
GUNZIP='/bin/gunzip'
RM='/bin/rm'
$RM -r delegated-afrinic-latest.md5
$WGET ftp://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-latest.md5
if ! $MD5SUM --check delegated-afrinic-latest.md5 > /dev/null 2>&1; then
$RM -f delegated-afrinic-latest
$WGET ftp://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-latest
fi
$RM -f delegated-lacnic-latest.md5
$WGET ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest.md5
if ! $MD5SUM --check delegated-lacnic-latest.md5 > /dev/null 2>&1; then
$RM -f delegated-lacnic-latest
$WGET ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest
fi
$RM -f delegated-arin-extended-latest.md5
$WGET ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest.md5
sed -i 's/[0-9]*$/latest/g' delegated-arin-extended-latest.md5
if ! $MD5SUM --check delegated-arin-extended-latest.md5 > /dev/null 2>&1; then
$RM -f delegated-arin-extended-latest
$WGET ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest
fi
$RM -f delegated-apnic-latest.md5
$WGET ftp://ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest.md5
if ! $MD5SUM --check delegated-apnic-latest.md5 > /dev/null 2>&1; then
$RM -f delegated-apnic-latest
$RM -f apnic.db.inetnum*
$WGET ftp://ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest
ftp -n -v ftp.apnic.net <<END
user anonymous -anonymous@anonymous.org
binary
passive
get /apnic/whois/apnic.db.inetnum.gz apnic.db.inetnum.gz
bye
END
$GUNZIP apnic.db.inetnum
fi
$RM -f delegated-ripencc-latest.md5
$WGET ftp://ftp.ripe.net/ripe/stats/delegated-ripencc-latest.md5
if ! $MD5SUM --check delegated-ripencc-latest.md5 > /dev/null 2>&1; then
$RM -f delegated-ripencc-latest
$RM -f ripe.db.inetnum*
$WGET ftp://ftp.ripe.net/ripe/stats/delegated-ripencc-latest
$WGET ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.inetnum.gz
$GUNZIP ripe.db.inetnum
fi
|
Markus-Go/ip-countryside
|
getDBs.sh
|
Shell
|
apache-2.0
| 1,933
|
package org.gradle.test.performance.mediummonolithicjavaproject.p422;
public class Production8447 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
}
|
oehme/analysing-gradle-performance
|
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p422/Production8447.java
|
Java
|
apache-2.0
| 1,891
|
/**
*
*/
package org.vaadin.netbeans.refactoring;
import java.util.List;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
import org.netbeans.api.java.source.TreeMaker;
import org.netbeans.api.java.source.WorkingCopy;
import org.netbeans.modules.refactoring.api.SafeDeleteRefactoring;
import org.vaadin.netbeans.code.generator.JavaUtils;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.Tree;
/**
* @author denis
*/
class DeletePackageRefactoringPlugin extends
AbstractPackageRefactoringPlugin<SafeDeleteRefactoring>
{
DeletePackageRefactoringPlugin( SafeDeleteRefactoring refactoring ) {
super(refactoring);
}
@Override
protected TransformTask getTransformTask() {
return new DeleteGwtTask();
}
static void removeWebServletAnnotation( TypeElement type, WorkingCopy copy,
AnnotationMirror annotation )
{
TreeMaker treeMaker = copy.getTreeMaker();
Tree tree = copy.getTrees().getTree(type, annotation);
if (tree instanceof AnnotationTree) {
Tree[] trees = getDeleteWidgetChangedTrees((AnnotationTree) tree,
treeMaker);
if (trees[0] == null || trees[1] == null) {
return;
}
copy.rewrite(trees[0], trees[1]);
}
}
static void removeVaadinServletAnnotation( TypeElement type,
WorkingCopy copy, AnnotationMirror annotation )
{
TreeMaker treeMaker = copy.getTreeMaker();
Tree tree = copy.getTrees().getTree(type, annotation);
AnnotationTree annotationTree = null;
if (tree instanceof AnnotationTree) {
annotationTree = (AnnotationTree) tree;
}
else {
return;
}
ExpressionTree widgetsetTree = getAnnotationTreeAttribute(
annotationTree, JavaUtils.WIDGETSET);
AnnotationTree newTree = treeMaker.removeAnnotationAttrValue(
annotationTree, widgetsetTree);
copy.rewrite(annotationTree, newTree);
}
static Tree[] getDeleteWidgetChangedTrees(
AnnotationTree servletAnnotation, TreeMaker maker )
{
Tree oldTree = null;
Tree newTree = null;
ExpressionTree expressionTree = getAnnotationTreeAttribute(
servletAnnotation, JavaUtils.INIT_PARAMS);
if (expressionTree instanceof AssignmentTree) {
AssignmentTree assignmentTree = (AssignmentTree) expressionTree;
ExpressionTree expression = assignmentTree.getExpression();
if (expression instanceof AnnotationTree) {
AnnotationTree widgetsetTree = (AnnotationTree) expression;
if (getWidgetset(widgetsetTree) != null) {
oldTree = servletAnnotation;
newTree = maker.removeAnnotationAttrValue(
servletAnnotation, expressionTree);
}
}
else if (expression instanceof NewArrayTree) {
NewArrayTree arrayTree = (NewArrayTree) expression;
List<? extends ExpressionTree> expressions = arrayTree
.getInitializers();
for (ExpressionTree webInitAnnotation : expressions) {
if (webInitAnnotation instanceof AnnotationTree) {
AnnotationTree widgetsetTree = (AnnotationTree) webInitAnnotation;
if (getWidgetset(widgetsetTree) != null) {
oldTree = arrayTree;
newTree = maker.removeNewArrayInitializer(
arrayTree, widgetsetTree);
break;
}
}
}
}
}
return new Tree[] { oldTree, newTree };
}
class DeleteGwtTask extends AbstractTransformTask {
DeleteGwtTask() {
super(getAcceptor());
}
@Override
protected void doUpdateWebServletAnnotation( TypeElement type,
WorkingCopy copy, AnnotationMirror annotation,
String widgetsetFqn )
{
removeWebServletAnnotation(type, copy, annotation);
}
@Override
protected void doUpdateVaadinServletAnnotation( TypeElement type,
WorkingCopy copy, AnnotationMirror annotation,
String widgetsetFqn )
{
removeVaadinServletAnnotation(type, copy, annotation);
}
}
}
|
Artur-/foobar
|
src/org/vaadin/netbeans/refactoring/DeletePackageRefactoringPlugin.java
|
Java
|
apache-2.0
| 4,746
|
#include "stdafx.h"
#include "radioactivezone.h"
#include "hudmanager.h"
#include "level.h"
#include "xrmessages.h"
#include "../bone.h"
#include "clsid_game.h"
#include "game_base_space.h"
#include "Hit.h"
CRadioactiveZone::CRadioactiveZone(void)
{}
CRadioactiveZone::~CRadioactiveZone(void)
{}
void CRadioactiveZone::Load(LPCSTR section)
{
inherited::Load(section);
}
bool CRadioactiveZone::BlowoutState ()
{
bool result = inherited::BlowoutState();
if(!result) UpdateBlowout();
return result;
}
void CRadioactiveZone::Affect(SZoneObjectInfo* O)
{
// âåðìÿ ñðàáàòûâàíèÿ íå ÷àùå, ÷åì çàäàííûé ïåðèîä
if(m_dwDeltaTime < m_dwPeriod) return;
//. m_dwDeltaTime = 0;
CGameObject *GO = O->object;
if(GO)
{
Fvector pos;
XFORM().transform_tiny(pos,CFORM()->getSphere().P);
#ifdef DEBUG
char pow[255];
sprintf(pow, "zone hit. %.3f", Power(GO->Position().distance_to(pos)));
if(bDebug) Msg("%s %s", *GO->cName(), pow);
#endif
Fvector dir;
dir.set(0,0,0);
Fvector position_in_bone_space;
float power = (GameID() == GAME_SINGLE) ? Power(GO->Position().distance_to(pos)) : 0.0f;
float impulse = 0.f;
if(power > EPS)
{
//. m_dwDeltaTime = 0;
position_in_bone_space.set(0.f,0.f,0.f);
CreateHit(GO->ID(),ID(),dir,power,BI_NONE,position_in_bone_space,impulse,ALife::eHitTypeRadiation);
}
}
}
void CRadioactiveZone::feel_touch_new (CObject* O )
{
inherited::feel_touch_new(O);
if (GameID() != GAME_SINGLE)
{
if (O->CLS_ID == CLSID_OBJECT_ACTOR)
{
CreateHit(O->ID(),ID(),Fvector().set(0, 0, 0),0.0f,BI_NONE,Fvector().set(0, 0, 0),0.0f,ALife::eHitTypeRadiation);
}
};
};
#include "actor.h"
BOOL CRadioactiveZone::feel_touch_contact(CObject* O)
{
CActor* A = smart_cast<CActor*>(O);
if ( A )
{
if (!((CCF_Shape*)CFORM())->Contact(O)) return FALSE;
return A->feel_touch_on_contact(this);
}else
return FALSE;
}
void CRadioactiveZone::UpdateWorkload (u32 dt)
{
if (IsEnabled() && GameID() != GAME_SINGLE)
{
OBJECT_INFO_VEC_IT it;
Fvector pos;
XFORM().transform_tiny(pos,CFORM()->getSphere().P);
for(it = m_ObjectInfoMap.begin(); m_ObjectInfoMap.end() != it; ++it)
{
if( !(*it).object->getDestroy() && (*it).object->CLS_ID == CLSID_OBJECT_ACTOR)
{
//=====================================
NET_Packet l_P;
l_P.write_start();
l_P.read_start();
float dist = (*it).object->Position().distance_to(pos);
float power = Power(dist)*dt/1000;
/// Msg("Zone Dist %f, Radiation Power %f, ", dist, power);
SHit HS;
HS.GenHeader(GE_HIT, (*it).object->ID());
HS.whoID =ID();
HS.weaponID = ID();
HS.dir = Fvector().set(0,0,0);
HS.power = power;
HS.boneID = BI_NONE;
HS.p_in_bone_space = Fvector().set(0, 0, 0);
HS.impulse = 0.0f;
HS.hit_type = ALife::eHitTypeRadiation;
HS.Write_Packet_Cont(l_P);
(*it).object->OnEvent(l_P, HS.PACKET_TYPE);
//=====================================
};
}
}
inherited::UpdateWorkload(dt);
}
|
OLR-xray/XRay-NEW
|
XRay/xr_3da/xrGame/RadioactiveZone.cpp
|
C++
|
apache-2.0
| 3,021
|
# Gasteria spiralis var. tortulata VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Xanthorrhoeaceae/Gasteria/Gasteria obliqua/ Syn. Gasteria spiralis tortulata/README.md
|
Markdown
|
apache-2.0
| 189
|
// Copyright 2019 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*! THIS FILE IS AUTO-GENERATED */
import {AuthPlus, getAPI, GoogleConfigurable} from 'googleapis-common';
import {translate_v2} from './v2';
import {translate_v3beta1} from './v3beta1';
export const VERSIONS = {
v2: translate_v2.Translate,
v3beta1: translate_v3beta1.Translate,
};
export function translate(version: 'v2'): translate_v2.Translate;
export function translate(
options: translate_v2.Options
): translate_v2.Translate;
export function translate(version: 'v3beta1'): translate_v3beta1.Translate;
export function translate(
options: translate_v3beta1.Options
): translate_v3beta1.Translate;
export function translate<
T = translate_v2.Translate | translate_v3beta1.Translate
>(
this: GoogleConfigurable,
versionOrOptions:
| 'v2'
| translate_v2.Options
| 'v3beta1'
| translate_v3beta1.Options
) {
return getAPI<T>('translate', versionOrOptions, VERSIONS, this);
}
const auth = new AuthPlus();
export {auth};
|
stems/google-api-nodejs-client
|
src/apis/translate/index.ts
|
TypeScript
|
apache-2.0
| 1,538
|
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.spectrads3;
import com.spectralogic.ds3client.models.ChecksumType;
import com.spectralogic.ds3client.commands.interfaces.AbstractResponse;
public class ImportS3TargetSpectraS3Response extends AbstractResponse {
public ImportS3TargetSpectraS3Response(final String checksum, final ChecksumType.Type checksumType) {
super(checksum, checksumType);
}
}
|
DenverM80/ds3_java_sdk
|
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/spectrads3/ImportS3TargetSpectraS3Response.java
|
Java
|
apache-2.0
| 1,220
|
# Ivysalt's sentry module. It keeps track of people who join and leave a chat.
# LICENSE: This single module is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
# @category Tools
# @copyright Copyright (c) 2018 dpc
# @version 1.1
# @author dpc
import asyncio
import json
import os
from discord.ext import commands
from cogs.utils import checks
from cogs.utils.dataIO import fileIO
ban_message = "``Omae wa mou shindeiru.``"
joinleave_path = 'data/sentry/joinleave.json'
bans_path = 'data/sentry/bans.json'
def is_int(s):
"""Checks whether the input is an integer."""
try:
int(s)
if float(s) % 1 == 0:
return True
else:
return False
except ValueError:
return False
def check_folders():
folders = ["data/sentry"]
for folder in folders:
if not os.path.exists(folder):
print("Creating " + folder + " folder...")
os.makedirs(folder)
def check_files():
default = {}
if not os.path.isfile(joinleave_path):
print("Creating joinleave.json")
fileIO(joinleave_path, "save", default)
if not os.path.isfile(bans_path):
print("Creating bans.json")
fileIO(bans_path, "save", default)
# validating data
check_folders()
check_files()
with open(joinleave_path) as joinleave_file:
joinleave_data = json.load(joinleave_file)
with open(bans_path) as sentry_file:
sentry_bans = json.load(sentry_file)
def save(path, data):
with open(path, "w") as file:
json.dump(data, file, indent=4)
class Sentry:
"""Adds various sentry commands.
This module was written specifically for a few servers."""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, no_pm=True)
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def preban(self, ctx, user_id: str):
"""Users added with this command will be banned on sight.
Only admins may use this command."""
# adding user id to the ban list
if is_int(user_id):
if (ctx.message.server.id in sentry_bans):
if (user_id in sentry_bans[ctx.message.server.id]):
yield from self.bot.say("That user is already pre-banned from this server.")
else:
sentry_bans[ctx.message.server.id].append(user_id)
save(bans_path, sentry_bans)
yield from self.bot.say("User has been pre-banned from this server.")
else:
sentry_bans[ctx.message.server.id] = [user_id]
save(bans_path, sentry_bans)
yield from self.bot.say("User has been pre-banned from this server.")
else:
yield from self.bot.say("Improper command usage.")
# checking if user's already in the server, and banning them if they are
for member in ctx.message.server.members:
if (member.id in sentry_bans[member.server.id]):
#yield from self.bot.send_message(member, ban_message)
yield from (asyncio.sleep(2))
yield from self.bot.ban(member, 7)
print("Banning user {0}#{2} with id {3} from {1}...".format(member.name, member.server.name, member.discriminator, member.id))
@commands.command(pass_context=True, no_pm=True, description=
"Note: users that have been already banned will not be unbanned.")
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def unpreban(self, ctx, user_id: str):
"""Users removed with this command will not be banned on sight.
Only admins may use this command."""
if (ctx.message.server.id in sentry_bans):
if (user_id in sentry_bans[ctx.message.server.id]):
sentry_bans[ctx.message.server.id].remove(user_id)
save(bans_path, sentry_bans)
yield from self.bot.say("User removed from pre-ban list on this server.")
else:
yield from self.bot.say("User is not pre-banned on this server.")
else:
yield from self.bot.say("User is not pre-banned on this server.")
@commands.command(pass_context=True, no_pm=True, description=
"Note: users that have been already banned will not be unbanned.")
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def listpreban(self, ctx):
"""Users removed with this command will not be banned on sight.
Only admins may use this command."""
if (ctx.message.server.id in sentry_bans):
if len(sentry_bans[ctx.message.server.id]) > 0:
user_id_list = "```\n=== Prebans in server {} ===\n".format(ctx.message.server.name)
for user_id in sentry_bans[ctx.message.server.id]:
user_id_list += user_id
user_id_list += "\n"
user_id_list += "```"
yield from self.bot.send_message(ctx.message.author, user_id_list)
else:
yield from self.bot.say("No pre-bans on this server.")
else:
yield from self.bot.say("No pre-bans on this server.")
@commands.command(pass_context=True, no_pm=True)
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def unban(self, ctx, *, uid: str = None):
"""Removes a ban from the server.
Only admins may use this command."""
user = yield from self.bot.get_user_info(uid)
yield from self.bot.unban(ctx.message.server, user)
yield from self.bot.say('User {} unbanned.'.format(user.name))
@commands.command(pass_context=True, no_pm=True)
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def setannounce(self, ctx, channel: str = "current"):
"""Sets the channel to announce server's arrivals and parts.\n\nOnly admins may use this command."""
# parses the input as a channel id
if (len(ctx.message.channel_mentions) == 1):
channel_id = ctx.message.channel_mentions[0].id
elif is_int(channel):
channel_id = channel
elif channel == "current":
channel_id = ctx.message.channel
else:
yield from self.bot.say("Sorry, I don't know what channel that is.")
return
#checks if channel is in server
channel_object = ctx.message.server.get_channel(channel_id)
if channel_object is None:
yield from self.bot.say("Sorry, I can't tell what channel that is.")
return
# assigns the announce channel
if (ctx.message.server.id in joinleave_data):
joinleave_data[ctx.message.server.id]["announce_channel"] = channel_id
save(joinleave_path, joinleave_data)
yield from self.bot.say("Saved announce channel {}.".format(channel_object.mention))
else:
joinleave_data[ctx.message.server.id] = {"announce_channel": channel_id, "autoassign_role": "", "join_announce": False, "leave_announce": True}
save(joinleave_path, joinleave_data)
yield from self.bot.say("Saved announce channel {}.".format(channel_object.mention))
@commands.command(pass_context=True, no_pm=True)
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def delannounce(self, ctx):
"""Removes the bot announcements in this server.\n\nOnly admins may use this command."""
# assigns the announce channel
if (ctx.message.server.id in joinleave_data):
joinleave_data[ctx.message.server.id]["announce_channel"] = ""
yield from self.bot.say("Removed announce channel for this server.")
else:
joinleave_data[ctx.message.server.id] = {"announce_channel": "", "autoassign_role": "", "join_announce": False, "leave_announce": True}
yield from self.bot.say("There was no announce channel for this server.")
@commands.command(pass_context=True, no_pm=True)
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def announcejoin(self, ctx, join: bool = False):
"""Sets the bot to announce server's new arrivals.\n\nOnly admins may use this command."""
# assigns the announce channel
if (ctx.message.server.id in joinleave_data):
joinleave_data[ctx.message.server.id]["join_announce"] = join
save(joinleave_path, joinleave_data)
yield from self.bot.say("Setting for join announcement set to ``{}``.".format(join))
else:
yield from self.bot.say("Server data not found. Set an announcement channel with ``?setannounce`` first.")
@commands.command(pass_context=True, no_pm=True)
@checks.admin_or_permissions(ban_members=True)
@asyncio.coroutine
def announceleave(self, ctx, leave: bool = True):
"""Sets the bot to announce server's new arrivals.\n\nOnly admins may use this command."""
# assigns the announce channel
if (ctx.message.server.id in joinleave_data):
joinleave_data[ctx.message.server.id]["leave_announce"] = leave
save(joinleave_path, joinleave_data)
yield from self.bot.say("Setting for leave announcement set to ``{}``.".format(leave))
else:
yield from self.bot.say("Server data not found. Set an announcement channel with ``?setannounce`` first.")
@asyncio.coroutine
def on_member_join(self, member):
if (member.server.id in sentry_bans):
if (member.id in sentry_bans[member.server.id]):
#yield from self.bot.send_message(member, ban_message)
yield from (asyncio.sleep(2))
yield from self.bot.ban(member, 7)
print("Banning user {0}#{2} with ID {3} from {1}...".format(member.name, member.server.name, member.discriminator, member.id))
if (member.server.id in joinleave_data):
yield from self.bot.send_message(member.server.get_channel(joinleave_data[member.server.id]["announce_channel"]), "Intruder **{0}#{2}** with ID ``{3}`` sighted! Banning from {1}.".format(member.name, member.server.name, member.discriminator, member.id))
if (member.server.id in joinleave_data) and (joinleave_data[member.server.id]["join_announce"] == True):
yield from self.bot.send_message(member.server.get_channel(joinleave_data[member.server.id]["announce_channel"]),"**{0}#{1}**, with user ID {2}, just joined **{3}**!".format(member.name, member.discriminator, member.id, member.server.name))
@asyncio.coroutine
def on_member_remove(self, member):
if (member.server.id in joinleave_data) and (joinleave_data[member.server.id]["leave_announce"] != False):
yield from self.bot.send_message(member.server.get_channel(joinleave_data[member.server.id]["announce_channel"]),"**{0}#{1}**, with user ID {2}, just left **{3}**!".format(member.name, member.discriminator, member.id, member.server.name))
@asyncio.coroutine
def on_ready(self):
for server in self.bot.servers:
if (server.id in sentry_bans):
for member in server.members:
if (member.id in sentry_bans[server.id]):
#yield from self.bot.send_message(member, ban_message)
yield from (asyncio.sleep(2))
yield from self.bot.ban(member, 7)
print("Banning user {0}#{2} with ID {3} from {1}...".format(member.name, server.name, member.discriminator, member.id))
def setup(bot):
check_folders()
check_files()
bot.add_cog(Sentry(bot))
|
retrodpc/Bulbaspot-Cogs
|
sentry/sentry.py
|
Python
|
apache-2.0
| 11,849
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.