code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
import subprocess
from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.base.workunit import WorkUnitLabel
from pants.binaries.thrift_binary import ThriftBinary
from pants.task.simple_codegen_task import SimpleCodegenTask
from pants.util.dirutil import safe_mkdir
from pants.util.memo import memoized_property
from twitter.common.collections import OrderedSet
from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary
class GoThriftGen(SimpleCodegenTask):
@classmethod
def register_options(cls, register):
super(GoThriftGen, cls).register_options(register)
register('--strict', default=True, fingerprint=True, type=bool,
help='Run thrift compiler with strict warnings.')
register('--gen-options', advanced=True, fingerprint=True,
help='Use these apache thrift go gen options.')
register('--thrift-import', advanced=True,
help='Use this thrift-import gen option to thrift.')
register('--thrift-import-target', advanced=True,
help='Use this thrift import on symbolic defs.')
@classmethod
def subsystem_dependencies(cls):
return (super(GoThriftGen, cls).subsystem_dependencies() +
(ThriftDefaults, ThriftBinary.Factory.scoped(cls)))
@memoized_property
def _thrift_binary(self):
thrift_binary = ThriftBinary.Factory.scoped_instance(self).create()
return thrift_binary.path
@memoized_property
def _deps(self):
thrift_import_target = self.get_options().thrift_import_target
thrift_imports = self.context.resolve(thrift_import_target)
return thrift_imports
@memoized_property
def _service_deps(self):
service_deps = self.get_options().get('service_deps')
return list(self.resolve_deps(service_deps)) if service_deps else self._deps
SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)')
NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE)
def _declares_service(self, source):
with open(source) as thrift:
return any(line for line in thrift if self.SERVICE_PARSER.search(line))
def _get_go_namespace(self, source):
with open(source) as thrift:
namespace = self.NAMESPACE_PARSER.search(thrift.read())
if not namespace:
raise TaskError('Thrift file {} must contain "namespace go "', source)
return namespace.group(1)
def synthetic_target_extra_dependencies(self, target, target_workdir):
for source in target.sources_relative_to_buildroot():
if self._declares_service(os.path.join(get_buildroot(), source)):
return self._service_deps
return self._deps
def synthetic_target_type(self, target):
return GoThriftGenLibrary
def is_gentarget(self, target):
return isinstance(target, GoThriftLibrary)
@memoized_property
def _thrift_cmd(self):
cmd = [self._thrift_binary]
thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import)
gen_options = self.get_options().gen_options
if gen_options:
gen_options += ',' + thrift_import
else:
gen_options = thrift_import
cmd.extend(('--gen', 'go:{}'.format(gen_options)))
if self.get_options().strict:
cmd.append('-strict')
if self.get_options().level == 'debug':
cmd.append('-verbose')
return cmd
def _generate_thrift(self, target, target_workdir):
target_cmd = self._thrift_cmd[:]
bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt))
for base in bases:
target_cmd.extend(('-I', base))
target_cmd.extend(('-o', target_workdir))
all_sources = list(target.sources_relative_to_buildroot())
if len(all_sources) != 1:
raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target)
source = all_sources[0]
target_cmd.append(os.path.join(get_buildroot(), source))
with self.context.new_workunit(name=source,
labels=[WorkUnitLabel.TOOL],
cmd=' '.join(target_cmd)) as workunit:
result = subprocess.call(target_cmd,
stdout=workunit.output('stdout'),
stderr=workunit.output('stderr'))
if result != 0:
raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result))
gen_dir = os.path.join(target_workdir, 'gen-go')
src_dir = os.path.join(target_workdir, 'src')
safe_mkdir(src_dir)
go_dir = os.path.join(target_workdir, 'src', 'go')
os.rename(gen_dir, go_dir)
@classmethod
def product_types(cls):
return ['go']
def execute_codegen(self, target, target_workdir):
self._generate_thrift(target, target_workdir)
@property
def _copy_target_attributes(self):
"""Override `_copy_target_attributes` to exclude `provides`."""
return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides']
def synthetic_target_dir(self, target, target_workdir):
all_sources = list(target.sources_relative_to_buildroot())
source = all_sources[0]
namespace = self._get_go_namespace(source)
return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep))
| cevaris/pants | contrib/go/src/python/pants/contrib/go/tasks/go_thrift_gen.py | Python | apache-2.0 | 5,677 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_25) on Tue Feb 07 22:52:55 CET 2012 -->
<TITLE>
S-Index
</TITLE>
<META NAME="date" CONTENT="2012-02-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="S-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../com/osbcp/cssparser/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-8.html"><B>PREV LETTER</B></A>
<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">C</A> <A HREF="index-3.html">E</A> <A HREF="index-4.html">G</A> <A HREF="index-5.html">H</A> <A HREF="index-6.html">I</A> <A HREF="index-7.html">P</A> <A HREF="index-8.html">R</A> <A HREF="index-9.html">S</A> <A HREF="index-10.html">T</A> <A HREF="index-11.html">V</A> <HR>
<A NAME="_S_"><!-- --></A><H2>
<B>S</B></H2>
<DL>
<DT><A HREF="../com/osbcp/cssparser/Selector.html" title="class in com.osbcp.cssparser"><B>Selector</B></A> - Class in <A HREF="../com/osbcp/cssparser/package-summary.html">com.osbcp.cssparser</A><DD>Represents a CSS selector.<DT><A HREF="../com/osbcp/cssparser/Selector.html#Selector(java.lang.String)"><B>Selector(String)</B></A> -
Constructor for class com.osbcp.cssparser.<A HREF="../com/osbcp/cssparser/Selector.html" title="class in com.osbcp.cssparser">Selector</A>
<DD>Creates a new selector.
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../com/osbcp/cssparser/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-8.html"><B>PREV LETTER</B></A>
<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">C</A> <A HREF="index-3.html">E</A> <A HREF="index-4.html">G</A> <A HREF="index-5.html">H</A> <A HREF="index-6.html">I</A> <A HREF="index-7.html">P</A> <A HREF="index-8.html">R</A> <A HREF="index-9.html">S</A> <A HREF="index-10.html">T</A> <A HREF="index-11.html">V</A> <HR>
</BODY>
</HTML>
| corgrath/osbcp-css-parser | doc/javadoc/index-files/index-9.html | HTML | apache-2.0 | 6,207 |
# Github pages for DHGMS Solutions
## Introduction
This is the branch for the [Github pages for the DHGMS Solutions project documentation](http://dhgms-solutions.github.io/).
## Viewing the documentation
The documentation can be found at http://dhgms-solutions.github.io/
## Contributing to the documentation
It is likely you won't want to contribute to this repository, but one of the [actual project repositories](https://github.com/DHGMS-Solutions/).
### 1\. Fork the documentation
See the [github help page for instructions on how to create a fork](http://help.github.com/fork-a-repo/).
### 2\. Write desired content
Use your preffered method for carrying out work.
### 3\. Send a pull request
See the [github help page for instructions on how to send pull requests](http://help.github.com/send-pull-requests/)
| DHGMS-Solutions/dhgms-solutions.github.io | README.md | Markdown | apache-2.0 | 827 |
var gplay = require('google-play-scraper');
var fs = require('fs')
var Promise = require('promise');
var myArgs = process.argv.slice(2);
var passed_appid = myArgs[0];
var passed_appcount = myArgs[1];
console.log(passed_appid);
var read = Promise.denodeify(fs.readFile);
var write = Promise.denodeify(fs.writeFile);
var dir = './dataset/' + passed_appcount;
gplay.app({appId: passed_appid})
.then(function (str) {
if(JSON.stringify(str, null, ' ').indexOf("title") > -1) {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
return write(dir + '/meta.json', JSON.stringify(str, null, ' '), 'utf8')
} else {
console.log('app doesnt exist');
return false
}
})
.then(function (){process.exit()}); | iresium/apprater | scraper.js | JavaScript | apache-2.0 | 764 |
import unittest, re
from rexp.compiler import PatternCompiler
class CompilerTestMethods(unittest.TestCase):
def test_compile_1(self):
compiler = PatternCompiler(pattern_set=dict(
TEST=r'\w+'
))
try:
c1 = compiler.compile('$1{TEST}')
except Exception as exc:
self.assertTrue(1)
c1 = compiler.compile('$1{TEST}', ['test'])
self.assertEqual(c1, r'(?:(?P<test>(\w+)))')
def test_compile_2(self):
compiler = PatternCompiler(pattern_set=dict(
TEST=r'\w+'
))
try:
c1 = compiler.compile('$1{TEST}')
except:
self.assertTrue(1)
c1 = compiler.compile('$1{TEST}', ['test'])
self.assertEqual(c1, r'(?:(?P<test>(\w+)))')
| ebbkrdrcn/rexp | test/compiler.py | Python | apache-2.0 | 790 |
<!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_79) on Thu Sep 17 01:48:29 IST 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery (Solr 5.3.1 API)</title>
<meta name="date" content="2015-09-17">
<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="Uses of Class org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery (Solr 5.3.1 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><a href="../../../../../../../org/apache/solr/client/solrj/request/CoreAdminRequest.RequestRecovery.html" title="class in org.apache.solr.client.solrj.request">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/solr/client/solrj/request/class-use/CoreAdminRequest.RequestRecovery.html" target="_top">Frames</a></li>
<li><a href="CoreAdminRequest.RequestRecovery.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.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery" class="title">Uses of Class<br>org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery</div>
<!-- ======= 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><a href="../../../../../../../org/apache/solr/client/solrj/request/CoreAdminRequest.RequestRecovery.html" title="class in org.apache.solr.client.solrj.request">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/solr/client/solrj/request/class-use/CoreAdminRequest.RequestRecovery.html" target="_top">Frames</a></li>
<li><a href="CoreAdminRequest.RequestRecovery.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>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| TitasNandi/Summer_Project | solr-5.3.1/docs/solr-solrj/org/apache/solr/client/solrj/request/class-use/CoreAdminRequest.RequestRecovery.html | HTML | apache-2.0 | 5,193 |
// Models
app.SearchModel = Backbone.Model.extend({
idAttribute: "session_token",
urlRoot: function() {
var u = '/search/' + this.id;
return u;
}
});
// Collections
app.SearchCollection = Backbone.Collection.extend({
model: app.SearchModel,
url: function() {
if (typeof this.id === 'undefined')
return '/search';
else
return '/search/' + this.id;
},
initialize: function(options) {
if (typeof options != 'undefined')
this.id = options.session_token;
}
});
// Views
app.cardList = Backbone.View.extend({
el: '#cardList'
});
app.cardView = Backbone.View.extend({
tagName: 'div',
initialize: function(card) {
this.card = card;
},
template: _.template($("#card-template").html()),
render: function(cardList) {
this.$el.html(this.template({
card: this.card
}));
this.$el.addClass('card');
cardList.$el.append(this.el);
return this;
}
}); | GOPINATH-GS4/stock | public/lib/cards.js | JavaScript | apache-2.0 | 1,119 |
---
layout: post
title: "383. Ransom Note-勒索信"
subtitle: " \"LeetCode\""
date: 2016-9-13 10:08:36
author: "Zering"
header-img: "img/road.jpg"
catalog: true
tags:
- LeetCode
---
### 问题
问题地址:https://leetcode.com/problems/ransom-note/
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
### 问题翻译
任意给你一个勒索信字符串和一个包含杂志所有字母的字符串,写一个功能判断勒索信能否由杂志的字母组成。
杂志里的每一个字母只能使用一次
注意:假定所有的字母都是小写字母,示例:
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
### 问题分析
1. 杂志必须包含勒索信的所有字母;
2. 杂志单个字母只能使用一次;
这个问题,最简单的想法就是逐一的遍历勒索信和杂志字母,以下提供三种解法:
解法一:将ransomNote的字符串挨个遍历,每个字符再从magazine里遍历匹配,只是再创建了个byte数组,数组每个元素的索引表示magazine字符串的位置,元素值表示是否被校验过,0表示还未被校验过,非0就表示该位置已经被校验过。不过这种做法效率不高。
解法二:将ransomNote和magazine都从小到大排序,然后对ransomNote遍历,同时在magazine中匹配,如果匹配到了,则记住此时magazine中字符的索引,便于下次操作,因为都是排序的。如果直到magazine中字符已经大于ransomNote中字符了,就说明就再也匹配不到了,则表示匹配失败。
解法三:LeetCode Discuss中的最热代码,它的原理是列出了magazine的字母表,然后算出了出现个数,然后遍历ransomNote,保证有足够的字母可用,代码非常清晰。
### 问题解答(java示例)
解法一:
public boolean canConstruct(String ransomNote, String magazine) {
boolean ret = true;
byte[] bytes = new byte[magazine.length()];
for (int i = 0; i < ransomNote.length(); i++) {
char c = ransomNote.charAt(i);
boolean found = false;
for (int j = 0; j < magazine.length(); j++) {
if (bytes[j] == 0 && magazine.charAt(j) == c) {
bytes[j]++;
found = true;
break;
}
}
if (!found) {
ret = false;
break;
}
}
return ret;
}
解法二:
public boolean canConstruct(String ransomNote, String magazine) {
boolean ret = true;
char[] ra = ransomNote.toCharArray();
Arrays.sort(ra);
char[] ma = magazine.toCharArray();
Arrays.sort(ma);
int index = 0;
boolean found = true;
for (int i = 0; i < ra.length && ret; i++) {
char ri = ra[i];
found = false;
for (int j = index; j < ma.length; j++) {
if (ma[j] > ri) {
ret = false;
break;
} else if (ma[j] == ri) {
index++;
found = true;
break;
} else {
index++;
}
}
if (!found) {
ret = false;
break;
}
}
return ret;
}
解法三:
public boolean canConstruct(String ransomNote, String magazine) {
int[] arr = new int[26];
for (int i = 0; i < magazine.length(); i++) {
arr[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if(--arr[ransomNote.charAt(i)-'a'] < 0) {
return false;
}
}
return true;
}
### 后记
练习源码地址:[https://github.com/Zering/LeetCode](https://github.com/Zering/LeetCode) | Zering/Zering.github.io | _posts/2016-09-13-Ransom-Note.md | Markdown | apache-2.0 | 4,398 |
package com.yuzhou.viewer.service;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.google.common.eventbus.EventBus;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.yuzhou.viewer.R;
import com.yuzhou.viewer.model.GoogleImage;
import com.yuzhou.viewer.model.GoogleImageFactory;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuzhou on 2015/08/02.
*/
public class GoogleApiTask extends AsyncTask<ApiParam, Integer, List<GoogleImage>>
{
private final SyncHttpClient client = new SyncHttpClient();
private final List<GoogleImage> items = new ArrayList<>();
private final EventBus eventBus;
private final Context context;
private int errorResource;
public GoogleApiTask(EventBus eventBus, Context context)
{
this.eventBus = eventBus;
this.context = context;
}
private List<GoogleImage> interExecute(ApiParam request)
{
Log.d("VIEWER", request.toString());
client.get(request.getUrl(), request.getParams(), new JsonHttpResponseHandler()
{
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject response)
{
Log.i("VIEWER", "status code=" + statusCode + ", response=" + response + ", error=" + throwable.getMessage());
errorResource = R.string.error_unavailable_network;
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
if (response == null) {
Log.i("VIEWER", "Response no context");
errorResource = R.string.error_server_side;
return;
}
try {
int httpCode = response.getInt("responseStatus");
if (httpCode == 400) {
errorResource = R.string.error_data_not_found;
Log.d("VIEWER", "response=" + response.getString("responseDetails"));
return;
}
if (httpCode != 200) {
errorResource = R.string.error_server_side;
Log.d("VIEWER", "response=" + response.getString("responseDetails"));
return;
}
List<GoogleImage> images = GoogleImageFactory.create(response);
if (images.isEmpty()) {
Log.i("VIEWER", "Can not parse JSON");
Log.d("VIEWER", "response=" + response.toString());
errorResource = R.string.error_server_side;
return;
}
items.addAll(images);
} catch (JSONException e) {
Log.i("VIEWER", "Can not parse JSON");
e.printStackTrace();
}
}
});
return items;
}
@Override
protected List<GoogleImage> doInBackground(ApiParam... requests)
{
ApiParam request = requests[0];
return interExecute(request);
}
@Override
protected void onPreExecute()
{
items.clear();
}
@Override
protected void onPostExecute(List<GoogleImage> googleImages)
{
if (errorResource > 0) {
Toast.makeText(context, errorResource, Toast.LENGTH_LONG).show();
}
eventBus.post(items);
}
} | yuzhou2/android_02_grid_image_search | app/src/main/java/com/yuzhou/viewer/service/GoogleApiTask.java | Java | apache-2.0 | 3,730 |
<?php
/**
* Smarty Internal Plugin Compile Insert
*
* Compiles the {insert} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Insert Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Insert extends Smarty_Internal_CompileBase {
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('_any');
/**
* Compiles code for the {insert} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
*
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
// never compile as nocache code
$compiler->suppressNocacheProcessing = true;
$compiler->tag_nocache = true;
$_smarty_tpl = $compiler->template;
$_name = null;
$_script = null;
$_output = '<?php ';
// save posible attributes
eval('$_name = ' . $_attr['name'] . ';');
if (isset($_attr['assign']))
{
// output will be stored in a smarty variable instead of being displayed
$_assign = $_attr['assign'];
// create variable to make shure that the compiler knows about its nocache status
$compiler->template->tpl_vars[trim($_attr['assign'], "'")] = new Smarty_Variable(null, true);
}
if (isset($_attr['script']))
{
// script which must be included
$_function = "smarty_insert_{$_name}";
$_smarty_tpl = $compiler->template;
$_filepath = false;
eval('$_script = ' . $_attr['script'] . ';');
if (!isset($compiler->smarty->security_policy) && file_exists($_script))
{
$_filepath = $_script;
}
else
{
if (isset($compiler->smarty->security_policy))
{
$_dir = $compiler->smarty->security_policy->trusted_dir;
}
else
{
$_dir = $compiler->smarty->trusted_dir;
}
if (!empty($_dir))
{
foreach ((array)$_dir as $_script_dir)
{
$_script_dir = rtrim($_script_dir, '/\\') . DS;
if (file_exists($_script_dir . $_script))
{
$_filepath = $_script_dir . $_script;
break;
}
}
}
}
if ($_filepath == false)
{
$compiler->trigger_template_error("{insert} missing script file '{$_script}'", $compiler->lex->taglineno);
}
// code for script file loading
$_output .= "require_once '{$_filepath}' ;";
require_once $_filepath;
if (!is_callable($_function))
{
$compiler->trigger_template_error(" {insert} function '{$_function}' is not callable in script file '{$_script}'", $compiler->lex->taglineno);
}
}
else
{
$_filepath = 'null';
$_function = "insert_{$_name}";
// function in PHP script ?
if (!is_callable($_function))
{
// try plugin
if (!$_function = $compiler->getPlugin($_name, 'insert'))
{
$compiler->trigger_template_error("{insert} no function or plugin found for '{$_name}'", $compiler->lex->taglineno);
}
}
}
// delete {insert} standard attributes
unset($_attr['name'], $_attr['assign'], $_attr['script'], $_attr['nocache']);
// convert attributes into parameter array string
$_paramsArray = array();
foreach ($_attr as $_key => $_value)
{
$_paramsArray[] = "'$_key' => $_value";
}
$_params = 'array(' . implode(", ", $_paramsArray) . ')';
// call insert
if (isset($_assign))
{
if ($_smarty_tpl->caching)
{
$_output .= "echo Smarty_Internal_Nocache_Insert::compile ('{$_function}',{$_params}, \$_smarty_tpl, '{$_filepath}',{$_assign});?>";
}
else
{
$_output .= "\$_smarty_tpl->assign({$_assign} , {$_function} ({$_params},\$_smarty_tpl), true);?>";
}
}
else
{
$compiler->has_output = true;
if ($_smarty_tpl->caching)
{
$_output .= "echo Smarty_Internal_Nocache_Insert::compile ('{$_function}',{$_params}, \$_smarty_tpl, '{$_filepath}');?>";
}
else
{
$_output .= "echo {$_function}({$_params},\$_smarty_tpl);?>";
}
}
return $_output;
}
}
?>
| slayerhover/yaf-cms-backoffice | library/Smarty/sysplugins/smarty_internal_compile_insert.php | PHP | apache-2.0 | 4,415 |
ChromeTabDisguise
=================
A simple tool to disguise Chrome Tab's favicon and title.
| jromer94/ChromeTabDisguise | README.md | Markdown | apache-2.0 | 95 |
package com.rockhoppertech.music.fx.cmn;
/*
* #%L
* rockymusic-fx
* %%
* Copyright (C) 1996 - 2013 Rockhopper Technologies
* %%
* 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.
* #L%
*/
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.SceneBuilder;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <a href="http://genedelisa.com/">Gene De Lisa</a>
*
*/
public class GrandStaffApp extends Application {
private static final Logger logger = LoggerFactory
.getLogger(GrandStaffApp.class);
private Stage stage;
private Scene scene;
private Pane root;
private GrandStaffAppController controller;
public static void main(String[] args) throws Exception {
launch(args);
}
void loadRootFxml() {
String fxmlFile = "/fxml/GrandStaffPanel.fxml";
logger.debug("Loading FXML for main view from: {}", fxmlFile);
try {
FXMLLoader loader = new FXMLLoader(
GrandStaffApp.class.getResource(fxmlFile));
root = (AnchorPane) loader.load();
controller = loader.getController();
} catch (IOException e) {
logger.error(e.getLocalizedMessage(),e);
}
}
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
// this.staffModel = new StaffModel();
// MIDITrack track = MIDITrackBuilder
// .create()
// .noteString(
// "E5 F G Ab G# A B C C6 D Eb F# G A B C7 B4 Bf4 A4 Af4")
// .durations(5, 4, 3, 2, 1, 1.5, .5, .75, .25, .25)
// .sequential()
// .build();
// this.staffModel.setTrack(track);
loadRootFxml();
this.scene = SceneBuilder.create()
.root(root)
.fill(Color.web("#1030F0"))
.stylesheets("/styles/grandStaffApp.css")
.build();
this.configureStage();
logger.debug("started");
}
private void configureStage() {
stage.setTitle("Music Notation");
// fullScreen();
stage.setScene(this.scene);
stage.show();
}
private void fullScreen() {
// make it full screen
stage.setX(0);
stage.setY(0);
stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());
stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());
}
}
| genedelisa/rockymusic | rockymusic-fx/src/main/java/com/rockhoppertech/music/fx/cmn/GrandStaffApp.java | Java | apache-2.0 | 3,230 |
function htmlEncode(value){
return $('<div/>').text(value).html();
}
var app = angular.module("oasassets",[]).controller("snippetsController",function($scope){
$scope.snippet = function(item){
var elem = $("#"+item);
var contents = elem.html().trim();
elem.html(htmlEncode(contents));
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
};
$scope.loadMenu = function(){
$('#side-menu').metisMenu();
};
});
| bizoru/assets-oas | js/app.js | JavaScript | apache-2.0 | 510 |
package org.tuxdevelop.spring.batch.lightmin.server.cluster.configuration;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@Data
@ConfigurationProperties(prefix = "spring.batch.lightmin.server.cluster.infinispan")
public class InfinispanServerClusterConfigurationProperties {
@NestedConfigurationProperty
private RepositoryConfigurationProperties repository = new RepositoryConfigurationProperties();
@Data
static class RepositoryConfigurationProperties {
private Boolean initSchedulerExecutionRepository = Boolean.FALSE;
private Boolean initSchedulerConfigurationRepository = Boolean.FALSE;
}
}
| tuxdevelop/spring-batch-lightmin | spring-batch-lightmin-server/spring-batch-lightmin-server-cluster/spring-batch-lightmin-server-cluster-infinispan/src/main/java/org/tuxdevelop/spring/batch/lightmin/server/cluster/configuration/InfinispanServerClusterConfigurationProperties.java | Java | apache-2.0 | 765 |
<?php
$this->Nm_lang_conf_region = array();
$this->Nm_lang_conf_region['en_us;en_us'] = "English (United States)";
$this->Nm_lang_conf_region['es;es_es'] = "Spanish (Spain)";
$this->Nm_lang_conf_region['pt_br;pt_br'] = "Portuguese (Brazil)";
ksort($this->Nm_lang_conf_region);
?> | oprohonnyi/php_trn | 5_dev_tools/scriptcase/PHPTrn/_lib/lang/lang_config_region.php | PHP | apache-2.0 | 289 |
<?php
/************************
Example Client App for inserting categories
*************************/
// Make sure we're being called from the command line, not a web interface
if (PHP_SAPI !== 'cli')
{
die('This is a command line only application.');
}
// We are a valid entry point.
const _JEXEC = 1;
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', 1);
// Load system defines
if (file_exists(dirname(__DIR__) . '/defines.php'))
{
require_once dirname(__DIR__) . '/defines.php';
}
if (!defined('_JDEFINES'))
{
define('JPATH_BASE', dirname(__DIR__));
require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_LIBRARIES . '/import.legacy.php';
require_once JPATH_LIBRARIES . '/cms.php';
// Load the configuration
require_once JPATH_CONFIGURATION . '/configuration.php';
// ----------------------
class InsertCatExampleCli extends JApplicationCli {
public function __construct() {
parent::__construct();
$this->config = new JConfig();
$this->dbo = JDatabase::getInstance(
array(
'driver' => $this->config->dbtype,
'host' => $this->config->host,
'user' => $this->config->user,
'password' => $this->config->password,
'database' => $this->config->db,
'prefix' => $this->config->dbprefix,
)
);
// important for storing several rows
JFactory::$application = $this;
}
public function doExecute() {
$category_titles = array("Test Title 1", "Test Title 2", "Test Title 3");
// add categories to database
for ($i=0; $i<count($category_titles); $i++) {
$this->insertCategory($category_titles[$i]);
}
}
private function insertCategory($cat_title) {
$tbl_cat = JTable::getInstance("Category");
// get existing aliases from categories table
$tab = $this->dbo->quoteName($this->config->dbprefix . "categories");
$conditions = array(
$this->dbo->quoteName("extension") . " LIKE 'com_content'"
);
$query = $this->dbo->getQuery(true);
$query
->select($this->dbo->quoteName("alias"))
->from($tab)
->where($conditions);
$this->dbo->setQuery($query);
$cat_from_db = $this->dbo->loadObjectList();
$category_existing = False;
$new_cat_alias = JFilterOutput::stringURLSafe($cat_title);
foreach ($cat_from_db as $cdb) {
if ($cdb->alias == $new_cat_alias) {
$category_existing = True;
echo "category already existing: " . $new_cat_alias . "\n";
}
}
// ----------------
if (!$category_existing) {
$values = [
"id" => null,
"title" => $cat_title,
"path" => $new_cat_alias,
"access" => 1,
"extension" => "com_content",
"published" => 1,
"language" => "*",
"created_user_id" => 0,
"params" => array (
"category_layout" => "",
"image" => "",
),
"metadata" => array (
"author" => "",
"robots" => "",
),
];
$tbl_cat->setLocation(1, "last-child");
if (!$tbl_cat->bind($values)) {
JError::raiseWarning(500, $row->getError());
return FALSE;
}
if (!$tbl_cat->check()) {
JError::raiseError(500, $article->getError());
return FALSE;
}
if (!$tbl_cat->store(TRUE)) {
JError::raiseError(500, $article->getError());
return FALSE;
}
$tbl_cat->rebuildPath($tbl_cat->id);
echo "category inserted: " . $tbl_cat->id . " - " . $new_cat_alias . "\n";
}
}
}
try {
JApplicationCli::getInstance('InsertCatExampleCli')->execute();
}
catch (Exception $e) {
// An exception has been caught, just echo the message.
fwrite(STDOUT, $e->getMessage() . "\n");
exit($e->getCode());
}
?>
| stoffels-it/joomla-extensions-examples | insert-cat-example.php | PHP | apache-2.0 | 4,296 |
# Annotations
You can add these Kubernetes annotations to specific Ingress objects to customize their behavior.
!!! tip
Annotation keys and values can only be strings.
Other types, such as boolean or numeric values must be quoted,
i.e. `"true"`, `"false"`, `"100"`.
!!! note
The annotation prefix can be changed using the
[`--annotations-prefix` command line argument](../cli-arguments.md),
but the default is `nginx.ingress.kubernetes.io`, as described in the
table below.
|Name | type |
|---------------------------|------|
|[nginx.ingress.kubernetes.io/app-root](#rewrite)|string|
|[nginx.ingress.kubernetes.io/affinity](#session-affinity)|cookie|
|[nginx.ingress.kubernetes.io/affinity-mode](#session-affinity)|"balanced" or "persistent"|
|[nginx.ingress.kubernetes.io/affinity-canary-behavior](#session-affinity)|"sticky" or "legacy"|
|[nginx.ingress.kubernetes.io/auth-realm](#authentication)|string|
|[nginx.ingress.kubernetes.io/auth-secret](#authentication)|string|
|[nginx.ingress.kubernetes.io/auth-secret-type](#authentication)|string|
|[nginx.ingress.kubernetes.io/auth-type](#authentication)|basic or digest|
|[nginx.ingress.kubernetes.io/auth-tls-secret](#client-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-tls-verify-depth](#client-certificate-authentication)|number|
|[nginx.ingress.kubernetes.io/auth-tls-verify-client](#client-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-tls-error-page](#client-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-tls-pass-certificate-to-upstream](#client-certificate-authentication)|"true" or "false"|
|[nginx.ingress.kubernetes.io/auth-url](#external-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-cache-key](#external-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-cache-duration](#external-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-proxy-set-headers](#external-authentication)|string|
|[nginx.ingress.kubernetes.io/auth-snippet](#external-authentication)|string|
|[nginx.ingress.kubernetes.io/enable-global-auth](#external-authentication)|"true" or "false"|
|[nginx.ingress.kubernetes.io/backend-protocol](#backend-protocol)|string|HTTP,HTTPS,GRPC,GRPCS,AJP|
|[nginx.ingress.kubernetes.io/canary](#canary)|"true" or "false"|
|[nginx.ingress.kubernetes.io/canary-by-header](#canary)|string|
|[nginx.ingress.kubernetes.io/canary-by-header-value](#canary)|string|
|[nginx.ingress.kubernetes.io/canary-by-header-pattern](#canary)|string|
|[nginx.ingress.kubernetes.io/canary-by-cookie](#canary)|string|
|[nginx.ingress.kubernetes.io/canary-weight](#canary)|number|
|[nginx.ingress.kubernetes.io/client-body-buffer-size](#client-body-buffer-size)|string|
|[nginx.ingress.kubernetes.io/configuration-snippet](#configuration-snippet)|string|
|[nginx.ingress.kubernetes.io/custom-http-errors](#custom-http-errors)|[]int|
|[nginx.ingress.kubernetes.io/default-backend](#default-backend)|string|
|[nginx.ingress.kubernetes.io/enable-cors](#enable-cors)|"true" or "false"|
|[nginx.ingress.kubernetes.io/cors-allow-origin](#enable-cors)|string|
|[nginx.ingress.kubernetes.io/cors-allow-methods](#enable-cors)|string|
|[nginx.ingress.kubernetes.io/cors-allow-headers](#enable-cors)|string|
|[nginx.ingress.kubernetes.io/cors-expose-headers](#enable-cors)|string|
|[nginx.ingress.kubernetes.io/cors-allow-credentials](#enable-cors)|"true" or "false"|
|[nginx.ingress.kubernetes.io/cors-max-age](#enable-cors)|number|
|[nginx.ingress.kubernetes.io/force-ssl-redirect](#server-side-https-enforcement-through-redirect)|"true" or "false"|
|[nginx.ingress.kubernetes.io/from-to-www-redirect](#redirect-fromto-www)|"true" or "false"|
|[nginx.ingress.kubernetes.io/http2-push-preload](#http2-push-preload)|"true" or "false"|
|[nginx.ingress.kubernetes.io/limit-connections](#rate-limiting)|number|
|[nginx.ingress.kubernetes.io/limit-rps](#rate-limiting)|number|
|[nginx.ingress.kubernetes.io/global-rate-limit](#global-rate-limiting)|number|
|[nginx.ingress.kubernetes.io/global-rate-limit-window](#global-rate-limiting)|duration|
|[nginx.ingress.kubernetes.io/global-rate-limit-key](#global-rate-limiting)|string|
|[nginx.ingress.kubernetes.io/global-rate-limit-ignored-cidrs](#global-rate-limiting)|string|
|[nginx.ingress.kubernetes.io/permanent-redirect](#permanent-redirect)|string|
|[nginx.ingress.kubernetes.io/permanent-redirect-code](#permanent-redirect-code)|number|
|[nginx.ingress.kubernetes.io/temporal-redirect](#temporal-redirect)|string|
|[nginx.ingress.kubernetes.io/preserve-trailing-slash](#server-side-https-enforcement-through-redirect)|"true" or "false"|
|[nginx.ingress.kubernetes.io/proxy-body-size](#custom-max-body-size)|string|
|[nginx.ingress.kubernetes.io/proxy-cookie-domain](#proxy-cookie-domain)|string|
|[nginx.ingress.kubernetes.io/proxy-cookie-path](#proxy-cookie-path)|string|
|[nginx.ingress.kubernetes.io/proxy-connect-timeout](#custom-timeouts)|number|
|[nginx.ingress.kubernetes.io/proxy-send-timeout](#custom-timeouts)|number|
|[nginx.ingress.kubernetes.io/proxy-read-timeout](#custom-timeouts)|number|
|[nginx.ingress.kubernetes.io/proxy-next-upstream](#custom-timeouts)|string|
|[nginx.ingress.kubernetes.io/proxy-next-upstream-timeout](#custom-timeouts)|number|
|[nginx.ingress.kubernetes.io/proxy-next-upstream-tries](#custom-timeouts)|number|
|[nginx.ingress.kubernetes.io/proxy-request-buffering](#custom-timeouts)|string|
|[nginx.ingress.kubernetes.io/proxy-redirect-from](#proxy-redirect)|string|
|[nginx.ingress.kubernetes.io/proxy-redirect-to](#proxy-redirect)|string|
|[nginx.ingress.kubernetes.io/proxy-http-version](#proxy-http-version)|"1.0" or "1.1"|
|[nginx.ingress.kubernetes.io/proxy-ssl-secret](#backend-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/proxy-ssl-ciphers](#backend-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/proxy-ssl-name](#backend-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/proxy-ssl-protocols](#backend-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/proxy-ssl-verify](#backend-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/proxy-ssl-verify-depth](#backend-certificate-authentication)|number|
|[nginx.ingress.kubernetes.io/proxy-ssl-server-name](#backend-certificate-authentication)|string|
|[nginx.ingress.kubernetes.io/enable-rewrite-log](#enable-rewrite-log)|"true" or "false"|
|[nginx.ingress.kubernetes.io/rewrite-target](#rewrite)|URI|
|[nginx.ingress.kubernetes.io/satisfy](#satisfy)|string|
|[nginx.ingress.kubernetes.io/server-alias](#server-alias)|string|
|[nginx.ingress.kubernetes.io/server-snippet](#server-snippet)|string|
|[nginx.ingress.kubernetes.io/service-upstream](#service-upstream)|"true" or "false"|
|[nginx.ingress.kubernetes.io/session-cookie-name](#cookie-affinity)|string|
|[nginx.ingress.kubernetes.io/session-cookie-path](#cookie-affinity)|string|
|[nginx.ingress.kubernetes.io/session-cookie-change-on-failure](#cookie-affinity)|"true" or "false"|
|[nginx.ingress.kubernetes.io/session-cookie-samesite](#cookie-affinity)|string|
|[nginx.ingress.kubernetes.io/session-cookie-conditional-samesite-none](#cookie-affinity)|"true" or "false"|
|[nginx.ingress.kubernetes.io/ssl-redirect](#server-side-https-enforcement-through-redirect)|"true" or "false"|
|[nginx.ingress.kubernetes.io/ssl-passthrough](#ssl-passthrough)|"true" or "false"|
|[nginx.ingress.kubernetes.io/upstream-hash-by](#custom-nginx-upstream-hashing)|string|
|[nginx.ingress.kubernetes.io/x-forwarded-prefix](#x-forwarded-prefix-header)|string|
|[nginx.ingress.kubernetes.io/load-balance](#custom-nginx-load-balancing)|string|
|[nginx.ingress.kubernetes.io/upstream-vhost](#custom-nginx-upstream-vhost)|string|
|[nginx.ingress.kubernetes.io/whitelist-source-range](#whitelist-source-range)|CIDR|
|[nginx.ingress.kubernetes.io/proxy-buffering](#proxy-buffering)|string|
|[nginx.ingress.kubernetes.io/proxy-buffers-number](#proxy-buffers-number)|number|
|[nginx.ingress.kubernetes.io/proxy-buffer-size](#proxy-buffer-size)|string|
|[nginx.ingress.kubernetes.io/proxy-max-temp-file-size](#proxy-max-temp-file-size)|string|
|[nginx.ingress.kubernetes.io/ssl-ciphers](#ssl-ciphers)|string|
|[nginx.ingress.kubernetes.io/ssl-prefer-server-ciphers](#ssl-ciphers)|"true" or "false"|
|[nginx.ingress.kubernetes.io/connection-proxy-header](#connection-proxy-header)|string|
|[nginx.ingress.kubernetes.io/enable-access-log](#enable-access-log)|"true" or "false"|
|[nginx.ingress.kubernetes.io/enable-opentracing](#enable-opentracing)|"true" or "false"|
|[nginx.ingress.kubernetes.io/opentracing-trust-incoming-span](#opentracing-trust-incoming-span)|"true" or "false"|
|[nginx.ingress.kubernetes.io/enable-influxdb](#influxdb)|"true" or "false"|
|[nginx.ingress.kubernetes.io/influxdb-measurement](#influxdb)|string|
|[nginx.ingress.kubernetes.io/influxdb-port](#influxdb)|string|
|[nginx.ingress.kubernetes.io/influxdb-host](#influxdb)|string|
|[nginx.ingress.kubernetes.io/influxdb-server-name](#influxdb)|string|
|[nginx.ingress.kubernetes.io/use-regex](#use-regex)|bool|
|[nginx.ingress.kubernetes.io/enable-modsecurity](#modsecurity)|bool|
|[nginx.ingress.kubernetes.io/enable-owasp-core-rules](#modsecurity)|bool|
|[nginx.ingress.kubernetes.io/modsecurity-transaction-id](#modsecurity)|string|
|[nginx.ingress.kubernetes.io/modsecurity-snippet](#modsecurity)|string|
|[nginx.ingress.kubernetes.io/mirror-request-body](#mirror)|string|
|[nginx.ingress.kubernetes.io/mirror-target](#mirror)|string|
### Canary
In some cases, you may want to "canary" a new set of changes by sending a small number of requests to a different service than the production service. The canary annotation enables the Ingress spec to act as an alternative service for requests to route to depending on the rules applied. The following annotations to configure canary can be enabled after `nginx.ingress.kubernetes.io/canary: "true"` is set:
* `nginx.ingress.kubernetes.io/canary-by-header`: The header to use for notifying the Ingress to route the request to the service specified in the Canary Ingress. When the request header is set to `always`, it will be routed to the canary. When the header is set to `never`, it will never be routed to the canary. For any other value, the header will be ignored and the request compared against the other canary rules by precedence.
* `nginx.ingress.kubernetes.io/canary-by-header-value`: The header value to match for notifying the Ingress to route the request to the service specified in the Canary Ingress. When the request header is set to this value, it will be routed to the canary. For any other header value, the header will be ignored and the request compared against the other canary rules by precedence. This annotation has to be used together with . The annotation is an extension of the `nginx.ingress.kubernetes.io/canary-by-header` to allow customizing the header value instead of using hardcoded values. It doesn't have any effect if the `nginx.ingress.kubernetes.io/canary-by-header` annotation is not defined.
* `nginx.ingress.kubernetes.io/canary-by-header-pattern`: This works the same way as `canary-by-header-value` except it does PCRE Regex matching. Note that when `canary-by-header-value` is set this annotation will be ignored. When the given Regex causes error during request processing, the request will be considered as not matching.
* `nginx.ingress.kubernetes.io/canary-by-cookie`: The cookie to use for notifying the Ingress to route the request to the service specified in the Canary Ingress. When the cookie value is set to `always`, it will be routed to the canary. When the cookie is set to `never`, it will never be routed to the canary. For any other value, the cookie will be ignored and the request compared against the other canary rules by precedence.
* `nginx.ingress.kubernetes.io/canary-weight`: The integer based (0 - 100) percent of random requests that should be routed to the service specified in the canary Ingress. A weight of 0 implies that no requests will be sent to the service in the Canary ingress by this canary rule. A weight of 100 means implies all requests will be sent to the alternative service specified in the Ingress.
Canary rules are evaluated in order of precedence. Precedence is as follows:
`canary-by-header -> canary-by-cookie -> canary-weight`
**Note** that when you mark an ingress as canary, then all the other non-canary annotations will be ignored (inherited from the corresponding main ingress) except `nginx.ingress.kubernetes.io/load-balance`, `nginx.ingress.kubernetes.io/upstream-hash-by`, and [annotations related to session affinity](#session-affinity). If you want to restore the original behavior of canaries when session affinity was ignored, set `nginx.ingress.kubernetes.io/affinity-canary-behavior` annotation with value `legacy` on the canary ingress definition.
**Known Limitations**
Currently a maximum of one canary ingress can be applied per Ingress rule.
### Rewrite
In some scenarios the exposed URL in the backend service differs from the specified path in the Ingress rule. Without a rewrite any request will return 404.
Set the annotation `nginx.ingress.kubernetes.io/rewrite-target` to the path expected by the service.
If the Application Root is exposed in a different path and needs to be redirected, set the annotation `nginx.ingress.kubernetes.io/app-root` to redirect requests for `/`.
!!! example
Please check the [rewrite](../../examples/rewrite/README.md) example.
### Session Affinity
The annotation `nginx.ingress.kubernetes.io/affinity` enables and sets the affinity type in all Upstreams of an Ingress. This way, a request will always be directed to the same upstream server.
The only affinity type available for NGINX is `cookie`.
The annotation `nginx.ingress.kubernetes.io/affinity-mode` defines the stickiness of a session. Setting this to `balanced` (default) will redistribute some sessions if a deployment gets scaled up, therefore rebalancing the load on the servers. Setting this to `persistent` will not rebalance sessions to new servers, therefore providing maximum stickiness.
The annotation `nginx.ingress.kubernetes.io/affinity-canary-behavior` defines the behavior of canaries when session affinity is enabled. Setting this to `sticky` (default) will ensure that users that were served by canaries, will continue to be served by canaries. Setting this to `legacy` will restore original canary behavior, when session affinity was ignored.
!!! attention
If more than one Ingress is defined for a host and at least one Ingress uses `nginx.ingress.kubernetes.io/affinity: cookie`, then only paths on the Ingress using `nginx.ingress.kubernetes.io/affinity` will use session cookie affinity. All paths defined on other Ingresses for the host will be load balanced through the random selection of a backend server.
!!! example
Please check the [affinity](../../examples/affinity/cookie/README.md) example.
#### Cookie affinity
If you use the ``cookie`` affinity type you can also specify the name of the cookie that will be used to route the requests with the annotation `nginx.ingress.kubernetes.io/session-cookie-name`. The default is to create a cookie named 'INGRESSCOOKIE'.
The NGINX annotation `nginx.ingress.kubernetes.io/session-cookie-path` defines the path that will be set on the cookie. This is optional unless the annotation `nginx.ingress.kubernetes.io/use-regex` is set to true; Session cookie paths do not support regex.
Use `nginx.ingress.kubernetes.io/session-cookie-samesite` to apply a `SameSite` attribute to the sticky cookie. Browser accepted values are `None`, `Lax`, and `Strict`. Some browsers reject cookies with `SameSite=None`, including those created before the `SameSite=None` specification (e.g. Chrome 5X). Other browsers mistakenly treat `SameSite=None` cookies as `SameSite=Strict` (e.g. Safari running on OSX 14). To omit `SameSite=None` from browsers with these incompatibilities, add the annotation `nginx.ingress.kubernetes.io/session-cookie-conditional-samesite-none: "true"`.
### Authentication
It is possible to add authentication by adding additional annotations in the Ingress rule. The source of the authentication is a secret that contains usernames and passwords.
The annotations are:
```
nginx.ingress.kubernetes.io/auth-type: [basic|digest]
```
Indicates the [HTTP Authentication Type: Basic or Digest Access Authentication](https://tools.ietf.org/html/rfc2617).
```
nginx.ingress.kubernetes.io/auth-secret: secretName
```
The name of the Secret that contains the usernames and passwords which are granted access to the `path`s defined in the Ingress rules.
This annotation also accepts the alternative form "namespace/secretName", in which case the Secret lookup is performed in the referenced namespace instead of the Ingress namespace.
```
nginx.ingress.kubernetes.io/auth-secret-type: [auth-file|auth-map]
```
The `auth-secret` can have two forms:
- `auth-file` - default, an htpasswd file in the key `auth` within the secret
- `auth-map` - the keys of the secret are the usernames, and the values are the hashed passwords
```
nginx.ingress.kubernetes.io/auth-realm: "realm string"
```
!!! example
Please check the [auth](../../examples/auth/basic/README.md) example.
### Custom NGINX upstream hashing
NGINX supports load balancing by client-server mapping based on [consistent hashing](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#hash) for a given key. The key can contain text, variables or any combination thereof. This feature allows for request stickiness other than client IP or cookies. The [ketama](https://www.last.fm/user/RJ/journal/2007/04/10/rz_libketama_-_a_consistent_hashing_algo_for_memcache_clients) consistent hashing method will be used which ensures only a few keys would be remapped to different servers on upstream group changes.
There is a special mode of upstream hashing called subset. In this mode, upstream servers are grouped into subsets, and stickiness works by mapping keys to a subset instead of individual upstream servers. Specific server is chosen uniformly at random from the selected sticky subset. It provides a balance between stickiness and load distribution.
To enable consistent hashing for a backend:
`nginx.ingress.kubernetes.io/upstream-hash-by`: the nginx variable, text value or any combination thereof to use for consistent hashing. For example: `nginx.ingress.kubernetes.io/upstream-hash-by: "$request_uri"` or `nginx.ingress.kubernetes.io/upstream-hash-by: "$request_uri$host"` or `nginx.ingress.kubernetes.io/upstream-hash-by: "${request_uri}-text-value"` to consistently hash upstream requests by the current request URI.
"subset" hashing can be enabled setting `nginx.ingress.kubernetes.io/upstream-hash-by-subset`: "true". This maps requests to subset of nodes instead of a single one. `upstream-hash-by-subset-size` determines the size of each subset (default 3).
Please check the [chashsubset](../../examples/chashsubset/deployment.yaml) example.
### Custom NGINX load balancing
This is similar to [`load-balance` in ConfigMap](./configmap.md#load-balance), but configures load balancing algorithm per ingress.
>Note that `nginx.ingress.kubernetes.io/upstream-hash-by` takes preference over this. If this and `nginx.ingress.kubernetes.io/upstream-hash-by` are not set then we fallback to using globally configured load balancing algorithm.
### Custom NGINX upstream vhost
This configuration setting allows you to control the value for host in the following statement: `proxy_set_header Host $host`, which forms part of the location block. This is useful if you need to call the upstream server by something other than `$host`.
### Client Certificate Authentication
It is possible to enable Client Certificate Authentication using additional annotations in Ingress Rule.
Client Certificate Authentication is applied per host and it is not possible to specify rules that differ for individual paths.
To enable, add the annotation `nginx.ingress.kubernetes.io/auth-tls-secret: namespace/secretName`. This secret must have a file named `ca.crt` containing the full Certificate Authority chain `ca.crt` that is enabled to authenticate against this Ingress.
You can further customize client certificate authentication and behaviour with these annotations:
* `nginx.ingress.kubernetes.io/auth-tls-verify-depth`: The validation depth between the provided client certificate and the Certification Authority chain. (default: 1)
* `nginx.ingress.kubernetes.io/auth-tls-verify-client`: Enables verification of client certificates. Possible values are:
* `on`: Request a client certificate that must be signed by a certificate that is included in the secret key `ca.crt` of the secret specified by `nginx.ingress.kubernetes.io/auth-tls-secret: namespace/secretName`. Failed certificate verification will result in a status code 400 (Bad Request) (default)
* `off`: Don't request client certificates and don't do client certificate verification.
* `optional`: Do optional client certificate validation against the CAs from `auth-tls-secret`. The request fails with status code 400 (Bad Request) when a certificate is provided that is not signed by the CA. When no or an otherwise invalid certificate is provided, the request does not fail, but instead the verification result is sent to the upstream service.
* `optional_no_ca`: Do optional client certificate validation, but do not fail the request when the client certificate is not signed by the CAs from `auth-tls-secret`. Certificate verification result is sent to the upstream service.
* `nginx.ingress.kubernetes.io/auth-tls-error-page`: The URL/Page that user should be redirected in case of a Certificate Authentication Error
* `nginx.ingress.kubernetes.io/auth-tls-pass-certificate-to-upstream`: Indicates if the received certificates should be passed or not to the upstream server in the header `ssl-client-cert`. Possible values are "true" or "false" (default).
The following headers are sent to the upstream service according to the `auth-tls-*` annotations:
* `ssl-client-issuer-dn`: The issuer information of the client certificate. Example: "CN=My CA"
* `ssl-client-subject-dn`: The subject information of the client certificate. Example: "CN=My Client"
* `ssl-client-verify`: The result of the client verification. Possible values: "SUCCESS", "FAILED: <description, why the verification failed>"
* `ssl-client-cert`: The full client certificate in PEM format. Will only be sent when `nginx.ingress.kubernetes.io/auth-tls-pass-certificate-to-upstream` is set to "true". Example: `-----BEGIN%20CERTIFICATE-----%0A...---END%20CERTIFICATE-----%0A`
!!! example
Please check the [client-certs](../../examples/auth/client-certs/README.md) example.
!!! attention
TLS with Client Authentication is **not** possible in Cloudflare and might result in unexpected behavior.
Cloudflare only allows Authenticated Origin Pulls and is required to use their own certificate: [https://blog.cloudflare.com/protecting-the-origin-with-tls-authenticated-origin-pulls/](https://blog.cloudflare.com/protecting-the-origin-with-tls-authenticated-origin-pulls/)
Only Authenticated Origin Pulls are allowed and can be configured by following their tutorial: [https://support.cloudflare.com/hc/en-us/articles/204494148-Setting-up-NGINX-to-use-TLS-Authenticated-Origin-Pulls](https://support.cloudflare.com/hc/en-us/articles/204494148-Setting-up-NGINX-to-use-TLS-Authenticated-Origin-Pulls)
### Backend Certificate Authentication
It is possible to authenticate to a proxied HTTPS backend with certificate using additional annotations in Ingress Rule.
* `nginx.ingress.kubernetes.io/proxy-ssl-secret: secretName`:
Specifies a Secret with the certificate `tls.crt`, key `tls.key` in PEM format used for authentication to a proxied HTTPS server. It should also contain trusted CA certificates `ca.crt` in PEM format used to verify the certificate of the proxied HTTPS server.
This annotation expects the Secret name in the form "namespace/secretName".
* `nginx.ingress.kubernetes.io/proxy-ssl-verify`:
Enables or disables verification of the proxied HTTPS server certificate. (default: off)
* `nginx.ingress.kubernetes.io/proxy-ssl-verify-depth`:
Sets the verification depth in the proxied HTTPS server certificates chain. (default: 1)
* `nginx.ingress.kubernetes.io/proxy-ssl-ciphers`:
Specifies the enabled [ciphers](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_ciphers) for requests to a proxied HTTPS server. The ciphers are specified in the format understood by the OpenSSL library.
* `nginx.ingress.kubernetes.io/proxy-ssl-name`:
Allows to set [proxy_ssl_name](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_name). This allows overriding the server name used to verify the certificate of the proxied HTTPS server. This value is also passed through SNI when a connection is established to the proxied HTTPS server.
* `nginx.ingress.kubernetes.io/proxy-ssl-protocols`:
Enables the specified [protocols](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_protocols) for requests to a proxied HTTPS server.
* `nginx.ingress.kubernetes.io/proxy-ssl-server-name`:
Enables passing of the server name through TLS Server Name Indication extension (SNI, RFC 6066) when establishing a connection with the proxied HTTPS server.
### Configuration snippet
Using this annotation you can add additional configuration to the NGINX location. For example:
```yaml
nginx.ingress.kubernetes.io/configuration-snippet: |
more_set_headers "Request-Id: $req_id";
```
Be aware this can be dangerous in multi-tenant clusters, as it can lead to people with otherwise limited permissions being able to retrieve all secrets on the cluster. The recommended mitigation for this threat is to disable this feature, so it may not work for you. See CVE-2021-25742 and the [related issue on github](https://github.com/kubernetes/ingress-nginx/issues/7837) for more information.
### Custom HTTP Errors
Like the [`custom-http-errors`](./configmap.md#custom-http-errors) value in the ConfigMap, this annotation will set NGINX `proxy-intercept-errors`, but only for the NGINX location associated with this ingress. If a [default backend annotation](#default-backend) is specified on the ingress, the errors will be routed to that annotation's default backend service (instead of the global default backend).
Different ingresses can specify different sets of error codes. Even if multiple ingress objects share the same hostname, this annotation can be used to intercept different error codes for each ingress (for example, different error codes to be intercepted for different paths on the same hostname, if each path is on a different ingress).
If `custom-http-errors` is also specified globally, the error values specified in this annotation will override the global value for the given ingress' hostname and path.
Example usage:
```
nginx.ingress.kubernetes.io/custom-http-errors: "404,415"
```
### Default Backend
This annotation is of the form `nginx.ingress.kubernetes.io/default-backend: <svc name>` to specify a custom default backend. This `<svc name>` is a reference to a service inside of the same namespace in which you are applying this annotation. This annotation overrides the global default backend. In case the service has [multiple ports](https://kubernetes.io/docs/concepts/services-networking/service/#multi-port-services), the first one is the one which will received the backend traffic.
This service will be used to handle the response when the configured service in the Ingress rule does not have any active endpoints. It will also be used to handle the error responses if both this annotation and the [custom-http-errors annotation](#custom-http-errors) are set.
### Enable CORS
To enable Cross-Origin Resource Sharing (CORS) in an Ingress rule, add the annotation
`nginx.ingress.kubernetes.io/enable-cors: "true"`. This will add a section in the server
location enabling this functionality.
CORS can be controlled with the following annotations:
* `nginx.ingress.kubernetes.io/cors-allow-methods`: Controls which methods are accepted.
This is a multi-valued field, separated by ',' and accepts only letters (upper and lower case).
- Default: `GET, PUT, POST, DELETE, PATCH, OPTIONS`
- Example: `nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS"`
* `nginx.ingress.kubernetes.io/cors-allow-headers`: Controls which headers are accepted.
This is a multi-valued field, separated by ',' and accepts letters, numbers, _ and -.
- Default: `DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization`
- Example: `nginx.ingress.kubernetes.io/cors-allow-headers: "X-Forwarded-For, X-app123-XPTO"`
* `nginx.ingress.kubernetes.io/cors-expose-headers`: Controls which headers are exposed to response.
This is a multi-valued field, separated by ',' and accepts letters, numbers, _, - and *.
- Default: *empty*
- Example: `nginx.ingress.kubernetes.io/cors-expose-headers: "*, X-CustomResponseHeader"`
* `nginx.ingress.kubernetes.io/cors-allow-origin`: Controls what's the accepted Origin for CORS.
This is a multi-valued field, separated by ','. It must follow this format: `http(s)://origin-site.com` or `http(s)://origin-site.com:port`
- Default: `*`
- Example: `nginx.ingress.kubernetes.io/cors-allow-origin: "https://origin-site.com:4443, http://origin-site.com, https://example.org:1199"`
It also supports single level wildcard subdomains and follows this format: `http(s)://*.foo.bar`, `http(s)://*.bar.foo:8080` or `http(s)://*.abc.bar.foo:9000`
- Example: `nginx.ingress.kubernetes.io/cors-allow-origin: "https://*.origin-site.com:4443, http://*.origin-site.com, https://example.org:1199"`
* `nginx.ingress.kubernetes.io/cors-allow-credentials`: Controls if credentials can be passed during CORS operations.
- Default: `true`
- Example: `nginx.ingress.kubernetes.io/cors-allow-credentials: "false"`
* `nginx.ingress.kubernetes.io/cors-max-age`: Controls how long preflight requests can be cached.
- Default: `1728000`
- Example: `nginx.ingress.kubernetes.io/cors-max-age: 600`
!!! note
For more information please see [https://enable-cors.org](https://enable-cors.org/server_nginx.html)
### HTTP2 Push Preload.
Enables automatic conversion of preload links specified in the “Link” response header fields into push requests.
!!! example
* `nginx.ingress.kubernetes.io/http2-push-preload: "true"`
### Server Alias
Allows the definition of one or more aliases in the server definition of the NGINX configuration using the annotation `nginx.ingress.kubernetes.io/server-alias: "<alias 1>,<alias 2>"`.
This will create a server with the same configuration, but adding new values to the `server_name` directive.
!!! note
A server-alias name cannot conflict with the hostname of an existing server. If it does, the server-alias annotation will be ignored.
If a server-alias is created and later a new server with the same hostname is created, the new server configuration will take
place over the alias configuration.
For more information please see [the `server_name` documentation](http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name).
### Server snippet
Using the annotation `nginx.ingress.kubernetes.io/server-snippet` it is possible to add custom configuration in the server configuration block.
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/server-snippet: |
set $agentflag 0;
if ($http_user_agent ~* "(Mobile)" ){
set $agentflag 1;
}
if ( $agentflag = 1 ) {
return 301 https://m.example.com;
}
```
!!! attention
This annotation can be used only once per host.
### Client Body Buffer Size
Sets buffer size for reading client request body per location. In case the request body is larger than the buffer,
the whole body or only its part is written to a temporary file. By default, buffer size is equal to two memory pages.
This is 8K on x86, other 32-bit platforms, and x86-64. It is usually 16K on other 64-bit platforms. This annotation is
applied to each location provided in the ingress rule.
!!! note
The annotation value must be given in a format understood by Nginx.
!!! example
* `nginx.ingress.kubernetes.io/client-body-buffer-size: "1000"` # 1000 bytes
* `nginx.ingress.kubernetes.io/client-body-buffer-size: 1k` # 1 kilobyte
* `nginx.ingress.kubernetes.io/client-body-buffer-size: 1K` # 1 kilobyte
* `nginx.ingress.kubernetes.io/client-body-buffer-size: 1m` # 1 megabyte
* `nginx.ingress.kubernetes.io/client-body-buffer-size: 1M` # 1 megabyte
For more information please see [http://nginx.org](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size)
### External Authentication
To use an existing service that provides authentication the Ingress rule can be annotated with `nginx.ingress.kubernetes.io/auth-url` to indicate the URL where the HTTP request should be sent.
```yaml
nginx.ingress.kubernetes.io/auth-url: "URL to the authentication service"
```
Additionally it is possible to set:
* `nginx.ingress.kubernetes.io/auth-method`:
`<Method>` to specify the HTTP method to use.
* `nginx.ingress.kubernetes.io/auth-signin`:
`<SignIn_URL>` to specify the location of the error page.
* `nginx.ingress.kubernetes.io/auth-signin-redirect-param`:
`<SignIn_URL>` to specify the URL parameter in the error page which should contain the original URL for a failed signin request.
* `nginx.ingress.kubernetes.io/auth-response-headers`:
`<Response_Header_1, ..., Response_Header_n>` to specify headers to pass to backend once authentication request completes.
* `nginx.ingress.kubernetes.io/auth-proxy-set-headers`:
`<ConfigMap>` the name of a ConfigMap that specifies headers to pass to the authentication service
* `nginx.ingress.kubernetes.io/auth-request-redirect`:
`<Request_Redirect_URL>` to specify the X-Auth-Request-Redirect header value.
* `nginx.ingress.kubernetes.io/auth-cache-key`:
`<Cache_Key>` this enables caching for auth requests. specify a lookup key for auth responses. e.g. `$remote_user$http_authorization`. Each server and location has it's own keyspace. Hence a cached response is only valid on a per-server and per-location basis.
* `nginx.ingress.kubernetes.io/auth-cache-duration`:
`<Cache_duration>` to specify a caching time for auth responses based on their response codes, e.g. `200 202 30m`. See [proxy_cache_valid](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_valid) for details. You may specify multiple, comma-separated values: `200 202 10m, 401 5m`. defaults to `200 202 401 5m`.
* `nginx.ingress.kubernetes.io/auth-snippet`:
`<Auth_Snippet>` to specify a custom snippet to use with external authentication, e.g.
```yaml
nginx.ingress.kubernetes.io/auth-url: http://foo.com/external-auth
nginx.ingress.kubernetes.io/auth-snippet: |
proxy_set_header Foo-Header 42;
```
> Note: `nginx.ingress.kubernetes.io/auth-snippet` is an optional annotation. However, it may only be used in conjunction with `nginx.ingress.kubernetes.io/auth-url` and will be ignored if `nginx.ingress.kubernetes.io/auth-url` is not set
!!! example
Please check the [external-auth](../../examples/auth/external-auth/README.md) example.
#### Global External Authentication
By default the controller redirects all requests to an existing service that provides authentication if `global-auth-url` is set in the NGINX ConfigMap. If you want to disable this behavior for that ingress, you can use `enable-global-auth: "false"` in the NGINX ConfigMap.
`nginx.ingress.kubernetes.io/enable-global-auth`:
indicates if GlobalExternalAuth configuration should be applied or not to this Ingress rule. Default values is set to `"true"`.
!!! note
For more information please see [global-auth-url](./configmap.md#global-auth-url).
### Rate Limiting
These annotations define limits on connections and transmission rates. These can be used to mitigate [DDoS Attacks](https://www.nginx.com/blog/mitigating-ddos-attacks-with-nginx-and-nginx-plus).
* `nginx.ingress.kubernetes.io/limit-connections`: number of concurrent connections allowed from a single IP address. A 503 error is returned when exceeding this limit.
* `nginx.ingress.kubernetes.io/limit-rps`: number of requests accepted from a given IP each second. The burst limit is set to this limit multiplied by the burst multiplier, the default multiplier is 5. When clients exceed this limit, [limit-req-status-code](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#limit-req-status-code) ***default:*** 503 is returned.
* `nginx.ingress.kubernetes.io/limit-rpm`: number of requests accepted from a given IP each minute. The burst limit is set to this limit multiplied by the burst multiplier, the default multiplier is 5. When clients exceed this limit, [limit-req-status-code](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#limit-req-status-code) ***default:*** 503 is returned.
* `nginx.ingress.kubernetes.io/limit-burst-multiplier`: multiplier of the limit rate for burst size. The default burst multiplier is 5, this annotation override the default multiplier. When clients exceed this limit, [limit-req-status-code](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#limit-req-status-code) ***default:*** 503 is returned.
* `nginx.ingress.kubernetes.io/limit-rate-after`: initial number of kilobytes after which the further transmission of a response to a given connection will be rate limited. This feature must be used with [proxy-buffering](#proxy-buffering) enabled.
* `nginx.ingress.kubernetes.io/limit-rate`: number of kilobytes per second allowed to send to a given connection. The zero value disables rate limiting. This feature must be used with [proxy-buffering](#proxy-buffering) enabled.
* `nginx.ingress.kubernetes.io/limit-whitelist`: client IP source ranges to be excluded from rate-limiting. The value is a comma separated list of CIDRs.
If you specify multiple annotations in a single Ingress rule, limits are applied in the order `limit-connections`, `limit-rpm`, `limit-rps`.
To configure settings globally for all Ingress rules, the `limit-rate-after` and `limit-rate` values may be set in the [NGINX ConfigMap](./configmap.md#limit-rate). The value set in an Ingress annotation will override the global setting.
The client IP address will be set based on the use of [PROXY protocol](./configmap.md#use-proxy-protocol) or from the `X-Forwarded-For` header value when [use-forwarded-headers](./configmap.md#use-forwarded-headers) is enabled.
### Global Rate Limiting
**Note:** Be careful when configuring both (Local) Rate Limiting and Global Rate Limiting at the same time.
They are two completely different rate limiting implementations. Whichever limit exceeds first will reject the
requests. It might be a good idea to configure both of them to ease load on Global Rate Limiting backend
in cases of spike in traffic.
The stock NGINX rate limiting does not share its counters among different NGINX instances.
Given that most ingress-nginx deployments are elastic and number of replicas can change any day
it is impossible to configure a proper rate limit using stock NGINX functionalities.
Global Rate Limiting overcome this by using [lua-resty-global-throttle](https://github.com/ElvinEfendi/lua-resty-global-throttle). `lua-resty-global-throttle` shares its counters via a central store such as `memcached`.
The obvious shortcoming of this is users have to deploy and operate a `memcached` instance
in order to benefit from this functionality. Configure the `memcached`
using [these configmap settings](./configmap.md#global-rate-limit).
**Here are a few remarks for ingress-nginx integration of `lua-resty-global-throttle`:**
1. We minimize `memcached` access by caching exceeding limit decisions. The expiry of
cache entry is the desired delay `lua-resty-global-throttle` calculates for us.
The Lua Shared Dictionary used for that is `global_throttle_cache`. Currently its size defaults to 10M.
Customize it as per your needs using [lua-shared-dicts](./configmap.md#lua-shared-dicts).
When we fail to cache the exceeding limit decision then we log an NGINX error. You can monitor
for that error to decide if you need to bump the cache size. Without cache the cost of processing a
request is two memcached commands: `GET`, and `INCR`. With the cache it is only `INCR`.
1. Log NGINX variable `$global_rate_limit_exceeding`'s value to have some visibility into
what portion of requests are rejected (value `y`), whether they are rejected using cached decision (value `c`),
or if they are not rejeced (default value `n`). You can use [log-format-upstream](./configmap.md#log-format-upstream)
to include that in access logs.
1. In case of an error it will log the error message and **fail open**.
1. The annotations below creates Global Rate Limiting instance per ingress.
That means if there are multuple paths configured under the same ingress,
the Global Rate Limiting will count requests to all the paths under the same counter.
Extract a path out into its own ingress if you need to isolate a certain path.
* `nginx.ingress.kubernetes.io/global-rate-limit`: Configures maximum allowed number of requests per window. Required.
* `nginx.ingress.kubernetes.io/global-rate-limit-window`: Configures a time window (i.e `1m`) that the limit is applied. Required.
* `nginx.ingress.kubernetes.io/global-rate-limit-key`: Configures a key for counting the samples. Defaults to `$remote_addr`. You can also combine multiple NGINX variables here, like `${remote_addr}-${http_x_api_client}` which would mean the limit will be applied to requests coming from the same API client (indicated by `X-API-Client` HTTP request header) with the same source IP address.
* `nginx.ingress.kubernetes.io/global-rate-limit-ignored-cidrs`: comma separated list of IPs and CIDRs to match client IP against. When there's a match request is not considered for rate limiting.
### Permanent Redirect
This annotation allows to return a permanent redirect (Return Code 301) instead of sending data to the upstream. For example `nginx.ingress.kubernetes.io/permanent-redirect: https://www.google.com` would redirect everything to Google.
### Permanent Redirect Code
This annotation allows you to modify the status code used for permanent redirects. For example `nginx.ingress.kubernetes.io/permanent-redirect-code: '308'` would return your permanent-redirect with a 308.
### Temporal Redirect
This annotation allows you to return a temporal redirect (Return Code 302) instead of sending data to the upstream. For example `nginx.ingress.kubernetes.io/temporal-redirect: https://www.google.com` would redirect everything to Google with a Return Code of 302 (Moved Temporarily)
### SSL Passthrough
The annotation `nginx.ingress.kubernetes.io/ssl-passthrough` instructs the controller to send TLS connections directly
to the backend instead of letting NGINX decrypt the communication. See also [TLS/HTTPS](../tls.md#ssl-passthrough) in
the User guide.
!!! note
SSL Passthrough is **disabled by default** and requires starting the controller with the
[`--enable-ssl-passthrough`](../cli-arguments.md) flag.
!!! attention
Because SSL Passthrough works on layer 4 of the OSI model (TCP) and not on the layer 7 (HTTP), using SSL Passthrough
invalidates all the other annotations set on an Ingress object.
### Service Upstream
By default the NGINX ingress controller uses a list of all endpoints (Pod IP/port) in the NGINX upstream configuration.
The `nginx.ingress.kubernetes.io/service-upstream` annotation disables that behavior and instead uses a single upstream in NGINX, the service's Cluster IP and port.
This can be desirable for things like zero-downtime deployments as it reduces the need to reload NGINX configuration when Pods come up and down. See issue [#257](https://github.com/kubernetes/ingress-nginx/issues/257).
#### Known Issues
If the `service-upstream` annotation is specified the following things should be taken into consideration:
* Sticky Sessions will not work as only round-robin load balancing is supported.
* The `proxy_next_upstream` directive will not have any effect meaning on error the request will not be dispatched to another upstream.
### Server-side HTTPS enforcement through redirect
By default the controller redirects (308) to HTTPS if TLS is enabled for that ingress.
If you want to disable this behavior globally, you can use `ssl-redirect: "false"` in the NGINX [ConfigMap](./configmap.md#ssl-redirect).
To configure this feature for specific ingress resources, you can use the `nginx.ingress.kubernetes.io/ssl-redirect: "false"`
annotation in the particular resource.
When using SSL offloading outside of cluster (e.g. AWS ELB) it may be useful to enforce a redirect to HTTPS
even when there is no TLS certificate available.
This can be achieved by using the `nginx.ingress.kubernetes.io/force-ssl-redirect: "true"` annotation in the particular resource.
To preserve the trailing slash in the URI with `ssl-redirect`, set `nginx.ingress.kubernetes.io/preserve-trailing-slash: "true"` annotation for that particular resource.
### Redirect from/to www
In some scenarios is required to redirect from `www.domain.com` to `domain.com` or vice versa.
To enable this feature use the annotation `nginx.ingress.kubernetes.io/from-to-www-redirect: "true"`
!!! attention
If at some point a new Ingress is created with a host equal to one of the options (like `domain.com`) the annotation will be omitted.
!!! attention
For HTTPS to HTTPS redirects is mandatory the SSL Certificate defined in the Secret, located in the TLS section of Ingress, contains both FQDN in the common name of the certificate.
### Whitelist source range
You can specify allowed client IP source ranges through the `nginx.ingress.kubernetes.io/whitelist-source-range` annotation.
The value is a comma separated list of [CIDRs](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing), e.g. `10.0.0.0/24,172.10.0.1`.
To configure this setting globally for all Ingress rules, the `whitelist-source-range` value may be set in the [NGINX ConfigMap](./configmap.md#whitelist-source-range).
!!! note
Adding an annotation to an Ingress rule overrides any global restriction.
### Custom timeouts
Using the configuration configmap it is possible to set the default global timeout for connections to the upstream servers.
In some scenarios is required to have different values. To allow this we provide annotations that allows this customization:
- `nginx.ingress.kubernetes.io/proxy-connect-timeout`
- `nginx.ingress.kubernetes.io/proxy-send-timeout`
- `nginx.ingress.kubernetes.io/proxy-read-timeout`
- `nginx.ingress.kubernetes.io/proxy-next-upstream`
- `nginx.ingress.kubernetes.io/proxy-next-upstream-timeout`
- `nginx.ingress.kubernetes.io/proxy-next-upstream-tries`
- `nginx.ingress.kubernetes.io/proxy-request-buffering`
Note: All timeout values are unitless and in seconds e.g. `nginx.ingress.kubernetes.io/proxy-read-timeout: "120"` sets a valid 120 seconds proxy read timeout.
### Proxy redirect
With the annotations `nginx.ingress.kubernetes.io/proxy-redirect-from` and `nginx.ingress.kubernetes.io/proxy-redirect-to` it is possible to
set the text that should be changed in the `Location` and `Refresh` header fields of a [proxied server response](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect)
Setting "off" or "default" in the annotation `nginx.ingress.kubernetes.io/proxy-redirect-from` disables `nginx.ingress.kubernetes.io/proxy-redirect-to`,
otherwise, both annotations must be used in unison. Note that each annotation must be a string without spaces.
By default the value of each annotation is "off".
### Custom max body size
For NGINX, an 413 error will be returned to the client when the size in a request exceeds the maximum allowed size of the client request body. This size can be configured by the parameter [`client_max_body_size`](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size).
To configure this setting globally for all Ingress rules, the `proxy-body-size` value may be set in the [NGINX ConfigMap](./configmap.md#proxy-body-size).
To use custom values in an Ingress rule define these annotation:
```yaml
nginx.ingress.kubernetes.io/proxy-body-size: 8m
```
### Proxy cookie domain
Sets a text that [should be changed in the domain attribute](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cookie_domain) of the "Set-Cookie" header fields of a proxied server response.
To configure this setting globally for all Ingress rules, the `proxy-cookie-domain` value may be set in the [NGINX ConfigMap](./configmap.md#proxy-cookie-domain).
### Proxy cookie path
Sets a text that [should be changed in the path attribute](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cookie_path) of the "Set-Cookie" header fields of a proxied server response.
To configure this setting globally for all Ingress rules, the `proxy-cookie-path` value may be set in the [NGINX ConfigMap](./configmap.md#proxy-cookie-path).
### Proxy buffering
Enable or disable proxy buffering [`proxy_buffering`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering).
By default proxy buffering is disabled in the NGINX config.
To configure this setting globally for all Ingress rules, the `proxy-buffering` value may be set in the [NGINX ConfigMap](./configmap.md#proxy-buffering).
To use custom values in an Ingress rule define these annotation:
```yaml
nginx.ingress.kubernetes.io/proxy-buffering: "on"
```
### Proxy buffers Number
Sets the number of the buffers in [`proxy_buffers`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffers) used for reading the first part of the response received from the proxied server.
By default proxy buffers number is set as 4
To configure this setting globally, set `proxy-buffers-number` in [NGINX ConfigMap](./configmap.md#proxy-buffers-number). To use custom values in an Ingress rule, define this annotation:
```yaml
nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
```
### Proxy buffer size
Sets the size of the buffer [`proxy_buffer_size`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size) used for reading the first part of the response received from the proxied server.
By default proxy buffer size is set as "4k"
To configure this setting globally, set `proxy-buffer-size` in [NGINX ConfigMap](./configmap.md#proxy-buffer-size). To use custom values in an Ingress rule, define this annotation:
```yaml
nginx.ingress.kubernetes.io/proxy-buffer-size: "8k"
```
### Proxy max temp file size
When [`buffering`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering) of responses from the proxied server is enabled, and the whole response does not fit into the buffers set by the [`proxy_buffer_size`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size) and [`proxy_buffers`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffers) directives, a part of the response can be saved to a temporary file. This directive sets the maximum `size` of the temporary file setting the [`proxy_max_temp_file_size`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_max_temp_file_size). The size of data written to the temporary file at a time is set by the [`proxy_temp_file_write_size`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_temp_file_write_size) directive.
The zero value disables buffering of responses to temporary files.
To use custom values in an Ingress rule, define this annotation:
```yaml
nginx.ingress.kubernetes.io/proxy-max-temp-file-size: "1024m"
```
### Proxy HTTP version
Using this annotation sets the [`proxy_http_version`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_http_version) that the Nginx reverse proxy will use to communicate with the backend.
By default this is set to "1.1".
```yaml
nginx.ingress.kubernetes.io/proxy-http-version: "1.0"
```
### SSL ciphers
Specifies the [enabled ciphers](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_ciphers).
Using this annotation will set the `ssl_ciphers` directive at the server level. This configuration is active for all the paths in the host.
```yaml
nginx.ingress.kubernetes.io/ssl-ciphers: "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP"
```
The following annotation will set the `ssl_prefer_server_ciphers` directive at the server level. This configuration specifies that server ciphers should be preferred over client ciphers when using the SSLv3 and TLS protocols.
```yaml
nginx.ingress.kubernetes.io/ssl-prefer-server-ciphers: "true"
```
### Connection proxy header
Using this annotation will override the default connection header set by NGINX.
To use custom values in an Ingress rule, define the annotation:
```yaml
nginx.ingress.kubernetes.io/connection-proxy-header: "keep-alive"
```
### Enable Access Log
Access logs are enabled by default, but in some scenarios access logs might be required to be disabled for a given
ingress. To do this, use the annotation:
```yaml
nginx.ingress.kubernetes.io/enable-access-log: "false"
```
### Enable Rewrite Log
Rewrite logs are not enabled by default. In some scenarios it could be required to enable NGINX rewrite logs.
Note that rewrite logs are sent to the error_log file at the notice level. To enable this feature use the annotation:
```yaml
nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
```
### Enable Opentracing
Opentracing can be enabled or disabled globally through the ConfigMap but this will sometimes need to be overridden
to enable it or disable it for a specific ingress (e.g. to turn off tracing of external health check endpoints)
```yaml
nginx.ingress.kubernetes.io/enable-opentracing: "true"
```
### Opentracing Trust Incoming Span
The option to trust incoming trace spans can be enabled or disabled globally through the ConfigMap but this will
sometimes need to be overriden to enable it or disable it for a specific ingress (e.g. only enable on a private endpoint)
```yaml
nginx.ingress.kubernetes.io/opentracing-trust-incoming-span: "true"
```
### X-Forwarded-Prefix Header
To add the non-standard `X-Forwarded-Prefix` header to the upstream request with a string value, the following annotation can be used:
```yaml
nginx.ingress.kubernetes.io/x-forwarded-prefix: "/path"
```
### ModSecurity
[ModSecurity](http://modsecurity.org/) is an OpenSource Web Application firewall. It can be enabled for a particular set
of ingress locations. The ModSecurity module must first be enabled by enabling ModSecurity in the
[ConfigMap](./configmap.md#enable-modsecurity). Note this will enable ModSecurity for all paths, and each path
must be disabled manually.
It can be enabled using the following annotation:
```yaml
nginx.ingress.kubernetes.io/enable-modsecurity: "true"
```
ModSecurity will run in "Detection-Only" mode using the [recommended configuration](https://github.com/SpiderLabs/ModSecurity/blob/v3/master/modsecurity.conf-recommended).
You can enable the [OWASP Core Rule Set](https://www.modsecurity.org/CRS/Documentation/) by
setting the following annotation:
```yaml
nginx.ingress.kubernetes.io/enable-owasp-core-rules: "true"
```
You can pass transactionIDs from nginx by setting up the following:
```yaml
nginx.ingress.kubernetes.io/modsecurity-transaction-id: "$request_id"
```
You can also add your own set of modsecurity rules via a snippet:
```yaml
nginx.ingress.kubernetes.io/modsecurity-snippet: |
SecRuleEngine On
SecDebugLog /tmp/modsec_debug.log
```
Note: If you use both `enable-owasp-core-rules` and `modsecurity-snippet` annotations together, only the
`modsecurity-snippet` will take effect. If you wish to include the [OWASP Core Rule Set](https://www.modsecurity.org/CRS/Documentation/) or
[recommended configuration](https://github.com/SpiderLabs/ModSecurity/blob/v3/master/modsecurity.conf-recommended) simply use the include
statement:
nginx 0.24.1 and below
```yaml
nginx.ingress.kubernetes.io/modsecurity-snippet: |
Include /etc/nginx/owasp-modsecurity-crs/nginx-modsecurity.conf
Include /etc/nginx/modsecurity/modsecurity.conf
```
nginx 0.25.0 and above
```yaml
nginx.ingress.kubernetes.io/modsecurity-snippet: |
Include /etc/nginx/owasp-modsecurity-crs/nginx-modsecurity.conf
```
### InfluxDB
Using `influxdb-*` annotations we can monitor requests passing through a Location by sending them to an InfluxDB backend exposing the UDP socket
using the [nginx-influxdb-module](https://github.com/influxdata/nginx-influxdb-module/).
```yaml
nginx.ingress.kubernetes.io/enable-influxdb: "true"
nginx.ingress.kubernetes.io/influxdb-measurement: "nginx-reqs"
nginx.ingress.kubernetes.io/influxdb-port: "8089"
nginx.ingress.kubernetes.io/influxdb-host: "127.0.0.1"
nginx.ingress.kubernetes.io/influxdb-server-name: "nginx-ingress"
```
For the `influxdb-host` parameter you have two options:
- Use an InfluxDB server configured with the [UDP protocol](https://docs.influxdata.com/influxdb/v1.5/supported_protocols/udp/) enabled.
- Deploy Telegraf as a sidecar proxy to the Ingress controller configured to listen UDP with the [socket listener input](https://github.com/influxdata/telegraf/tree/release-1.6/plugins/inputs/socket_listener) and to write using
anyone of the [outputs plugins](https://github.com/influxdata/telegraf/tree/release-1.7/plugins/outputs) like InfluxDB, Apache Kafka,
Prometheus, etc.. (recommended)
It's important to remember that there's no DNS resolver at this stage so you will have to configure
an ip address to `nginx.ingress.kubernetes.io/influxdb-host`. If you deploy Influx or Telegraf as sidecar (another container in the same pod) this becomes straightforward since you can directly use `127.0.0.1`.
### Backend Protocol
Using `backend-protocol` annotations is possible to indicate how NGINX should communicate with the backend service. (Replaces `secure-backends` in older versions)
Valid Values: HTTP, HTTPS, GRPC, GRPCS, AJP and FCGI
By default NGINX uses `HTTP`.
Example:
```yaml
nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
```
### Use Regex
!!! attention
When using this annotation with the NGINX annotation `nginx.ingress.kubernetes.io/affinity` of type `cookie`, `nginx.ingress.kubernetes.io/session-cookie-path` must be also set; Session cookie paths do not support regex.
Using the `nginx.ingress.kubernetes.io/use-regex` annotation will indicate whether or not the paths defined on an Ingress use regular expressions. The default value is `false`.
The following will indicate that regular expression paths are being used:
```yaml
nginx.ingress.kubernetes.io/use-regex: "true"
```
The following will indicate that regular expression paths are __not__ being used:
```yaml
nginx.ingress.kubernetes.io/use-regex: "false"
```
When this annotation is set to `true`, the case insensitive regular expression [location modifier](https://nginx.org/en/docs/http/ngx_http_core_module.html#location) will be enforced on ALL paths for a given host regardless of what Ingress they are defined on.
Additionally, if the [`rewrite-target` annotation](#rewrite) is used on any Ingress for a given host, then the case insensitive regular expression [location modifier](https://nginx.org/en/docs/http/ngx_http_core_module.html#location) will be enforced on ALL paths for a given host regardless of what Ingress they are defined on.
Please read about [ingress path matching](../ingress-path-matching.md) before using this modifier.
### Satisfy
By default, a request would need to satisfy all authentication requirements in order to be allowed. By using this annotation, requests that satisfy either any or all authentication requirements are allowed, based on the configuration value.
```yaml
nginx.ingress.kubernetes.io/satisfy: "any"
```
### Mirror
Enables a request to be mirrored to a mirror backend. Responses by mirror backends are ignored. This feature is useful, to see how requests will react in "test" backends.
The mirror backend can be set by applying:
```yaml
nginx.ingress.kubernetes.io/mirror-target: https://test.env.com/$request_uri
```
By default the request-body is sent to the mirror backend, but can be turned off by applying:
```yaml
nginx.ingress.kubernetes.io/mirror-request-body: "off"
```
**Note:** The mirror directive will be applied to all paths within the ingress resource.
The request sent to the mirror is linked to the original request. If you have a slow mirror backend, then the original request will throttle.
For more information on the mirror module see [ngx_http_mirror_module](https://nginx.org/en/docs/http/ngx_http_mirror_module.html)
| canhnt/ingress | docs/user-guide/nginx-configuration/annotations.md | Markdown | apache-2.0 | 61,451 |
# Bidens schaffneri Sherff SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Bidens schaffneri/README.md | Markdown | apache-2.0 | 174 |
module SchemaEvolutionManager
# Container for common args, mainly to have stricter validation on
# inputs. Tried to use GetoptLong but could not write solid unit
# tests around it... so we have our own internal simple implementation.
class Args
if !defined?(FLAGS_WITH_ARGUMENTS)
FLAGS_WITH_ARGUMENTS = {
:artifact_name => "Specifies the name of the artifact. Tag will be appended to this name",
:user => "Connect to the database as this username instead of the default",
:host => "Specifies the host name of the machine on which the server is running",
:port => "Specifies the port on which the server is running",
:name => "Specifies the name of the database to which to connect",
:url => "The connection string for the psql database",
:dir => "Path to a directory",
:tag => "A git tag (e.g. 0.0.1)",
:prefix => "Configure installer to use this prefix",
:set => "Passthrough for postgresql --set argument"
}
FLAGS_NO_ARGUMENTS = {
:password => "Prompt user to enter password for the database user. Password is stored for the duration of the process",
:dry_run => "Include flag to echo commands that will run without actually executing them",
:help => "Display help",
:verbose => "Enable verbose logging of all system calls",
}
end
attr_reader :artifact_name, :host, :port, :name, :prefix, :url, :user, :dir, :dry_run, :tag, :password, :set
# args: Actual string arguments
# :required => list of parameters that are required
# :optional => list of parameters that are optional
def initialize(args, opts={})
Preconditions.assert_class_or_nil(args, String)
required = (opts.delete(:required) || []).map { |flag| format_flag(flag) }
optional = (opts.delete(:optional) || []).map { |flag| format_flag(flag) }
Preconditions.assert_class(required, Array)
Preconditions.assert_class(optional, Array)
Preconditions.assert_empty_opts(opts)
Preconditions.check_state(optional.size + required.size > 0,
"Must have at least 1 optional or required parameter")
if !optional.include?(:help)
optional << :help
end
if !optional.include?(:verbose)
optional << :verbose
end
found_arguments = parse_string_arguments(args)
missing = required.select { |field| blank?(found_arguments[field]) }
@artifact_name = found_arguments.delete(:artifact_name)
@host = found_arguments.delete(:host)
@port = found_arguments.delete(:port)
@name = found_arguments.delete(:name)
@prefix = found_arguments.delete(:prefix)
@url = found_arguments.delete(:url)
@user = found_arguments.delete(:user)
@dir = found_arguments.delete(:dir)
@tag = found_arguments.delete(:tag)
@set = found_arguments.delete(:set)
@dry_run = found_arguments.delete(:dry_run)
@password = found_arguments.delete(:password)
@help = found_arguments.delete(:help)
@verbose = found_arguments.delete(:verbose)
Preconditions.check_state(found_arguments.empty?,
"Did not handle all flags: %s" % found_arguments.keys.join(" "))
if @help
RdocUsage.printAndExit(0)
end
if @verbose
Library.set_verbose(true)
end
if !missing.empty?
missing_fields_error(required, optional, missing)
end
end
# Hack to minimize bleeding from STDIN. Returns an instance of Args class
def Args.from_stdin(opts)
values = ARGV.join(" ")
Args.new(values, opts)
end
private
def blank?(value)
value.to_s.strip == ""
end
def missing_fields_error(required, optional, fields)
Preconditions.assert_class(fields, Array)
Preconditions.check_state(!fields.empty?, "Missing fields cannot be empty")
title = fields.size == 1 ? "Missing parameter" : "Missing parameters"
sorted = fields.sort_by { |f| f.to_s }
puts "**************************************************"
puts "ERROR: #{title}: #{sorted.join(", ")}"
puts "**************************************************"
puts help_parameters("Required parameters", required)
puts help_parameters("Optional parameters", optional)
exit(1)
end
def help_parameters(title, parameters)
docs = []
if !parameters.empty?
docs << ""
docs << title
docs << "-------------------"
parameters.each do |flag|
documentation = FLAGS_WITH_ARGUMENTS[flag] || FLAGS_NO_ARGUMENTS[flag]
Preconditions.check_not_null(documentation, "No documentation found for flag[%s]" % flag)
docs << " --#{flag}"
docs << " " + documentation
docs << ""
end
end
docs.join("\n")
end
def parse_string_arguments(args)
Preconditions.assert_class_or_nil(args, String)
found = {}
index = 0
values = args.to_s.strip.split(/\s+/)
while index < values.length do
flag = format_flag(values[index])
index += 1
if FLAGS_WITH_ARGUMENTS.has_key?(flag)
found[flag] = values[index]
index += 1
elsif FLAGS_NO_ARGUMENTS.has_key?(flag)
found[flag] = true
else
raise "Unknown flag[%s]" % flag
end
end
found
end
# Strip leading dashes and convert to symbol
def format_flag(flag)
Preconditions.assert_class(flag, String)
flag.sub(/^\-\-/, '').to_sym
end
end
end
| mbryzek/schema-evolution-manager | lib/schema-evolution-manager/args.rb | Ruby | apache-2.0 | 5,648 |
<?php
namespace Ajax\semantic\components\validation;
use Ajax\service\AjaxCall;
use Ajax\JsUtils;
/**
* @author jc
* @version 1.001
* Generates a JSON Rule for the validation of a field
*/
class Rule implements \JsonSerializable{
/**
* @var string
*/
private $type;
/**
* @var string
*/
private $prompt;
/**
* @var string
*/
private $value;
public function __construct($type,$prompt=NULL,$value=NULL){
$this->type=$type;
$this->prompt=$prompt;
$this->value=$value;
}
public function getType() {
return $this->type;
}
public function setType($type) {
$this->type=$type;
return $this;
}
public function getPrompt() {
return $this->prompt;
}
public function setPrompt($prompt) {
$this->prompt=$prompt;
return $this;
}
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value=$value;
return $this;
}
#[\ReturnTypeWillChange]
public function jsonSerialize() {
$result= ["type"=>$this->type];
if(isset($this->prompt))
$result["prompt"]=$this->prompt;
if(isset($this->value))
$result["value"]=$this->value;
return $result;
}
/**
* A field should match the value of another validation field, for example to confirm passwords
* @param string $name
* @param string $prompt
* @return \Ajax\semantic\components\validation\Rule
*/
public static function match($name,$prompt=NULL){
return new Rule("match[".$name."]",$prompt);
}
/**
* A field should be different than another specified field
* @param string $name
* @param string $prompt
* @return \Ajax\semantic\components\validation\Rule
*/
public static function different($name,$prompt=NULL){
return new Rule("different[".$name."]",$prompt);
}
/**
* A field is an integer value, or matches an integer range
* @param int|NULL $min
* @param int|NULL $max
* @param string $prompt
* @return \Ajax\semantic\components\validation\Rule
*/
public static function integer($min=NULL,$max=NULL,$prompt=NULL){
if(\is_int($min) && \is_int($max))
return new Rule("integer[{$min}..{$max}]",$prompt);
return new Rule("integer",$prompt);
}
public static function decimal($prompt=NULL){
return new Rule("decimal",$prompt);
}
public static function number($prompt=NULL){
return new Rule("number",$prompt);
}
public static function is($value,$prompt=NULL){
return new Rule("is[".$value."]",$prompt);
}
public static function isExactly($value,$prompt=NULL){
return new Rule("isExactly[".$value."]",$prompt);
}
public static function not($value,$prompt=NULL){
return new Rule("not[".$value."]",$prompt);
}
public static function notExactly($value,$prompt=NULL){
return new Rule("notExactly[".$value."]",$prompt);
}
public static function contains($value,$prompt=NULL){
return new Rule("contains[".$value."]",$prompt);
}
public static function containsExactly($value,$prompt=NULL){
return new Rule("containsExactly[".$value."]",$prompt);
}
public static function doesntContain($value,$prompt=NULL){
return new Rule("doesntContain[".$value."]",$prompt);
}
public static function doesntContainExactly($value,$prompt=NULL){
return new Rule("doesntContainExactly[".$value."]",$prompt);
}
public static function minCount($value,$prompt=NULL){
return new Rule("minCount[".$value."]",$prompt);
}
public static function maxCount($value,$prompt=NULL){
return new Rule("maxCount[".$value."]",$prompt);
}
public static function exactCount($value,$prompt=NULL){
return new Rule("exactCount[".$value."]",$prompt);
}
public static function email($prompt=NULL){
return new Rule("email",$prompt);
}
public static function url($prompt=NULL){
return new Rule("url",$prompt);
}
public static function regExp($value,$prompt=NULL){
return new Rule("regExp",$prompt,$value);
}
public static function custom($name,$jsFunction){
return "$.fn.form.settings.rules.".$name." =".$jsFunction ;
}
public static function ajax(JsUtils $js,$name,$url,$params,$jsCallback,$method="post",$parameters=[]){
$parameters=\array_merge(["async"=>false,"url"=>$url,"params"=>$params,"hasLoader"=>false,"jsCallback"=>$jsCallback,"dataType"=>"json","stopPropagation"=>false,"preventDefault"=>false,"responseElement"=>null],$parameters);
$ajax=new AjaxCall($method, $parameters);
return self::custom($name, "function(value,ruleValue){var result=true;".$ajax->compile($js)."return result;}");
}
}
| phpMv/phpMv-UI | Ajax/semantic/components/validation/Rule.php | PHP | apache-2.0 | 4,448 |
import torch
from deluca.lung.core import Controller, LungEnv
class PIDCorrection(Controller):
def __init__(self, base_controller: Controller, sim: LungEnv, pid_K=[0.0, 0.0], decay=0.1, **kwargs):
self.base_controller = base_controller
self.sim = sim
self.I = 0.0
self.K = pid_K
self.decay = decay
self.reset()
def reset(self):
self.base_controller.reset()
self.sim.reset()
self.I = 0.0
def compute_action(self, state, t):
u_in_base, u_out = self.base_controller(state, t)
err = self.sim.pressure - state
self.I = self.I * (1 - self.decay) + err * self.decay
pid_correction = self.K[0] * err + self.K[1] * self.I
u_in = torch.clamp(u_in_base + pid_correction, min=0.0, max=100.0)
self.sim(u_in, u_out, t)
return u_in, u_out
| google/deluca-lung | deluca/lung/experimental/controllers/_pid_correction.py | Python | apache-2.0 | 874 |
# Sphaeria eckfeldtii Ellis SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bull. Torrey bot. Club 8: 91 (1881)
#### Original name
Sphaeria eckfeldtii Ellis
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Sphaeria/Sphaeria eckfeldtii/README.md | Markdown | apache-2.0 | 210 |
# Heliopsis patula Wender. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Heliopsis/Heliopsis patula/README.md | Markdown | apache-2.0 | 174 |
# Numulariola mucronata (Mont.) P.M.D. Martin, 1976 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
S. Afr. J. Bot. 42(1): 78 (1976)
#### Original name
Camillea mucronata Mont., 1855
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Camillea/Camillea mucronata/ Syn. Numulariola mucronata/README.md | Markdown | apache-2.0 | 260 |
# Agave applanata var. parryi 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/Asparagaceae/Agave/Agave parryi/ Syn. Agave applanata parryi/README.md | Markdown | apache-2.0 | 184 |
# Duvernaysphaera oa Loeblich & Wicander, 1976 SPECIES
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Prasinophyta/Prasinophyceae/Mamiellales/Pycnococcaceae/Duvernaysphaera/Duvernaysphaera oa/README.md | Markdown | apache-2.0 | 210 |
# Memecylon perakense Merr. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Memecylon/Memecylon perakense/README.md | Markdown | apache-2.0 | 175 |
# Puccinia spreta Peck SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Ann. Rep. N. Y. St. Mus. nat. Hist. 29: 67 (1878)
#### Original name
Puccinia tiarellae Peck
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Puccinia/Puccinia spreta/README.md | Markdown | apache-2.0 | 217 |
# Croton uruguayensis Baill. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Croton/Croton uruguayensis/README.md | Markdown | apache-2.0 | 184 |
# Leymus divaricatus (Drobow) Tzvelev SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Bot. Mater. Gerb. Bot. Inst. Komarova Akad. Nauk S. S. S. R. 20:430. 1960
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Leymus/Leymus divaricatus/README.md | Markdown | apache-2.0 | 262 |
# Rottlera lappacea Wall. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Mallotus/Rottlera lappacea/README.md | Markdown | apache-2.0 | 173 |
# Heteropterys candolleana A.Juss. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Malpighiaceae/Heteropterys/Heteropterys candolleana/README.md | Markdown | apache-2.0 | 182 |
# Dianthus gasparrini Guss. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Dianthus/Dianthus gasparrini/README.md | Markdown | apache-2.0 | 175 |
# Schistophyllidium imbricatum (Kar. & Kir.) Soják SPECIES
#### Status
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Schistophyllidium/Schistophyllidium imbricatum/README.md | Markdown | apache-2.0 | 207 |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.IO;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// DialogValidValues allow user to provide ValidValues: Value and Label lists
/// </summary>
internal class DialogValidValues : System.Windows.Forms.Form
{
private DataTable _DataTable;
private DataGridTextBoxColumn dgtbLabel;
private DataGridTextBoxColumn dgtbValue;
private System.Windows.Forms.DataGridTableStyle dgTableStyle;
private System.Windows.Forms.DataGrid dgParms;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Button bDelete;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DialogValidValues(List<ParameterValueItem> list)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(list);
}
internal List<ParameterValueItem> ValidValues
{
get
{
List<ParameterValueItem> list = new List<ParameterValueItem>();
foreach (DataRow dr in _DataTable.Rows)
{
if (dr[0] == DBNull.Value)
continue;
string val = (string) dr[0];
if (val.Length <= 0)
continue;
string label;
if (dr[1] == DBNull.Value)
label = null;
else
label = (string) dr[1];
ParameterValueItem pvi = new ParameterValueItem();
pvi.Value = val;
pvi.Label = label;
list.Add(pvi);
}
return list.Count > 0? list: null;
}
}
private void InitValues(List<ParameterValueItem> list)
{
// Initialize the DataGrid columns
dgtbLabel = new DataGridTextBoxColumn();
dgtbValue = new DataGridTextBoxColumn();
this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] {
this.dgtbValue,
this.dgtbLabel});
//
// dgtbFE
//
dgtbValue.HeaderText = "Value";
dgtbValue.MappingName = "Value";
dgtbValue.Width = 75;
//
// dgtbValue
//
this.dgtbLabel.HeaderText = "Label";
this.dgtbLabel.MappingName = "Label";
this.dgtbLabel.Width = 75;
// Initialize the DataGrid
//this.dgParms.DataSource = _dsv.QueryParameters;
_DataTable = new DataTable();
_DataTable.Columns.Add(new DataColumn("Value", typeof(string)));
_DataTable.Columns.Add(new DataColumn("Label", typeof(string)));
string[] rowValues = new string[2];
if (list != null)
foreach (ParameterValueItem pvi in list)
{
rowValues[0] = pvi.Value;
rowValues[1] = pvi.Label;
_DataTable.Rows.Add(rowValues);
}
this.dgParms.DataSource = _DataTable;
////
DataGridTableStyle ts = dgParms.TableStyles[0];
ts.GridColumnStyles[0].Width = 140;
ts.GridColumnStyles[1].Width = 140;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dgParms = new System.Windows.Forms.DataGrid();
this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.bDelete = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dgParms)).BeginInit();
this.SuspendLayout();
//
// dgParms
//
this.dgParms.CaptionVisible = false;
this.dgParms.DataMember = "";
this.dgParms.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgParms.Location = new System.Drawing.Point(8, 8);
this.dgParms.Name = "dgParms";
this.dgParms.Size = new System.Drawing.Size(320, 168);
this.dgParms.TabIndex = 2;
this.dgParms.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dgTableStyle});
//
// dgTableStyle
//
this.dgTableStyle.AllowSorting = false;
this.dgTableStyle.DataGrid = this.dgParms;
this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgTableStyle.MappingName = "";
//
// bOK
//
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOK.Location = new System.Drawing.Point(216, 192);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 3;
this.bOK.Text = "OK";
//
// bCancel
//
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(312, 192);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 4;
this.bCancel.Text = "Cancel";
//
// bDelete
//
this.bDelete.Location = new System.Drawing.Point(336, 16);
this.bDelete.Name = "bDelete";
this.bDelete.Size = new System.Drawing.Size(48, 23);
this.bDelete.TabIndex = 5;
this.bDelete.Text = "Delete";
this.bDelete.Click += new System.EventHandler(this.bDelete_Click);
//
// DialogValidValues
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(392, 222);
this.ControlBox = false;
this.Controls.Add(this.bDelete);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.Controls.Add(this.dgParms);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogValidValues";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Valid Values";
((System.ComponentModel.ISupportInitialize)(this.dgParms)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void bDelete_Click(object sender, System.EventArgs e)
{
this._DataTable.Rows.RemoveAt(this.dgParms.CurrentRowIndex);
}
}
}
| gregberns/ZipRdlProjectDev410 | src/RdlDesign/DialogValidValues.cs | C# | apache-2.0 | 7,188 |
package org.ngrinder.home.controller;
import lombok.RequiredArgsConstructor;
import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.home.model.PanelEntry;
import org.ngrinder.home.service.HomeService;
import org.ngrinder.infra.config.Config;
import org.ngrinder.script.handler.ScriptHandler;
import org.ngrinder.script.handler.ScriptHandlerFactory;
import org.ngrinder.user.service.UserContext;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.util.*;
import static java.util.Comparator.comparing;
import static org.ngrinder.common.constant.ControllerConstants.*;
import static org.ngrinder.common.util.CollectionUtils.buildMap;
import static org.ngrinder.common.util.NoOp.noOp;
/**
* Home index page api controller.
*
* @since 3.5.0
*/
@RestController
@RequestMapping("/home/api")
@RequiredArgsConstructor
public class HomeApiController {
private static final String TIMEZONE_ID_PREFIXES = "^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private final HomeService homeService;
private final ScriptHandlerFactory scriptHandlerFactory;
private final UserContext userContext;
private final Config config;
private final MessageSource messageSource;
private List<TimeZone> timeZones = null;
@PostConstruct
public void init() {
timeZones = new ArrayList<>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES) && !TimeZone.getTimeZone(id).getDisplayName().contains("GMT")) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
timeZones.sort(comparing(TimeZone::getID));
}
@GetMapping("/handlers")
public List<ScriptHandler> getHandlers() {
return scriptHandlerFactory.getVisibleHandlers();
}
@GetMapping("/panel")
public Map<String, Object> getPanelEntries() {
return buildMap("leftPanelEntries", getLeftPanelEntries(), "rightPanelEntries", getRightPanelEntries());
}
@GetMapping("/timezones")
public List<TimeZone> getTimezones() {
return timeZones;
}
@GetMapping("/config")
public Map<String, Object> getCommonHomeConfig() {
return buildMap(
"askQuestionUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_ASK_QUESTION_URL,
getMessages(PROP_CONTROLLER_FRONT_PAGE_ASK_QUESTION_URL)),
"seeMoreQuestionUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_QNA_MORE_URL,
getMessages(PROP_CONTROLLER_FRONT_PAGE_QNA_MORE_URL)),
"seeMoreResourcesUrl", config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_RESOURCES_MORE_URL),
"userLanguage", config.getControllerProperties().getProperty(ControllerConstants.PROP_CONTROLLER_DEFAULT_LANG));
}
private List<PanelEntry> getRightPanelEntries() {
if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_FRONT_PAGE_ENABLED)) {
// Get nGrinder Resource RSS
String rightPanelRssURL = config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_RESOURCES_RSS);
return homeService.getRightPanelEntries(rightPanelRssURL);
}
return Collections.emptyList();
}
private List<PanelEntry> getLeftPanelEntries() {
if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_FRONT_PAGE_ENABLED)) {
// Make the i18n applied QnA panel. Depending on the user language, show the different QnA panel.
String leftPanelRssURLKey = getMessages(PROP_CONTROLLER_FRONT_PAGE_QNA_RSS);
// Make admin configure the QnA panel.
String leftPanelRssURL = config.getControllerProperties().getProperty(PROP_CONTROLLER_FRONT_PAGE_QNA_RSS,
leftPanelRssURLKey);
return homeService.getLeftPanelEntries(leftPanelRssURL);
}
return Collections.emptyList();
}
@GetMapping("/messagesources/{locale}")
public Map<String, String> getUserDefinedMessageSources(@PathVariable String locale) {
return homeService.getUserDefinedMessageSources(locale);
}
/**
* Get the message from messageSource by the given key.
*
* @param key key of message
* @return the found message. If not found, the error message will return.
*/
private String getMessages(String key) {
String userLanguage = "en";
try {
userLanguage = userContext.getCurrentUser().getUserLanguage();
} catch (Exception e) {
noOp();
}
Locale locale = new Locale(userLanguage);
return messageSource.getMessage(key, null, locale);
}
}
| naver/ngrinder | ngrinder-controller/src/main/java/org/ngrinder/home/controller/HomeApiController.java | Java | apache-2.0 | 4,677 |
package com.huawei.esdk.fusionmanager.local.model.system;
import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse;
/**
* 查询计划任务详情返回信息。
* <p>
* @since eSDK Cloud V100R003C30
*/
public class QueryScheduleTaskDetailResp extends FMSDKResponse
{
/**
* 计划任务。
*/
private ScheduleTask scheduleTask;
public ScheduleTask getScheduleTask()
{
return scheduleTask;
}
public void setScheduleTask(ScheduleTask scheduleTask)
{
this.scheduleTask = scheduleTask;
}
}
| eSDK/esdk_cloud_fm_r3_native_java | source/FM/V1R5/esdk_fm_neadp_1.5_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/model/system/QueryScheduleTaskDetailResp.java | Java | apache-2.0 | 571 |
<!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_74) on Mon Jan 02 20:06:46 EET 2017 -->
<title>Uses of Class com.complet.DatabaseConnection</title>
<meta name="date" content="2017-01-02">
<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 com.complet.DatabaseConnection";
}
}
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="../../../com/complet/package-summary.html">Package</a></li>
<li><a href="../../../com/complet/DatabaseConnection.html" title="class in com.complet">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/complet/class-use/DatabaseConnection.html" target="_top">Frames</a></li>
<li><a href="DatabaseConnection.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 com.complet.DatabaseConnection" class="title">Uses of Class<br>com.complet.DatabaseConnection</h2>
</div>
<div class="classUseContainer">No usage of com.complet.DatabaseConnection</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="../../../com/complet/package-summary.html">Package</a></li>
<li><a href="../../../com/complet/DatabaseConnection.html" title="class in com.complet">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/complet/class-use/DatabaseConnection.html" target="_top">Frames</a></li>
<li><a href="DatabaseConnection.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 ======= -->
</body>
</html>
| milouk/Web_Crawler | doc/com/complet/class-use/DatabaseConnection.html | HTML | apache-2.0 | 4,246 |
//Copyright (c) 2014 by Disy Informationssysteme GmbH
package net.disy.eenvplus.tfes.modules.sparql.expression;
import com.hp.hpl.jena.sparql.expr.E_LogicalAnd;
import com.hp.hpl.jena.sparql.expr.E_LogicalOr;
import com.hp.hpl.jena.sparql.expr.Expr;
import com.hp.hpl.jena.sparql.syntax.ElementFilter;
// NOT_PUBLISHED
public class SparqlExpressionBuilder {
private Expr current;
private SparqlExpressionBuilder(Expr expression) {
this.current = expression;
}
public static SparqlExpressionBuilder use(Expr expression) {
return new SparqlExpressionBuilder(expression);
}
public Expr toExpr() {
return current;
}
public ElementFilter toElementFilter() {
return new ElementFilter(current);
}
public SparqlExpressionBuilder and(Expr expression) {
if (expression != null) {
current = new E_LogicalAnd(current, expression);
}
return this;
}
public SparqlExpressionBuilder and(Expr expression, boolean condition) {
if (condition) {
return and(expression);
}
return this;
}
public SparqlExpressionBuilder or(Expr expression) {
if (expression != null) {
current = new E_LogicalOr(current, expression);
}
return this;
}
}
| eENVplus/tf-exploitation-server | TF_Exploitation_Server_modules/src/main/java/net/disy/eenvplus/tfes/modules/sparql/expression/SparqlExpressionBuilder.java | Java | apache-2.0 | 1,223 |
(function (chaiJquery) {
// Module systems magic dance.
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// NodeJS
module.exports = chaiJquery;
} else if (typeof define === "function" && define.amd) {
// AMD
define(function () {
return chaiJquery;
});
} else {
// Other environment (usually <script> tag): pass into global chai
var global = (false || eval)("this");
global.chai.use(chaiJquery);
}
}(function (chai, utils) {
var inspect = utils.inspect,
flag = utils.flag;
jQuery.fn.inspect = function (depth) {
var el = jQuery('<div />').append(this.clone());
if (depth) {
var children = el.children();
while (depth-- > 0)
children = children.children();
children.html('...');
}
return el.html();
};
chai.Assertion.addMethod('attr', function (name, val) {
var actual = flag(this, 'object').attr(name);
if (!flag(this, 'negate') || undefined === val) {
this.assert(
undefined !== actual
, 'expected #{this} to have a #{exp} attribute'
, 'expected #{this} not to have a #{exp} attribute'
, name
);
}
if (undefined !== val) {
this.assert(
val === actual
, 'expected #{this} to have a ' + inspect(name) + ' attribute with the value #{exp}, but the value was #{act}'
, 'expected #{this} not to have a ' + inspect(name) + ' attribute with the value #{act}'
, val
, actual
);
}
flag(this, 'object', actual);
});
chai.Assertion.addMethod('data', function (name, val) {
// Work around a chai bug (https://github.com/logicalparadox/chai/issues/16)
if (flag(this, 'negate') && undefined !== val && undefined === flag(this, 'object').data(name)) {
return;
}
var assertion = new chai.Assertion(flag(this, 'object').data());
if (flag(this, 'negate'))
assertion = assertion.not;
assertion.property(name, val);
});
chai.Assertion.addMethod('class', function (className) {
this.assert(
flag(this, 'object').hasClass(className)
, 'expected #{this} to have class #{exp}'
, 'expected #{this} not to have class #{exp}'
, className
);
});
chai.Assertion.addMethod('id', function (id) {
this.assert(
flag(this, 'object').attr('id') === id
, 'expected #{this} to have id #{exp}'
, 'expected #{this} not to have id #{exp}'
, id
);
});
chai.Assertion.addMethod('html', function (html) {
this.assert(
flag(this, 'object').html() === html
, 'expected #{this} to have HTML #{exp}'
, 'expected #{this} not to have HTML #{exp}'
, html
);
});
chai.Assertion.addMethod('text', function (text) {
this.assert(
flag(this, 'object').text() === text
, 'expected #{this} to have text #{exp}'
, 'expected #{this} not to have text #{exp}'
, text
);
});
chai.Assertion.addMethod('value', function (value) {
this.assert(
flag(this, 'object').val() === value
, 'expected #{this} to have value #{exp}'
, 'expected #{this} not to have value #{exp}'
, value
);
});
jQuery.each(['visible', 'hidden', 'selected', 'checked', 'disabled'], function (i, attr) {
chai.Assertion.addProperty(attr, function () {
this.assert(
flag(this, 'object').is(':' + attr)
, 'expected #{this} to be ' + attr
, 'expected #{this} not to be ' + attr);
});
});
chai.Assertion.overwriteProperty('exist', function (_super) {
return function () {
var obj = flag(this, 'object');
if (obj instanceof jQuery) {
this.assert(
obj.length > 0
, 'expected ' + inspect(obj.selector) + ' to exist'
, 'expected ' + inspect(obj.selector) + ' not to exist');
} else {
_super.apply(this, arguments);
}
};
});
chai.Assertion.overwriteProperty('be', function (_super) {
return function () {
var be = function (selector) {
var obj = flag(this, 'object');
if (obj instanceof jQuery) {
this.assert(
obj.is(selector)
, 'expected #{this} to be #{exp}'
, 'expected #{this} not to be #{exp}'
, selector
);
} else {
_super.apply(this, arguments);
}
};
be.__proto__ = this;
return be;
}
});
chai.Assertion.overwriteMethod('match', function (_super) {
return function (selector) {
var obj = flag(this, 'object');
if (obj instanceof jQuery) {
this.assert(
obj.is(selector)
, 'expected #{this} to match #{exp}'
, 'expected #{this} not to match #{exp}'
, selector
);
} else {
_super.apply(this, arguments);
}
}
});
chai.Assertion.overwriteProperty('contain', function (_super) {
return function () {
_super.call(this);
var contain = function (text) {
var obj = flag(this, 'object');
if (obj instanceof jQuery) {
this.assert(
obj.is(':contains(\'' + text + '\')')
, 'expected #{this} to contain #{exp}'
, 'expected #{this} not to contain #{exp}'
, text
);
} else {
Function.prototype.apply.call(_super.call(this), this, arguments);
}
};
contain.__proto__ = this;
return contain;
}
});
chai.Assertion.overwriteProperty('have', function (_super) {
return function () {
_super.call(this);
var have = function (selector) {
var obj = flag(this, 'object');
if (obj instanceof jQuery) {
this.assert(
// Using find() rather than has() to work around a jQuery bug:
// http://bugs.jquery.com/ticket/11706
obj.find(selector).length > 0
, 'expected #{this} to have #{exp}'
, 'expected #{this} not to have #{exp}'
, selector
);
}
};
have.__proto__ = this;
return have;
}
});
}));
| reaktor/jquery.spinner | test/chai-jquery-1.0.0.js | JavaScript | apache-2.0 | 6,187 |
package util
import "errors"
var (
// ErrNotFound Import or Version was not found.
ErrNotFound = errors.New("Requested resource was not found")
// ErrAlreadyExists Import or Version already exists and cannot be overwritten.
ErrAlreadyExists = errors.New("Resource already exists and cannot be overritten")
// ErrDisabled Import or Version has been disabled and cannot be downloaded.
ErrDisabled = errors.New("Resource disabled")
)
| deejross/dep-registry | util/errors.go | GO | apache-2.0 | 441 |
/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Southwest Research Institute
*
* 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.
*/
#ifndef ROBOT_KINEMATICS_H_
#define ROBOT_KINEMATICS_H_
// TODO: The include below picks up Eigen::Isometry3d, but there is probably a better way
#include <moveit/kinematic_constraints/kinematic_constraint.h>
#include "descartes_core/utils.h"
namespace descartes_core
{
DESCARTES_CLASS_FORWARD(RobotModel);
/**@brief RobotModel defines the interface to a kinematics/dynamics functions. Implementations
* of this class will be used in conjunction with TrajectoryPt objects to determine forward
* and inverse kinematics
*
* All methods in this interface class assume a *FIXED* TOOL & WOBJ frame (see TrajectoryPt
* for frame definitions). The methods for setting/getting these frames are not defined by
* this class. Implementations of this interface should provide these either by construction
* or getter/setter methods.
*/
class RobotModel
{
public:
virtual ~RobotModel()
{
}
/**
* @brief Returns the joint pose closest to the seed pose for a desired affine pose
* @param pose Affine pose of TOOL in WOBJ frame
* @param seed_state Joint position seed (returned solution is "close" to the seed).
* @param joint_pose Solution (if function successful).
* @return True if successful
*/
virtual bool getIK(const Eigen::Isometry3d &pose, const std::vector<double> &seed_state,
std::vector<double> &joint_pose) const = 0;
/**
* @brief Returns "all" the joint poses("distributed" in joint space) for a desired affine pose.
* "All" is determined by each implementation (In the worst case, this means at least getIK).
* "Distributed" is determined by each implementation.
* @param pose Affine pose of TOOL in WOBJ frame
* @param joint_poses Solution (if function successful).
* @return True if successful
*/
virtual bool getAllIK(const Eigen::Isometry3d &pose, std::vector<std::vector<double> > &joint_poses) const = 0;
/**
* @brief Returns the affine pose
* @param joint_pose Solution (if function successful).
* @param pose Affine pose of TOOL in WOBJ frame
* @return True if successful
*/
virtual bool getFK(const std::vector<double> &joint_pose, Eigen::Isometry3d &pose) const = 0;
/**
* @brief Returns number of DOFs
* @return Int
*/
virtual int getDOF() const = 0;
/**
* @brief Performs all necessary checks to determine joint pose is valid
* @param joint_pose Pose to check
* @return True if valid
*/
virtual bool isValid(const std::vector<double> &joint_pose) const = 0;
/**
* @brief Performs all necessary checks to determine affine pose is valid
* @param pose Affine pose of TOOL in WOBJ frame
* @return True if valid
*/
virtual bool isValid(const Eigen::Isometry3d &pose) const = 0;
/**
* @brief Returns the joint velocity limits for each joint in the robot kinematic model
* @return Sequence of joint velocity limits. Units are a function of the joint type (m/s
* for linear joints; rad/s for rotational). size of vector == getDOF()
*/
virtual std::vector<double> getJointVelocityLimits() const = 0;
/**
* @brief Initializes the robot model when it is instantiated as a moveit_core plugin.
* @param robot_description name of the ros parameter containing the urdf description
* @param group_name the manipulation group for all the robot links that are part of the same kinematic chain
* @param world_frame name of the root link in the urdf
* @param tcp_frame tool link attached to the robot. When it's not in 'group_name' then it should have
* a fixed location relative to the last link in 'group_name'.
*/
virtual bool initialize(const std::string &robot_description, const std::string &group_name,
const std::string &world_frame, const std::string &tcp_frame) = 0;
/**
* @brief Enables collision checks
* @param check_collisions enables or disables collisions
*/
virtual void setCheckCollisions(bool check_collisions)
{
check_collisions_ = check_collisions;
}
/**
* @brief Indicates if collision checks are enabled
* @return Bool
*/
virtual bool getCheckCollisions()
{
return check_collisions_;
}
/**
* @brief Performs necessary checks to see if the robot is capable of moving from the initial joint pose
* to the final pose in dt seconds
* @param from_joint_pose [description]
* @param to_joint_pose [description]
* @param dt [description]
* @return [description]
*/
virtual bool isValidMove(const std::vector<double> &from_joint_pose, const std::vector<double> &to_joint_pose,
double dt) const
{
return isValidMove(from_joint_pose.data(), to_joint_pose.data(), dt);
}
virtual bool isValidMove(const double* s, const double* f, double dt) const = 0;
protected:
RobotModel() : check_collisions_(false)
{
}
bool check_collisions_;
};
} // descartes_core
#endif /* ROBOT_KINEMATICS_H_ */
| ros-industrial-consortium/descartes | descartes_core/include/descartes_core/robot_model.h | C | apache-2.0 | 5,644 |
# Agropyron transiliense Popov 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/Poaceae/Elymus/Elymus mutabilis/ Syn. Agropyron transiliense/README.md | Markdown | apache-2.0 | 185 |
// Copyright (c) 2015 Illyriad Games Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.md in the project root for license information.
using System;
using System.Numerics;
namespace IllyriadGames.ByteArrayExtensions
{
public static class VectorizedCopyExtension
{
// Will be Jit'd to consts https://github.com/dotnet/coreclr/issues/1079
private static readonly int _vectorSpan = Vector<byte>.Count;
private static readonly int _vectorSpan2 = Vector<byte>.Count + Vector<byte>.Count;
private static readonly int _vectorSpan3 = Vector<byte>.Count + Vector<byte>.Count + Vector<byte>.Count;
private static readonly int _vectorSpan4 = Vector<byte>.Count + Vector<byte>.Count + Vector<byte>.Count + Vector<byte>.Count;
private const int _longSpan = sizeof(long);
private const int _longSpan2 = sizeof(long) + sizeof(long);
private const int _longSpan3 = sizeof(long) + sizeof(long) + sizeof(long);
private const int _intSpan = sizeof(int);
/// <summary>
/// Copies a specified number of bytes from a source array starting at a particular
/// offset to a destination array starting at a particular offset, not safe for overlapping data.
/// </summary>
/// <param name="src">The source buffer</param>
/// <param name="srcOffset">The zero-based byte offset into src</param>
/// <param name="dst">The destination buffer</param>
/// <param name="dstOffset">The zero-based byte offset into dst</param>
/// <param name="count">The number of bytes to copy</param>
/// <exception cref="ArgumentNullException"><paramref name="src"/> or <paramref name="dst"/> is null</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="srcOffset"/>, <paramref name="dstOffset"/>, or <paramref name="count"/> is less than 0</exception>
/// <exception cref="ArgumentException">
/// The number of bytes in src is less
/// than srcOffset plus count.-or- The number of bytes in dst is less than dstOffset
/// plus count.
/// </exception>
/// <remarks>
/// Code must be optimized, in release mode and <see cref="Vector"/>.IsHardwareAccelerated must be true for the performance benefits.
/// </remarks>
public unsafe static void VectorizedCopy(this byte[] src, int srcOffset, byte[] dst, int dstOffset, int count)
{
#if !DEBUG
// Tests need to check even if IsHardwareAccelerated == false
// Check will be Jitted away https://github.com/dotnet/coreclr/issues/1079
if (Vector.IsHardwareAccelerated)
{
#endif
if (count > 512 + 64)
{
// In-built copy faster for large arrays (vs repeated bounds checks on Vector.ctor?)
Array.Copy(src, srcOffset, dst, dstOffset, count);
return;
}
if (src == null) throw new ArgumentNullException(nameof(src));
if (dst == null) throw new ArgumentNullException(nameof(dst));
if (count < 0 || srcOffset < 0 || dstOffset < 0) throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0) return;
if (srcOffset + count > src.Length) throw new ArgumentException(nameof(src));
if (dstOffset + count > dst.Length) throw new ArgumentException(nameof(dst));
while (count >= _vectorSpan4)
{
new Vector<byte>(src, srcOffset).CopyTo(dst, dstOffset);
new Vector<byte>(src, srcOffset + _vectorSpan).CopyTo(dst, dstOffset + _vectorSpan);
new Vector<byte>(src, srcOffset + _vectorSpan2).CopyTo(dst, dstOffset + _vectorSpan2);
new Vector<byte>(src, srcOffset + _vectorSpan3).CopyTo(dst, dstOffset + _vectorSpan3);
if (count == _vectorSpan4) return;
count -= _vectorSpan4;
srcOffset += _vectorSpan4;
dstOffset += _vectorSpan4;
}
if (count >= _vectorSpan2)
{
new Vector<byte>(src, srcOffset).CopyTo(dst, dstOffset);
new Vector<byte>(src, srcOffset + _vectorSpan).CopyTo(dst, dstOffset + _vectorSpan);
if (count == _vectorSpan2) return;
count -= _vectorSpan2;
srcOffset += _vectorSpan2;
dstOffset += _vectorSpan2;
}
if (count >= _vectorSpan)
{
new Vector<byte>(src, srcOffset).CopyTo(dst, dstOffset);
if (count == _vectorSpan) return;
count -= _vectorSpan;
srcOffset += _vectorSpan;
dstOffset += _vectorSpan;
}
if (count > 0)
{
fixed (byte* srcOrigin = src)
fixed (byte* dstOrigin = dst)
{
var pSrc = srcOrigin + srcOffset;
var dSrc = dstOrigin + dstOffset;
if (count >= _longSpan)
{
var lpSrc = (long*)pSrc;
var ldSrc = (long*)dSrc;
if (count < _longSpan2)
{
count -= _longSpan;
pSrc += _longSpan;
dSrc += _longSpan;
*ldSrc = *lpSrc;
}
else if (count < _longSpan3)
{
count -= _longSpan2;
pSrc += _longSpan2;
dSrc += _longSpan2;
*ldSrc = *lpSrc;
*(ldSrc + 1) = *(lpSrc + 1);
}
else
{
count -= _longSpan3;
pSrc += _longSpan3;
dSrc += _longSpan3;
*ldSrc = *lpSrc;
*(ldSrc + 1) = *(lpSrc + 1);
*(ldSrc + 2) = *(lpSrc + 2);
}
}
if (count >= _intSpan)
{
var ipSrc = (int*)pSrc;
var idSrc = (int*)dSrc;
count -= _intSpan;
pSrc += _intSpan;
dSrc += _intSpan;
*idSrc = *ipSrc;
}
while (count > 0)
{
count--;
*dSrc = *pSrc;
dSrc += 1;
pSrc += 1;
}
}
}
#if !DEBUG
}
else
{
Array.Copy(src, srcOffset, dst, dstOffset, count);
return;
}
#endif
}
}
} | IllyriadGames/ByteArrayExtensions | src/IllyriadGames.ByteArrayExtensions/VectorizedCopyExtension.cs | C# | apache-2.0 | 7,465 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
#if USE_FASTQUANT
namespace FastQuant.Tests
#else
namespace SmartQuant.Tests
#endif
{
public class TickSeriesTest
{
[Fact]
public void TestGetIndex()
{
var ts = new TickSeries("test");
for (int i = 0; i < 10; ++i)
ts.Add(new Tick { DateTime = new DateTime(2000, 1, 1, 10, i, 30) });
var firstDt = new DateTime(2000, 1, 1, 10, 3, 30);
var firstTick = new Tick { DateTime = firstDt };
var lastDt = new DateTime(2000, 1, 1, 10, 9, 30);
var lastTick = new Tick { DateTime = lastDt };
// DateTime is in the middle;
Assert.Equal(3, ts.GetIndex(firstDt, IndexOption.Null));
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Null));
Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Null));
Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Prev));
Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Next));
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Null));
Assert.Equal(3, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Prev));
Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Next));
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Null));
Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Prev));
Assert.Equal(5, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Next));
// DateTime > LastDateTime
Assert.Equal(5, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Next));
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Null));
Assert.Equal(9, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Prev));
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Next));
// DateTime < FirstDateTime
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Null));
Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Prev));
Assert.Equal(0, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Next));
}
}
}
| fastquant/fastquant.dll | test/FastQuant.Tests.Shared/TickSeriesTest.cs | C# | apache-2.0 | 2,582 |
package com.sectong.util;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
private static Logger logger = Logger.getLogger(HttpUtil.class);
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
public static String postData(String urlStr, String data, String contentType){
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if(contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if(data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
}
| xaioyi/yidongyiljwj | src/main/java/com/sectong/util/HttpUtil.java | Java | apache-2.0 | 1,988 |
set AUTH_TOKEN=123456& ^
set HTTP_PORT=8080& ^
set MQTT_URL=mqtt://localhost& ^
set MQTT_USER=user ^
set MQTT_PASS=pass ^
set DOMAIN=infra& ^
set TLD=ictu& ^
set SCRIPT_BASE_DIR=X:\mnt\data\scripts& ^
set DATA_DIR=X:\mnt\data& ^
set PIPEWORKS_CMD=eth0 -i eth0 @CONTAINER_NAME@ dhclient& ^
nodemon index.coffee
| ICTU/docker-dashboard-agent-compose | run-dev.bat | Batchfile | apache-2.0 | 310 |
# AUTOGENERATED FILE
FROM balenalib/qemux86-64-alpine:3.13-run
ENV GO_VERSION 1.16.3
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-amd64.tar.gz" \
&& echo "10d1c63534be387026f37a3ac3ed00c7258dfbc3ed40255956bc736cf8b3bf3b go$GO_VERSION.linux-alpine-amd64.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-amd64.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-amd64.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@golang" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Alpine Linux 3.13 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.3 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/golang/qemux86-64/alpine/3.13/1.16.3/run/Dockerfile | Dockerfile | apache-2.0 | 2,474 |
'use strict';
viewModel.MonitoringAlarm = new Object();
var ma = viewModel.MonitoringAlarm;
ma.minDatetemp = new Date();
ma.maxDatetemp = new Date();
ma.minDateRet = new Date();
ma.maxDateRet = new Date();
vm.currentMenu('Alarm Data');
vm.currentTitle('Alarm Data');
vm.isShowDataAvailability(false);
vm.breadcrumb([
{ title: "Monitoring", href: '#' },
{ title: 'Alarm Data', href: viewModel.appName + 'page/monitoringalarm' }]);
var intervalTurbine = null;
ma.UpdateProjectList = function(project) {
setTimeout(function(){
$('#projectList').data('kendoDropDownList').value(project);
$("#projectList").data("kendoDropDownList").trigger("change");
},1000)
}
ma.UpdateTurbineList = function(turbineList) {
if(turbineList.length == 0){
$("#turbineList").multiselect('selectAll', false).multiselect("refresh");
}else{
$('#turbineList').multiselect("deselectAll", false).multiselect("refresh");
$('#turbineList').multiselect('select', turbineList);
}
}
ma.CreateGrid = function(gridType) {
app.loading(true);
$.when(fa.LoadData()).done(function () {
var COOKIES = {};
var cookieStr = document.cookie;
var param = {
period: fa.period,
dateStart: fa.dateStart,
dateEnd: fa.dateEnd,
turbine: [],
project: "",
tipe: gridType,
};
if(localStorage.getItem("projectname") !== null && localStorage.getItem("turbine") !== null) {
var locTurbine = localStorage.getItem("turbine");
param.turbine = locTurbine == "" ? [] : [locTurbine];
param.project = localStorage.getItem("projectname");
var tabActive = localStorage.getItem("tabActive");
$.when(ma.UpdateProjectList(param.project)).done(function () {
setTimeout(function(){
ma.UpdateTurbineList(param.turbine);
setTimeout(function() {
ma.LoadDataAvail(param.project, gridType);
if(tabActive !== null){
if(tabActive == "alarmRaw" ){
$("#alarmrawTab a:first-child").trigger('click');
}else{
ma.CreateGridAlarm(gridType, param);
}
}
},500);
app.resetLocalStorage();
}, 1500);
});
} else {
param.turbine = fa.turbine();
param.project = fa.project;
ma.CreateGridAlarm(gridType, param);
}
});
}
ma.buildParentFilter = function(filters, additionalFilter) {
$.each(filters, function(idx, val){
if(val.filter !== undefined) {
ma.buildParentFilter(val.filter.filters, additionalFilter)
}
additionalFilter.push(val);
});
}
ma.CreateGridAlarm = function(gridType, param) {
var gridName = "#alarmGrid"
var dt = new Date();
var time = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds();
var nameFile = "Monitoring Alarm Down_"+ moment(new Date()).format("Y-M-D")+"_"+time;
var defaultsort = [ { field: "TimeStart", dir: "desc" }, { field: "TimeEnd", dir: "asc" } ]
var url = viewModel.appName + "monitoringrealtime/getdataalarm";
if(gridType == "warning") {
gridName = "#warningGrid"
nameFile = "Monitoring Alarm Warning";
}
if(gridType == "alarmraw"){
gridName = "#alarmRawGrid"
nameFile = "Monitoring Alarm Raw";
defaultsort = [ { field: "TimeStamp", dir: "desc" } ]
}
var columns = [{
field: "turbine",
title: "Turbine",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 90
}, {
field: "timestart",
title: "Time Start",
width: 170,
filterable: false,
attributes: {
style: "text-align:center;"
},
template: "#= moment.utc(data.timestart).format('DD-MMM-YYYY') # #=moment.utc(data.timestart).format('HH:mm:ss')#"
}, {
field: "timeend",
title: "Time End",
width: 170,
filterable: false,
attributes: {
style: "text-align:center;"
},
template: "#= (moment.utc(data.timeend).format('DD-MM-YYYY') == '01-01-0001'?'Not yet finished' : (moment.utc(data.timeend).format('DD-MMM-YYYY') # #=moment.utc(data.timeend).format('HH:mm:ss')))#"
}, {
field: "duration",
title: "Duration (hh:mm:ss)",
width: 120,
attributes: {
style: "text-align:center;"
},
filterable: false,
//template: "#= time(data.duration) #"
template: '#= kendo.toString(secondsToTime(data.duration)) #',
}, {
field: "alarmcode",
title: "Alarm Code",
attributes: {
style: "text-align:center;"
},
filterable: {
operators: {
string: {
eq: "Is equal to"
}
},
ui: function(element) {
var form = element.closest("form");
form.find(".k-filter-help-text:first").text("Show items equal to:");
form.find("select").remove();
$("form").find("[data-bind='value:filters[0].value']").addClass('k-textbox');
}
},
width: 90,
},{
field: "alarmdesc",
title: "Description",
width: 330,
}];
if(gridType == "alarm"){
columns.push({
field: "reduceavailability",
title: "Reduce Avail.",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 90,
});
}
if(gridType == "alarmraw"){
columns = [{
field: "turbine",
title: "Turbine",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 70
}, {
field: "timestamp",
title: "Timestamp",
width: 120,
attributes: {
style: "text-align:center;"
},
filterable: false,
template: "#= moment.utc(data.timestamp).format('DD-MMM-YYYY') # #=moment.utc(data.timestamp).format('HH:mm:ss')#"
}, {
field: "tag",
title: "Tag",
width: 120,
filterable: false,
attributes: {
style: "text-align:center;"
},
}, {
field: "value",
title: "Value",
attributes: {
style: "text-align:center;"
},
filterable: false,
width: 70,
// template: "#= kendo.toString(data.Timestamp,'n2') #"
}, {
field: "description",
title: "Description",
width: 200
}, {
field: "addinfo",
title: "Note",
filterable: false,
width: 250
}];
}
$(gridName).html('');
$(gridName).kendoGrid({
dataSource: {
serverPaging: true,
serverSorting: true,
serverFiltering: true,
transport: {
read: {
url: url,
type: "POST",
data: param,
dataType: "json",
contentType: "application/json; charset=utf-8",
},
parameterMap: function(options) {
var additionalFilter = [];
if(options.filter !== undefined && options.filter != null) {
ma.buildParentFilter(options.filter.filters, additionalFilter)
}
if (additionalFilter.length > 0) {
options["filter"] = additionalFilter;
}
return JSON.stringify(options);
}
},
schema: {
data: function data(res) {
if (!app.isFine(res)) {
return;
}
var totalFreq = res.data.Total;
var totalHour = res.data.Duration;
ma.minDateRet = new Date(res.data.mindate);
ma.maxDateRet = new Date(res.data.maxdate);
ma.checkCompleteDate()
$('#alarm_duration').text((totalHour/3600).toFixed(2));
$('#alarm_frequency').text(totalFreq);
setTimeout(function(){
app.loading(false);
}, 300)
return res.data.Data;
},
total: function data(res) {
return res.data.Total;
}
},
pageSize: 10,
sort: defaultsort,
},
// toolbar: ["excel"],
excel: {
fileName: nameFile+".xlsx",
filterable: true,
allPages: true
},
// pdf: {
// fileName: nameFile+".pdf",
// },
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
eq: "Is equal to"
},
}
},
columns: columns
});
};
function secondsToTime(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var res = (h > 0 ? (h < 10 ? "0" + h : h) : "00") + ":" + (m > 0 ? (m < 10 ? "0" + m : m) : "00") + ":" + (s > 0 ? s : "00")
return res;
}
function time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
ma.InitDateValue = function () {
var maxDateData = new Date();
var lastStartDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
var lastEndDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
$('#dateStart').data('kendoDatePicker').value(lastStartDate);
$('#dateEnd').data('kendoDatePicker').value(lastEndDate);
}
ma.LoadDataAvail = function(projectname, gridType){
//fa.LoadData();
var payload = {
project: projectname,
tipe: gridType
};
toolkit.ajaxPost(viewModel.appName + "monitoringrealtime/getdataalarmavaildate", payload, function (res) {
if (!app.isFine(res)) {
return;
}
if (res.data.Data.length == 0) {
res.data.Data = [];
} else {
if (res.data.Data.length > 0) {
ma.minDatetemp = new Date(res.data.Data[0]);
ma.maxDatetemp = new Date(res.data.Data[1]);
app.currentDateData = new Date(res.data.Data[1]);
$('#availabledatestart').html(kendo.toString(moment.utc(ma.minDatetemp).format('DD-MMMM-YYYY')));
$('#availabledateend').html(kendo.toString(moment.utc(ma.maxDatetemp).format('DD-MMMM-YYYY')));
// $('#dateStart').data('kendoDatePicker').value( new Date(Date.UTC(moment( ma.maxDatetemp).get('year'), ma.maxDatetemp.getMonth(), ma.maxDatetemp.getDate() - 7, 0, 0, 0, 0)));
// $('#dateEnd').data('kendoDatePicker').value(kendo.toString(moment.utc(res.data.Data[1]).format('DD-MMM-YYYY')));
ma.checkCompleteDate();
}
}
});
}
ma.checkCompleteDate = function () {
var currentDateData = moment.utc(ma.maxDatetemp).format('YYYY-MM-DD');
var prevDateData = moment.utc(ma.minDatetemp).format('YYYY-MM-DD');
var dateStart = moment.utc(ma.minDateRet).format('YYYY-MM-DD');
var dateEnd = moment.utc(ma.maxDateRet).format('YYYY-MM-DD');
if ((dateEnd > currentDateData) || (dateStart > currentDateData)) {
fa.infoPeriodIcon(true);
} else if ((dateEnd < prevDateData) || (dateStart < prevDateData)) {
fa.infoPeriodIcon(true);
} else {
fa.infoPeriodIcon(false);
fa.infoPeriodRange("");
}
}
ma.ToByProject = function(){
setTimeout(function(){
app.loading(true);
app.resetLocalStorage();
var project = $('#projectList').data('kendoDropDownList').value();
localStorage.setItem('projectname', project);
if(localStorage.getItem("projectname")){
window.location = viewModel.appName + "page/monitoringbyproject";
}
},1500);
}
ma.exportToExcel = function(id){
$("#"+id).getKendoGrid().saveAsExcel();
}
$(document).ready(function(){
$('#btnRefresh').on('click', function () {
fa.checkTurbine();
if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Down") {
ma.CreateGrid("alarm");
} else if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Warning") {
ma.CreateGrid("warning");
}else{
ma.CreateGrid("alarmraw");
}
});
//setTimeout(function() {
$.when(ma.InitDateValue()).done(function () {
setTimeout(function() {
ma.CreateGrid("alarm");
ma.LoadDataAvail(fa.project, "alarm");
}, 100);
});
//}, 300);
$('#projectList').kendoDropDownList({
change: function () {
var project = $('#projectList').data("kendoDropDownList").value();
fa.populateTurbine(project);
ma.LoadDataAvail(project, "alarm");
}
});
});
| eaciit/windapp | web/assets/core/js/page-monitoring/monitoring-alarm.js | JavaScript | apache-2.0 | 14,310 |
/*
* Copyright 2015 Matthew Timmermans
*
* 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.nobigsoftware.dfalex;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import static backport.java.util.function.BackportFuncs.computeIfAbsent;
/**
* Turns an NFA into a non-minimal RawDfa by powerset construction
*/
class DfaFromNfa<RESULT> {
//inputs
private final Nfa<RESULT> m_nfa;
private final int[] m_nfaStartStates;
private final int[] m_dfaStartStates;
private final DfaAmbiguityResolver<? super RESULT> m_ambiguityResolver;
//utility
private final DfaStateSignatureCodec m_dfaSigCodec = new DfaStateSignatureCodec();
//These fields are scratch space
private final IntListKey m_tempStateSignature = new IntListKey();
private final ArrayDeque<Integer> m_tempNfaClosureList = new ArrayDeque<>();
private final HashSet<RESULT> m_tempResultSet = new HashSet<RESULT>();
//accumulators
private final HashMap<RESULT, Integer> m_acceptSetMap = new HashMap<>();
private final ArrayList<RESULT> m_acceptSets = new ArrayList<>();
private final HashMap<IntListKey, Integer> m_dfaStateSignatureMap = new HashMap<>();
private final ArrayList<IntListKey> m_dfaStateSignatures = new ArrayList<>();
private final ArrayList<DfaStateInfo> m_dfaStates = new ArrayList<>();
public DfaFromNfa(Nfa<RESULT> nfa, int[] nfaStartStates,
DfaAmbiguityResolver<? super RESULT> ambiguityResolver) {
m_nfa = nfa;
m_nfaStartStates = nfaStartStates;
m_dfaStartStates = new int[nfaStartStates.length];
m_ambiguityResolver = ambiguityResolver;
m_acceptSets.add(null);
_build();
}
public RawDfa<RESULT> getDfa() {
return new RawDfa<>(m_dfaStates, m_acceptSets, m_dfaStartStates);
}
private void _build() {
final CompactIntSubset nfaStateSet = new CompactIntSubset(m_nfa.numStates());
final ArrayList<NfaTransition> dfaStateTransitions = new ArrayList<>();
final ArrayList<NfaTransition> transitionQ = new ArrayList<>(1000);
//Create the DFA start states
for (int i = 0; i < m_dfaStartStates.length; ++i) {
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, m_nfaStartStates[i]);
m_dfaStartStates[i] = _getDfaState(nfaStateSet);
}
//Create the transitions and other DFA states.
//m_dfaStateSignatures grows as we discover new states.
//m_dfaStates grows as we complete them
for (int stateNum = 0; stateNum < m_dfaStateSignatures.size(); ++stateNum) {
final IntListKey dfaStateSig = m_dfaStateSignatures.get(stateNum);
dfaStateTransitions.clear();
//For each DFA state, combine the NFA transitions for each
//distinct character range into a DFA transiton, appending new DFA states
//as we discover them.
transitionQ.clear();
//dump all the NFA transitions for the state into the Q
DfaStateSignatureCodec.expand(dfaStateSig,
state -> m_nfa.forStateTransitions(state, transitionQ::add));
//sort all the transitions by first character
Collections.sort(transitionQ, (arg0, arg1) -> {
if (arg0.m_firstChar != arg1.m_firstChar) {
return (arg0.m_firstChar < arg1.m_firstChar ? -1 : 1);
}
return 0;
});
final int tqlen = transitionQ.size();
//first character we haven't accounted for yet
char minc = 0;
//NFA transitions at index < tqstart are no longer relevant
//NFA transitions at index >= tqstart are in first char order OR have first char <= minc
//The sequence of NFA transitions contributing the the previous DFA transition starts here
int tqstart = 0;
//make a range of NFA transitions corresponding to the next DFA transition
while (tqstart < tqlen) {
NfaTransition trans = transitionQ.get(tqstart);
if (trans.m_lastChar < minc) {
++tqstart;
continue;
}
//INVAR - trans contributes to the next DFA transition
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
char startc = trans.m_firstChar;
char endc = trans.m_lastChar;
if (startc < minc) {
startc = minc;
}
//make range of all transitions that include the start character, removing ones
//that drop out
for (int tqend = tqstart + 1; tqend < tqlen; ++tqend) {
trans = transitionQ.get(tqend);
if (trans.m_lastChar < startc) {
//remove this one
transitionQ.set(tqend, transitionQ.get(tqstart++));
continue;
}
if (trans.m_firstChar > startc) {
//this one is for the next transition
if (trans.m_firstChar <= endc) {
endc = (char) (trans.m_firstChar - 1);
}
break;
}
//this one counts
if (trans.m_lastChar < endc) {
endc = trans.m_lastChar;
}
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
}
dfaStateTransitions.add(new NfaTransition(startc, endc, _getDfaState(nfaStateSet)));
minc = (char) (endc + 1);
if (minc < endc) {
//wrapped around
break;
}
}
//INVARIANT: m_dfaStatesOut.size() == stateNum
m_dfaStates.add(_createStateInfo(dfaStateSig, dfaStateTransitions));
}
}
//Add an NFA state to m_currentNFASubset, along with the transitive
//closure over its epsilon transitions
private void _addNfaStateAndEpsilonsToSubset(CompactIntSubset dest, int stateNum) {
m_tempNfaClosureList.clear();
if (dest.add(stateNum)) {
m_tempNfaClosureList.add(stateNum);
}
Integer newNfaState;
while ((newNfaState = m_tempNfaClosureList.poll()) != null) {
m_nfa.forStateEpsilons(newNfaState, (Integer src) -> {
if (dest.add(src)) {
m_tempNfaClosureList.add(src);
}
});
}
}
private void _addNfaStateToSignatureCodec(int stateNum) {
if (m_nfa.hasTransitionsOrAccepts(stateNum)) {
m_dfaSigCodec.acceptInt(stateNum);
}
}
//Make a DFA state for a set of simultaneous NFA states
private Integer _getDfaState(CompactIntSubset nfaStateSet) {
//dump state combination into compressed form
m_tempStateSignature.clear();
m_dfaSigCodec.start(m_tempStateSignature::add, nfaStateSet.getSize(),
nfaStateSet.getRange());
nfaStateSet.dumpInOrder(this::_addNfaStateToSignatureCodec);
m_dfaSigCodec.finish();
//make sure it's in the map
Integer dfaStateNum = m_dfaStateSignatureMap.get(m_tempStateSignature);
if (dfaStateNum == null) {
dfaStateNum = m_dfaStateSignatures.size();
IntListKey newSig = new IntListKey(m_tempStateSignature);
m_dfaStateSignatures.add(newSig);
m_dfaStateSignatureMap.put(newSig, dfaStateNum);
}
return dfaStateNum;
}
@SuppressWarnings("unchecked")
private DfaStateInfo _createStateInfo(IntListKey sig, List<NfaTransition> transitions) {
//calculate the set of accepts
m_tempResultSet.clear();
DfaStateSignatureCodec.expand(sig, nfastate -> {
RESULT accept = m_nfa.getAccept(nfastate);
if (accept != null) {
m_tempResultSet.add(accept);
}
});
//and get an accept set index for it
RESULT dfaAccept = null;
if (m_tempResultSet.size() > 1) {
dfaAccept = (RESULT) m_ambiguityResolver.apply(m_tempResultSet);
} else if (!m_tempResultSet.isEmpty()) {
dfaAccept = m_tempResultSet.iterator().next();
}
int acceptSetIndex = 0;
if (dfaAccept != null) {
acceptSetIndex = computeIfAbsent(m_acceptSetMap, dfaAccept, keyset -> {
m_acceptSets.add(keyset);
return m_acceptSets.size() - 1;
});
}
return new DfaStateInfo(transitions, acceptSetIndex);
}
}
| 6thsolution/ApexNLP | dfalex/src/main/java/com/nobigsoftware/dfalex/DfaFromNfa.java | Java | apache-2.0 | 9,517 |
package com.emc.ecs.servicebroker.repository;
import com.emc.ecs.servicebroker.exception.EcsManagementClientException;
import com.emc.ecs.servicebroker.service.s3.S3Service;
import com.emc.ecs.servicebroker.model.Constants;
import com.emc.object.s3.bean.GetObjectResult;
import com.emc.object.s3.bean.ListObjectsResult;
import com.emc.object.s3.bean.S3Object;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.servicebroker.model.binding.SharedVolumeDevice;
import org.springframework.cloud.servicebroker.model.binding.VolumeDevice;
import org.springframework.cloud.servicebroker.model.binding.VolumeMount;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
@SuppressWarnings("unused")
public class ServiceInstanceBindingRepository {
static final Logger logger = LoggerFactory.getLogger(ServiceInstanceBindingRepository.class);
public static final String FILENAME_PREFIX = "service-instance-binding";
private final ObjectMapper objectMapper = new ObjectMapper();
{
// NOTE -- ideally we would not need this code, but for now, the VolumeMount class has
// custom serialization that is not matched with corresponding deserialization, so
// deserializing serialized volume mounts doesn't work OOTB.
SimpleModule module = new SimpleModule();
module.addDeserializer(VolumeMount.DeviceType.class, new DeviceTypeDeserializer());
module.addDeserializer(VolumeMount.Mode.class, new ModeDeserializer());
module.addDeserializer(VolumeDevice.class, new VolumeDeviceDeserializer());
objectMapper.registerModule(module);
}
@Autowired
private S3Service s3;
private static String getFilename(String id) {
return FILENAME_PREFIX + "/" + id + ".json";
}
private static boolean isCorrectFilename (String filename) {
return filename.matches(FILENAME_PREFIX + "/.*\\.json");
}
private ServiceInstanceBinding findByFilename(String filename) throws IOException {
if (!isCorrectFilename(filename)) {
String errorMessage = format("Invalid filename of service instance binding provided: %s", filename);
throw new IOException(errorMessage);
}
logger.debug("Loading service instance binding from repository file {}", filename);
GetObjectResult<InputStream> input = s3.getObject(filename);
return objectMapper.readValue(input.getObject(), ServiceInstanceBinding.class);
}
ServiceInstanceBinding removeSecretCredentials(ServiceInstanceBinding binding) {
Map<String, Object> credentials = binding.getCredentials();
credentials.remove(Constants.S3_URL);
credentials.remove(Constants.CREDENTIALS_SECRET_KEY);
binding.setCredentials(credentials);
return binding;
}
@PostConstruct
public void initialize() throws EcsManagementClientException {
logger.info("Service binding file prefix: {}", FILENAME_PREFIX);
}
public void save(ServiceInstanceBinding binding) throws IOException {
String filename = getFilename(binding.getBindingId());
String serialized = objectMapper.writeValueAsString(binding);
s3.putObject(filename, serialized);
}
public ServiceInstanceBinding find(String id) throws IOException {
String filename = getFilename(id);
return findByFilename(filename);
}
public ListServiceInstanceBindingsResponse listServiceInstanceBindings(String marker, int pageSize) throws IOException {
if (pageSize < 0) {
throw new IOException("Page size could not be negative number");
}
List<ServiceInstanceBinding> bindings = new ArrayList<>();
ListObjectsResult list = marker != null ?
s3.listObjects(FILENAME_PREFIX + "/", getFilename(marker), pageSize) :
s3.listObjects(FILENAME_PREFIX + "/", null, pageSize);
for (S3Object s3Object: list.getObjects()) {
String filename = s3Object.getKey();
if (isCorrectFilename(filename)) {
ServiceInstanceBinding binding = findByFilename(filename);
bindings.add(removeSecretCredentials(binding));
}
}
ListServiceInstanceBindingsResponse response = new ListServiceInstanceBindingsResponse(bindings);
response.setMarker(list.getMarker());
response.setPageSize(list.getMaxKeys());
response.setNextMarker(list.getNextMarker());
return response;
}
public void delete(String id) {
String filename = getFilename(id);
s3.deleteObject(filename);
}
public static class ModeDeserializer extends StdDeserializer<VolumeMount.Mode> {
ModeDeserializer() {
this(null);
}
ModeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeMount.Mode deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
String s = node.asText();
if (s.equals("rw")) {
return VolumeMount.Mode.READ_WRITE;
} else {
return VolumeMount.Mode.READ_ONLY;
}
}
}
public static class DeviceTypeDeserializer extends StdDeserializer<VolumeMount.DeviceType> {
DeviceTypeDeserializer() {
this(null);
}
DeviceTypeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeMount.DeviceType deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return VolumeMount.DeviceType.SHARED;
}
}
public static class VolumeDeviceDeserializer extends StdDeserializer<VolumeDevice> {
VolumeDeviceDeserializer() {
this(null);
}
VolumeDeviceDeserializer(Class<?> vc) {
super(vc);
}
@Override
public VolumeDevice deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return jp.getCodec().readValue(jp, SharedVolumeDevice.class);
}
}
} | emccode/ecs-cf-service-broker | src/main/java/com/emc/ecs/servicebroker/repository/ServiceInstanceBindingRepository.java | Java | apache-2.0 | 6,740 |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>RepositoryAttribute Constructor (String)</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">RepositoryAttribute Constructor (String)</h1>
</div>
</div>
<div id="nstext">
<p> Initialize a new instance of the <a href="log4net.Config.RepositoryAttribute.html">RepositoryAttribute</a> class with the name of the repository. </p>
<div class="syntax">
<span class="lang">[Visual Basic]</span>
<br />Overloads Public Sub New( _<br /> ByVal <i>name</i> As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">String</a> _<br />)</div>
<div class="syntax">
<span class="lang">[C#]</span>
<br />public RepositoryAttribute(<br /> <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">string</a> <i>name</i><br />);</div>
<h4 class="dtH4">Parameters</h4>
<dl>
<dt>
<i>name</i>
</dt>
<dd>The name of the repository.</dd>
</dl>
<h4 class="dtH4">Remarks</h4>
<p> Initialize the attribute with the name for the assembly's repository. </p>
<h4 class="dtH4">See Also</h4><p><a href="log4net.Config.RepositoryAttribute.html">RepositoryAttribute Class</a> | <a href="log4net.Config.html">log4net.Config Namespace</a> | <a href="log4net.Config.RepositoryAttributeConstructor.html">RepositoryAttribute Constructor Overload List</a></p><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div>
</body>
</html> | gersonkurz/manualisator | manualisator/log4net-1.2.13/doc/release/sdk/log4net.Config.RepositoryAttributeConstructor2.html | HTML | apache-2.0 | 2,398 |
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function, division
| dawncold/expenditure-application | expenditure_application/__init__.py | Python | apache-2.0 | 90 |
/*
* Copyright (c) 2016 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.kinesistee.config
import java.util
import awscala.dynamodbv2.{AttributeValue, DynamoDB}
import com.amazonaws.services.dynamodbv2.model.{QueryRequest, QueryResult}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
class ConfigurationBuilderSpec extends Specification with Mockito {
val sampleGoodConfig = scala.io.Source.fromURL(getClass.getResource("/sample_self_describing_config.json")).mkString
val sampleConfig = Configuration(name = "My Kinesis Tee example",
targetStream = TargetStream("my-target-stream", None),
transformer = Some(Transformer(BuiltIn.SNOWPLOW_TO_NESTED_JSON)),
filter = None)
"A valid configuration" should {
"generate the correct case class" in {
ConfigurationBuilder.build(sampleGoodConfig) mustEqual sampleConfig
}
}
"An invalid JSON configuration" should {
"throw an exception" in {
ConfigurationBuilder.build("banana") must throwA[IllegalArgumentException]
}
}
"A configuration that doesn't match the given schema" should {
"throw an exception" in {
ConfigurationBuilder.build(
"""
|{
| "schema": "com.thing",
| "data": { "foo":"bar" }
|}
""".stripMargin) must throwA(new IllegalArgumentException("Invalid configuration"))
}
}
"Loading from DynamoDB" should {
val sampleConfigTableName = "config-table-sample-name"
"load a configuration using dynamodb and the specified table name" in {
implicit val dynamoDB = mock[DynamoDB]
val res = mock[QueryResult]
val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList()
val one:util.Map[String,com.amazonaws.services.dynamodbv2.model.AttributeValue] = new util.HashMap()
one.put("id", new AttributeValue(Some("with-id")))
one.put("configuration", new AttributeValue(Some(sampleGoodConfig)))
items.add(one)
res.getItems returns items
dynamoDB.query(any[QueryRequest]) returns res
ConfigurationBuilder.build(sampleConfigTableName, "with-id") mustEqual sampleConfig
}
"give a good error if the table doesn't have a matching entry" in {
implicit val dynamoDB = mock[DynamoDB]
val res = mock[QueryResult]
val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList()
res.getItems returns items
dynamoDB.query(any[QueryRequest]) returns res
ConfigurationBuilder.build(sampleConfigTableName, "with-id") must throwA(new IllegalStateException(s"No configuration in table '$sampleConfigTableName' for lambda 'with-id'!"))
}
"give a good error if the table doesn't have the right keys (id and configuration)" in {
implicit val dynamoDB = mock[DynamoDB]
val res = mock[QueryResult]
val items:util.List[java.util.Map[java.lang.String,com.amazonaws.services.dynamodbv2.model.AttributeValue]] = new util.ArrayList()
val one:util.Map[String,com.amazonaws.services.dynamodbv2.model.AttributeValue] = new util.HashMap()
one.put("id", new AttributeValue(Some("with-id")))
one.put("this-is-not-config", new AttributeValue(Some("abc")))
items.add(one)
res.getItems returns items
dynamoDB.query(any[QueryRequest]) returns res
ConfigurationBuilder.build(sampleConfigTableName, "with-id") must throwA(new IllegalStateException(s"Config table '${sampleConfigTableName}' for lambda 'with-id' is missing a 'configuration' field!"))
}
"do something reasonable if ddb errors" in {
implicit val dynamoDB = mock[DynamoDB]
val exception = new IllegalArgumentException("Query exploded")
dynamoDB.query(any[QueryRequest]) throws exception
// NB IllegalArgumentException is rethrown as IllegalStateException
ConfigurationBuilder.build(sampleConfigTableName, "with-id") must throwA[IllegalStateException](message = "Query exploded")
}
}
}
| snowplow/kinesis-tee | src/test/scala/com/snowplowanalytics/kinesistee/config/ConfigurationBuilderSpec.scala | Scala | apache-2.0 | 4,846 |
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
2011,2012,2013,2014 Giovanni Di Sirio.
This file is part of ChibiOS/RT.
ChibiOS/RT is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
ChibiOS/RT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file chheap.c
* @brief Heaps code.
*
* @addtogroup heaps
* @details Heap Allocator related APIs.
* <h2>Operation mode</h2>
* The heap allocator implements a first-fit strategy and its APIs
* are functionally equivalent to the usual @p malloc() and @p free()
* library functions. The main difference is that the OS heap APIs
* are guaranteed to be thread safe.<br>
* @pre In order to use the heap APIs the @p CH_CFG_USE_HEAP option must
* be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_CFG_USE_HEAP || defined(__DOXYGEN__)
/*===========================================================================*/
/* Module local definitions. */
/*===========================================================================*/
/*
* Defaults on the best synchronization mechanism available.
*/
#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
#define H_LOCK(h) chMtxLock(&(h)->h_mtx)
#define H_UNLOCK(h) chMtxUnlock(&(h)->h_mtx)
#else
#define H_LOCK(h) chSemWait(&(h)->h_sem)
#define H_UNLOCK(h) chSemSignal(&(h)->h_sem)
#endif
/*===========================================================================*/
/* Module exported variables. */
/*===========================================================================*/
/*===========================================================================*/
/* Module local types. */
/*===========================================================================*/
/*===========================================================================*/
/* Module local variables. */
/*===========================================================================*/
/**
* @brief Default heap descriptor.
*/
static memory_heap_t default_heap;
/*===========================================================================*/
/* Module local functions. */
/*===========================================================================*/
/*===========================================================================*/
/* Module exported functions. */
/*===========================================================================*/
/**
* @brief Initializes the default heap.
*
* @notapi
*/
void _heap_init(void) {
default_heap.h_provider = chCoreAlloc;
default_heap.h_free.h.u.next = (union heap_header *)NULL;
default_heap.h_free.h.size = 0;
#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
chMtxObjectInit(&default_heap.h_mtx);
#else
chSemObjectInit(&default_heap.h_sem, 1);
#endif
}
/**
* @brief Initializes a memory heap from a static memory area.
* @pre Both the heap buffer base and the heap size must be aligned to
* the @p stkalign_t type size.
*
* @param[out] heapp pointer to the memory heap descriptor to be initialized
* @param[in] buf heap buffer base
* @param[in] size heap size
*
* @init
*/
void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size) {
union heap_header *hp;
chDbgCheck(MEM_IS_ALIGNED(buf) && MEM_IS_ALIGNED(size));
heapp->h_provider = (memgetfunc_t)NULL;
heapp->h_free.h.u.next = hp = buf;
heapp->h_free.h.size = 0;
hp->h.u.next = NULL;
hp->h.size = size - sizeof(union heap_header);
#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
chMtxObjectInit(&heapp->h_mtx);
#else
chSemObjectInit(&heapp->h_sem, 1);
#endif
}
/**
* @brief Allocates a block of memory from the heap by using the first-fit
* algorithm.
* @details The allocated block is guaranteed to be properly aligned for a
* pointer data type (@p stkalign_t).
*
* @param[in] heapp pointer to a heap descriptor or @p NULL in order to
* access the default heap.
* @param[in] size the size of the block to be allocated. Note that the
* allocated block may be a bit bigger than the requested
* size for alignment and fragmentation reasons.
* @return A pointer to the allocated block.
* @retval NULL if the block cannot be allocated.
*
* @api
*/
void *chHeapAlloc(memory_heap_t *heapp, size_t size) {
union heap_header *qp, *hp, *fp;
if (heapp == NULL)
heapp = &default_heap;
size = MEM_ALIGN_NEXT(size);
qp = &heapp->h_free;
H_LOCK(heapp);
while (qp->h.u.next != NULL) {
hp = qp->h.u.next;
if (hp->h.size >= size) {
if (hp->h.size < size + sizeof(union heap_header)) {
/* Gets the whole block even if it is slightly bigger than the
requested size because the fragment would be too small to be
useful.*/
qp->h.u.next = hp->h.u.next;
}
else {
/* Block bigger enough, must split it.*/
fp = (void *)((uint8_t *)(hp) + sizeof(union heap_header) + size);
fp->h.u.next = hp->h.u.next;
fp->h.size = hp->h.size - sizeof(union heap_header) - size;
qp->h.u.next = fp;
hp->h.size = size;
}
hp->h.u.heap = heapp;
H_UNLOCK(heapp);
return (void *)(hp + 1);
}
qp = hp;
}
H_UNLOCK(heapp);
/* More memory is required, tries to get it from the associated provider
else fails.*/
if (heapp->h_provider) {
hp = heapp->h_provider(size + sizeof(union heap_header));
if (hp != NULL) {
hp->h.u.heap = heapp;
hp->h.size = size;
hp++;
return (void *)hp;
}
}
return NULL;
}
#define LIMIT(p) (union heap_header *)((uint8_t *)(p) + \
sizeof(union heap_header) + \
(p)->h.size)
/**
* @brief Frees a previously allocated memory block.
*
* @param[in] p pointer to the memory block to be freed
*
* @api
*/
void chHeapFree(void *p) {
union heap_header *qp, *hp;
memory_heap_t *heapp;
chDbgCheck(p != NULL);
hp = (union heap_header *)p - 1;
heapp = hp->h.u.heap;
qp = &heapp->h_free;
H_LOCK(heapp);
while (true) {
chDbgAssert((hp < qp) || (hp >= LIMIT(qp)), "within free block");
if (((qp == &heapp->h_free) || (hp > qp)) &&
((qp->h.u.next == NULL) || (hp < qp->h.u.next))) {
/* Insertion after qp.*/
hp->h.u.next = qp->h.u.next;
qp->h.u.next = hp;
/* Verifies if the newly inserted block should be merged.*/
if (LIMIT(hp) == hp->h.u.next) {
/* Merge with the next block.*/
hp->h.size += hp->h.u.next->h.size + sizeof(union heap_header);
hp->h.u.next = hp->h.u.next->h.u.next;
}
if ((LIMIT(qp) == hp)) {
/* Merge with the previous block.*/
qp->h.size += hp->h.size + sizeof(union heap_header);
qp->h.u.next = hp->h.u.next;
}
break;
}
qp = qp->h.u.next;
}
H_UNLOCK(heapp);
return;
}
/**
* @brief Reports the heap status.
* @note This function is meant to be used in the test suite, it should
* not be really useful for the application code.
*
* @param[in] heapp pointer to a heap descriptor or @p NULL in order to
* access the default heap.
* @param[in] sizep pointer to a variable that will receive the total
* fragmented free space
* @return The number of fragments in the heap.
*
* @api
*/
size_t chHeapStatus(memory_heap_t *heapp, size_t *sizep) {
union heap_header *qp;
size_t n, sz;
if (heapp == NULL)
heapp = &default_heap;
H_LOCK(heapp);
sz = 0;
for (n = 0, qp = &heapp->h_free; qp->h.u.next; n++, qp = qp->h.u.next)
sz += qp->h.u.next->h.size;
if (sizep)
*sizep = sz;
H_UNLOCK(heapp);
return n;
}
#endif /* CH_CFG_USE_HEAP */
/** @} */
| roboknight/chibios-lpc43xx | os/rt/src/chheap.c | C | apache-2.0 | 9,017 |
# Unona fulva Wall. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Magnoliales/Annonaceae/Unona/Unona fulva/README.md | Markdown | apache-2.0 | 167 |
# AUTOGENERATED FILE
FROM balenalib/jetson-tx1-debian:bullseye-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.8.12
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \
&& echo "b04ecc256b15830a76bfcf1a5a4f8b510a10bc094e530df5267cd9e30e9aa955 Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | resin-io-library/base-images | balena-base-images/python/jetson-tx1/debian/bullseye/3.8.12/run/Dockerfile | Dockerfile | apache-2.0 | 4,095 |
char *my_strcpy(char *dest, char *src)
{
char *adrr;
for (adrr = dest; *src; *dest++ = *src++);
*dest++ = '\0';
return (adrr);
}
| Yunori/Fridge-menu | functions/my_strcpy.c | C | apache-2.0 | 138 |
# AUTOGENERATED FILE
FROM balenalib/surface-go-debian:bullseye-build
ENV NODE_VERSION 17.6.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \
&& echo "de9596fda9cc88451d03146278806687e954c03413e8aa0ee98ad46442d6cb1c node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v17.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | resin-io-library/base-images | balena-base-images/node/surface-go/debian/bullseye/17.6.0/build/Dockerfile | Dockerfile | apache-2.0 | 2,786 |
{-# LANGUAGE TemplateHaskell #-}
-- Copyright (C) 2010-2012 John Millikin <[email protected]>
--
-- 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.
module DBusTests.Signature (test_Signature) where
import Test.Chell
import Test.Chell.QuickCheck
import Test.QuickCheck hiding ((.&.), property)
import DBus
import DBusTests.Util
test_Signature :: Suite
test_Signature = suite "Signature"
[ test_BuildSignature
, test_ParseSignature
, test_ParseInvalid
, test_FormatSignature
, test_IsAtom
, test_ShowType
]
test_BuildSignature :: Test
test_BuildSignature = property "signature" prop where
prop = forAll gen_SignatureTypes check
check types = case signature types of
Nothing -> False
Just sig -> signatureTypes sig == types
test_ParseSignature :: Test
test_ParseSignature = property "parseSignature" prop where
prop = forAll gen_SignatureString check
check (s, types) = case parseSignature s of
Nothing -> False
Just sig -> signatureTypes sig == types
test_ParseInvalid :: Test
test_ParseInvalid = assertions "parse-invalid" $ do
-- at most 255 characters
$expect (just (parseSignature (replicate 254 'y')))
$expect (just (parseSignature (replicate 255 'y')))
$expect (nothing (parseSignature (replicate 256 'y')))
-- length also enforced by 'signature'
$expect (just (signature (replicate 255 TypeWord8)))
$expect (nothing (signature (replicate 256 TypeWord8)))
-- struct code
$expect (nothing (parseSignature "r"))
-- empty struct
$expect (nothing (parseSignature "()"))
$expect (nothing (signature [TypeStructure []]))
-- dict code
$expect (nothing (parseSignature "e"))
-- non-atomic dict key
$expect (nothing (parseSignature "a{vy}"))
$expect (nothing (signature [TypeDictionary TypeVariant TypeVariant]))
test_FormatSignature :: Test
test_FormatSignature = property "formatSignature" prop where
prop = forAll gen_SignatureString check
check (s, _) = let
Just sig = parseSignature s
in formatSignature sig == s
test_IsAtom :: Test
test_IsAtom = assertions "IsAtom" $ do
let Just sig = signature []
assertAtom TypeSignature sig
test_ShowType :: Test
test_ShowType = assertions "show-type" $ do
$expect (equal "Bool" (show TypeBoolean))
$expect (equal "Bool" (show TypeBoolean))
$expect (equal "Word8" (show TypeWord8))
$expect (equal "Word16" (show TypeWord16))
$expect (equal "Word32" (show TypeWord32))
$expect (equal "Word64" (show TypeWord64))
$expect (equal "Int16" (show TypeInt16))
$expect (equal "Int32" (show TypeInt32))
$expect (equal "Int64" (show TypeInt64))
$expect (equal "Double" (show TypeDouble))
$expect (equal "UnixFd" (show TypeUnixFd))
$expect (equal "String" (show TypeString))
$expect (equal "Signature" (show TypeSignature))
$expect (equal "ObjectPath" (show TypeObjectPath))
$expect (equal "Variant" (show TypeVariant))
$expect (equal "[Word8]" (show (TypeArray TypeWord8)))
$expect (equal "Dict Word8 (Dict Word8 Word8)" (show (TypeDictionary TypeWord8 (TypeDictionary TypeWord8 TypeWord8))))
$expect (equal "(Word8, Word16)" (show (TypeStructure [TypeWord8, TypeWord16])))
gen_SignatureTypes :: Gen [Type]
gen_SignatureTypes = do
(_, ts) <- gen_SignatureString
return ts
gen_SignatureString :: Gen (String, [Type])
gen_SignatureString = gen where
anyType = oneof [atom, container]
atom = elements
[ ("b", TypeBoolean)
, ("y", TypeWord8)
, ("q", TypeWord16)
, ("u", TypeWord32)
, ("t", TypeWord64)
, ("n", TypeInt16)
, ("i", TypeInt32)
, ("x", TypeInt64)
, ("d", TypeDouble)
, ("h", TypeUnixFd)
, ("s", TypeString)
, ("o", TypeObjectPath)
, ("g", TypeSignature)
]
container = oneof
[ return ("v", TypeVariant)
, array
, dict
, struct
]
array = do
(tCode, tEnum) <- anyType
return ('a':tCode, TypeArray tEnum)
dict = do
(kCode, kEnum) <- atom
(vCode, vEnum) <- anyType
return (concat ["a{", kCode, vCode, "}"], TypeDictionary kEnum vEnum)
struct = do
ts <- listOf1 (halfSized anyType)
let (codes, enums) = unzip ts
return ("(" ++ concat codes ++ ")", TypeStructure enums)
gen = do
types <- listOf anyType
let (codes, enums) = unzip types
let chars = concat codes
if length chars > 255
then halfSized gen
else return (chars, enums)
instance Arbitrary Signature where
arbitrary = do
ts <- gen_SignatureTypes
let Just sig = signature ts
return sig
| jmillikin/haskell-dbus | tests/DBusTests/Signature.hs | Haskell | apache-2.0 | 4,901 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// pch.h
// Header for standard system include files.
//
#pragma once
#include <msxml6.h>
#include <collection.h>
#include <ppltasks.h>
#include <wrl.h>
#include "Common\SuspensionManager.h"
#include "App.xaml.h"
#include <sstream>
| gisfromscratch/windowsappsamples | Windows account authorization sample/C++/Shared/pch.h | C | apache-2.0 | 624 |
# Gitbook Simple Page TOC Plugin [](https://badge.fury.io/js/gitbook-plugin-simple-page-toc)
This plugin inserts a table of content (TOC) section into your GitBook page. It is powered by the [markdown-toc](https://github.com/jonschlinkert/markdown-toc) library.
## Usage
### Installation
Add the plugin to your `book.json`:
```
{
"plugins" : [ "simple-page-toc" ]
}
```
### Create TOC
Place a `<!-- toc -->` code comment somewhere into your text. Generating your GitBook inserts a table of contents immediately after this comment.
### Optional configuration
You can add the following configuration params to your `book.json`:
```
{
"plugins" : [
"simple-page-toc"
],
"pluginsConfig": {
"simple-page-toc": {
"maxDepth": 3,
"skipFirstH1": true
}
}
}
```
Name | Type | Default | Description
----------- | ------- | ------- | ------------
maxDepth | Number | 3 | Use headings whose depth is at most maxdepth.
skipFirstH1 | Boolean | true | Exclude the first h1-level heading in a file.
## Changelog
* 0.1.0 Releases:
* 0.1.0 First release
* 0.1.1 Fixed invalid config example in README (thanks at15)
* 0.1.2 Fixed bug: Titles with hyphen builds with wrong anchor link
| stuebersystems/gitbook-plugin-simple-page-toc | README.md | Markdown | apache-2.0 | 1,312 |
/*******************************************************************************
* Copyright (C) 2016 Kwaku Twumasi-Afriyie <[email protected]>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kwaku Twumasi-Afriyie <[email protected]> - initial API and implementation
******************************************************************************/
package com.quakearts.webapp.facelets.bootstrap.renderers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIColumn;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import com.quakearts.webapp.facelets.bootstrap.components.BootTable;
import com.quakearts.webapp.facelets.bootstrap.renderkit.Attribute;
import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager;
import com.quakearts.webapp.facelets.bootstrap.renderkit.html_basic.HtmlBasicRenderer;
import com.quakearts.webapp.facelets.util.UtilityMethods;
import static com.quakearts.webapp.facelets.bootstrap.renderkit.RenderKitUtils.*;
public class BootTableRenderer extends HtmlBasicRenderer {
private static final Attribute[] ATTRIBUTES =
AttributeManager.getAttributes(AttributeManager.Key.DATATABLE);
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncode(component)) {
return;
}
BootTable data = (BootTable) component;
data.setRowIndex(-1);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("table", component);
writer.writeAttribute("id", component.getClientId(context),
"id");
String styleClass = data.get("styleClass");
writer.writeAttribute("class","table "+(styleClass !=null?" "+styleClass:""), "styleClass");
renderHTML5DataAttributes(context, component);
renderPassThruAttributes(context, writer, component,
ATTRIBUTES);
writer.writeText("\n", component, null);
UIComponent caption = getFacet(component, "caption");
if (caption != null) {
String captionClass = data.get("captionClass");
String captionStyle = data.get("captionStyle");
writer.startElement("caption", component);
if (captionClass != null) {
writer.writeAttribute("class", captionClass, "captionClass");
}
if (captionStyle != null) {
writer.writeAttribute("style", captionStyle, "captionStyle");
}
encodeRecursive(context, caption);
writer.endElement("caption");
}
UIComponent colGroups = getFacet(component, "colgroups");
if (colGroups != null) {
encodeRecursive(context, colGroups);
}
BootMetaInfo info = getMetaInfo(context, component);
UIComponent header = getFacet(component, "header");
if (header != null || info.hasHeaderFacets) {
String headerClass = data.get("headerClass");
writer.startElement("thead", component);
writer.writeText("\n", component, null);
if (header != null) {
writer.startElement("tr", header);
writer.startElement("th", header);
if (headerClass != null) {
writer.writeAttribute("class", headerClass, "headerClass");
}
if (info.columns.size() > 1) {
writer.writeAttribute("colspan",
String.valueOf(info.columns.size()), null);
}
writer.writeAttribute("scope", "colgroup", null);
encodeRecursive(context, header);
writer.endElement("th");
writer.endElement("tr");
writer.write("\n");
}
if (info.hasHeaderFacets) {
writer.startElement("tr", component);
writer.writeText("\n", component, null);
for (UIColumn column : info.columns) {
String columnHeaderClass = info.getCurrentHeaderClass();
writer.startElement("th", column);
if (columnHeaderClass != null) {
writer.writeAttribute("class", columnHeaderClass,
"columnHeaderClass");
} else if (headerClass != null) {
writer.writeAttribute("class", headerClass, "headerClass");
}
writer.writeAttribute("scope", "col", null);
UIComponent facet = getFacet(column, "header");
if (facet != null) {
encodeRecursive(context, facet);
}
writer.endElement("th");
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
}
writer.endElement("thead");
writer.writeText("\n", component, null);
}
}
@Override
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncodeChildren(component)) {
return;
}
UIData data = (UIData) component;
ResponseWriter writer = context.getResponseWriter();
BootMetaInfo info = getMetaInfo(context, data);
if(info.columns.isEmpty()) {
writer.startElement("tbody", component);
renderEmptyTableRow(writer, component);
writer.endElement("tbody");
return;
}
int processed = 0;
int rowIndex = data.getFirst() - 1;
int rows = data.getRows();
List<Integer> bodyRows = getBodyRows(context.getExternalContext().getApplicationMap(), data);
boolean hasBodyRows = (bodyRows != null && !bodyRows.isEmpty());
boolean wroteTableBody = false;
if (!hasBodyRows) {
writer.startElement("tbody", component);
writer.writeText("\n", component, null);
}
boolean renderedRow = false;
while (true) {
if ((rows > 0) && (++processed > rows)) {
break;
}
data.setRowIndex(++rowIndex);
if (!data.isRowAvailable()) {
break;
}
if (hasBodyRows && bodyRows.contains(data.getRowIndex())) {
if (wroteTableBody) {
writer.endElement("tbody");
}
writer.startElement("tbody", data);
wroteTableBody = true;
}
writer.startElement("tr", component);
if (info.rowClasses.length > 0) {
writer.writeAttribute("class", info.getCurrentRowClass(),
"rowClasses");
}
writer.writeText("\n", component, null);
info.newRow();
for (UIColumn column : info.columns) {
boolean isRowHeader = Boolean.TRUE.equals(column.getAttributes()
.get("rowHeader"));
if (isRowHeader) {
writer.startElement("th", column);
writer.writeAttribute("scope", "row", null);
} else {
writer.startElement("td", column);
}
String columnClass = info.getCurrentColumnClass();
if (columnClass != null) {
writer.writeAttribute("class", columnClass, "columnClasses");
}
for (Iterator<UIComponent> gkids = getChildren(column); gkids
.hasNext();) {
encodeRecursive(context, gkids.next());
}
if (isRowHeader) {
writer.endElement("th");
} else {
writer.endElement("td");
}
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
renderedRow = true;
}
if(!renderedRow) {
renderEmptyTableRow(writer, data);
}
writer.endElement("tbody");
writer.writeText("\n", component, null);
data.setRowIndex(-1);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
if (!shouldEncode(component)) {
return;
}
ResponseWriter writer = context.getResponseWriter();
BootMetaInfo info = getMetaInfo(context, component);
UIComponent footer = getFacet(component, "footer");
if (footer != null || info.hasFooterFacets) {
String footerClass = (String) component.getAttributes().get("footerClass");
writer.startElement("tfoot", component);
writer.writeText("\n", component, null);
if (info.hasFooterFacets) {
writer.startElement("tr", component);
writer.writeText("\n", component, null);
for (UIColumn column : info.columns) {
String columnFooterClass = (String) column.getAttributes().get(
"footerClass");
writer.startElement("td", column);
if (columnFooterClass != null) {
writer.writeAttribute("class", columnFooterClass,
"columnFooterClass");
} else if (footerClass != null) {
writer.writeAttribute("class", footerClass, "footerClass");
}
UIComponent facet = getFacet(column, "footer");
if (facet != null) {
encodeRecursive(context, facet);
}
writer.endElement("td");
writer.writeText("\n", component, null);
}
writer.endElement("tr");
writer.write("\n");
}
if (footer != null) {
writer.startElement("tr", footer);
writer.startElement("td", footer);
if (footerClass != null) {
writer.writeAttribute("class", footerClass, "footerClass");
}
if (info.columns.size() > 1) {
writer.writeAttribute("colspan",
String.valueOf(info.columns.size()), null);
}
encodeRecursive(context, footer);
writer.endElement("td");
writer.endElement("tr");
writer.write("\n");
}
writer.endElement("tfoot");
writer.writeText("\n", component, null);
}
clearMetaInfo(context, component);
((UIData) component).setRowIndex(-1);
writer.endElement("table");
writer.writeText("\n", component, null);
}
private List<Integer> getBodyRows(Map<String, Object> appMap, UIData data) {
List<Integer> result = null;
String bodyRows = (String) data.getAttributes().get("bodyrows");
if (bodyRows != null) {
String [] rows = UtilityMethods.split(appMap, bodyRows, ",");
if (rows != null) {
result = new ArrayList<Integer>(rows.length);
for (String curRow : rows) {
result.add(Integer.valueOf(curRow));
}
}
}
return result;
}
private void renderEmptyTableRow(final ResponseWriter writer,
final UIComponent component) throws IOException {
writer.startElement("tr", component);
writer.startElement("td", component);
writer.endElement("td");
writer.endElement("tr");
}
protected BootTableRenderer.BootMetaInfo getMetaInfo(FacesContext context,
UIComponent table) {
String key = createKey(table);
Map<Object, Object> attributes = context.getAttributes();
BootMetaInfo info = (BootMetaInfo) attributes
.get(key);
if (info == null) {
info = new BootMetaInfo(table);
attributes.put(key, info);
}
return info;
}
protected void clearMetaInfo(FacesContext context, UIComponent table) {
context.getAttributes().remove(createKey(table));
}
protected String createKey(UIComponent table) {
return BootMetaInfo.KEY + '_' + table.hashCode();
}
private static class BootMetaInfo {
private static final UIColumn PLACE_HOLDER_COLUMN = new UIColumn();
private static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final String KEY = BootMetaInfo.class.getName();
public final String[] rowClasses;
public final String[] columnClasses;
public final String[] headerClasses;
public final List<UIColumn> columns;
public final boolean hasHeaderFacets;
public final boolean hasFooterFacets;
public final int columnCount;
public int columnStyleCounter;
public int headerStyleCounter;
public int rowStyleCounter;
public BootMetaInfo(UIComponent table) {
rowClasses = getRowClasses(table);
columnClasses = getColumnClasses(table);
headerClasses = getHeaderClasses(table);
columns = getColumns(table);
columnCount = columns.size();
hasHeaderFacets = hasFacet("header", columns);
hasFooterFacets = hasFacet("footer", columns);
}
public void newRow() {
columnStyleCounter = 0;
headerStyleCounter = 0;
}
public String getCurrentColumnClass() {
String style = null;
if (columnStyleCounter < columnClasses.length
&& columnStyleCounter <= columnCount) {
style = columnClasses[columnStyleCounter++];
}
return ((style != null && style.length() > 0) ? style : null);
}
public String getCurrentHeaderClass() {
String style = null;
if (headerStyleCounter < headerClasses.length
&& headerStyleCounter <= columnCount) {
style = headerClasses[headerStyleCounter++];
}
return ((style != null && style.length() > 0) ? style : null);
}
public String getCurrentRowClass() {
String style = rowClasses[rowStyleCounter++];
if (rowStyleCounter >= rowClasses.length) {
rowStyleCounter = 0;
}
return style;
}
private static String[] getColumnClasses(UIComponent table) {
String values = ((BootTable) table).get("columnClasses");
if (values == null) {
return EMPTY_STRING_ARRAY;
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
private static String[] getHeaderClasses(UIComponent table) {
String values = ((BootTable) table).get("headerClasses");
if (values == null) {
return EMPTY_STRING_ARRAY;
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
private static List<UIColumn> getColumns(UIComponent table) {
if (table instanceof UIData) {
int childCount = table.getChildCount();
if (childCount > 0) {
List<UIColumn> results = new ArrayList<UIColumn>(childCount);
for (UIComponent kid : table.getChildren()) {
if ((kid instanceof UIColumn) && kid.isRendered()) {
results.add((UIColumn) kid);
}
}
return results;
} else {
return Collections.emptyList();
}
} else {
int count;
Object value = table.getAttributes().get("columns");
if ((value != null) && (value instanceof Integer)) {
count = ((Integer) value);
} else {
count = 2;
}
if (count < 1) {
count = 1;
}
List<UIColumn> result = new ArrayList<UIColumn>(count);
for (int i = 0; i < count; i++) {
result.add(PLACE_HOLDER_COLUMN);
}
return result;
}
}
private static boolean hasFacet(String name, List<UIColumn> columns) {
if (!columns.isEmpty()) {
for (UIColumn column : columns) {
if (column.getFacetCount() > 0) {
if (column.getFacets().containsKey(name)) {
return true;
}
}
}
}
return false;
}
private static String[] getRowClasses(UIComponent table) {
String values = ((BootTable) table).get("rowClasses");
if (values == null) {
return (EMPTY_STRING_ARRAY);
}
Map<String, Object> appMap = FacesContext.getCurrentInstance()
.getExternalContext().getApplicationMap();
return UtilityMethods.split(appMap, values.trim(), ",");
}
}
}
| kwakutwumasi/Quakearts-JSF-Webtools | qa-boot/src/main/java/com/quakearts/webapp/facelets/bootstrap/renderers/BootTableRenderer.java | Java | apache-2.0 | 15,874 |
<?php
/**
* SystemProviderListResponseTest
*
* PHP version 5
*
* @category Class
* @package BumbalClient
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Bumbal Client Api
*
* Bumbal API documentation
*
* OpenAPI spec version: 2.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace BumbalClient;
/**
* SystemProviderListResponseTest Class Doc Comment
*
* @category Class */
// * @description SystemProviderListResponse
/**
* @package BumbalClient
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class SystemProviderListResponseTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "SystemProviderListResponse"
*/
public function testSystemProviderListResponse()
{
}
/**
* Test attribute "items"
*/
public function testPropertyItems()
{
}
/**
* Test attribute "count_filtered"
*/
public function testPropertyCountFiltered()
{
}
/**
* Test attribute "count_unfiltered"
*/
public function testPropertyCountUnfiltered()
{
}
/**
* Test attribute "count_limited"
*/
public function testPropertyCountLimited()
{
}
}
| freightlive/bumbal-client-api-php | test/Model/SystemProviderListResponseTest.php | PHP | apache-2.0 | 1,978 |
using Foundation.Data.Hibernate;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NHibernate;
using NHibernate.Context;
using NHibernate.Engine;
namespace Foundation.Tests.Data.Hibernate
{
[TestClass]
public class HibernateUnitOfWorkTests
{
[TestMethod]
public void Constructor_opens_session_from_factory()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
new HibernateUnitOfWork(sessionFactory.Object);
sessionFactory.Verify(factory1 => factory1.OpenSession());
}
[TestMethod]
public void Constructor_sets_opened_session_flush_mode_to_commit()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
var flushMode = FlushMode.Auto;
session.SetupSet(session2 => session2.FlushMode).Callback(mode => flushMode = mode);
new HibernateUnitOfWork(sessionFactory.Object);
session.VerifySet( session1 => session1.FlushMode, Times.Once());
Assert.AreEqual(FlushMode.Commit, flushMode);
}
[TestMethod]
public void Constructor_begins_transaction_from_session()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
new HibernateUnitOfWork(sessionFactory.Object);
session.Verify(session1 => session1.BeginTransaction());
}
[TestMethod]
public void Dispose_also_disposes_of_session()
{
var session = new Mock<ISession>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
var work = new HibernateUnitOfWork(sessionFactory.Object);
work.Dispose();
session.Verify(session1 => session1.Dispose());
}
[TestMethod]
public void Dispose_also_disposes_of_transaction()
{
var session = new Mock<ISession>();
var transaction = new Mock<ITransaction>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactoryImplementor>();
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
session.Setup(session3 => session3.BeginTransaction()).Returns(transaction.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
var work = new HibernateUnitOfWork(sessionFactory.Object);
work.Dispose();
transaction.Verify(transaction1 => transaction1.Dispose());
}
[TestMethod]
public void Commit_also_commits_transaction()
{
var session = new Mock<ISession>();
var transaction = new Mock<ITransaction>();
var context = new Mock<CurrentSessionContext>();
var sessionFactory = new Mock<ISessionFactory>().As<ISessionFactoryImplementor>();
session.Setup(session2 => session2.SessionFactory).Returns(sessionFactory.Object);
session.Setup(session3 => session3.BeginTransaction()).Returns(transaction.Object);
sessionFactory.Setup(factory => factory.OpenSession()).Returns(session.Object);
sessionFactory.Setup(implementor => implementor.CurrentSessionContext).Returns(context.Object);
var work = new HibernateUnitOfWork(sessionFactory.Object);
work.Commit();
transaction.Verify(transaction1 => transaction1.Commit());
}
}
} | DavidMoore/Foundation | Tests/UnitTests/Foundation.Tests/Data/Hibernate/HibernateUnitOfWorkTests.cs | C# | apache-2.0 | 5,383 |
package info.pupcode.model.repo.test;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by fabientronche1 on 08.11.15.
*/
public class AbstractConcordionFixture {
protected SpringConfigTest springConfigTest;
protected ClassPathXmlApplicationContext applicationContext;
@Before
public void setUp() {
applicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
if (springConfigTest == null) {
springConfigTest = (SpringConfigTest) applicationContext.getBean(SpringConfigTest.class.getName());
}
}
}
| PUPInitiative/pup-code-poc | pup-code-domain/src/test/java/info/pupcode/model/repo/test/AbstractConcordionFixture.java | Java | apache-2.0 | 658 |
/*
* Copyright 2002-2010 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.
*/
using System;
using System.Collections.Generic;
using Spring.Objects.Factory.Config;
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Programmatic means of constructing a <see cref="IObjectDefinition"/> using the builder pattern. Intended primarily
/// for use when implementing custom namespace parsers.
/// </summary>
/// <remarks>Set methods are used instead of properties, so that chaining of methods can be used to create
/// 'one-liner'definitions that set multiple properties at one.</remarks>
/// <author>Rod Johnson</author>
/// <author>Rob Harrop</author>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class ObjectDefinitionBuilder
{
private AbstractObjectDefinition objectDefinition;
private IObjectDefinitionFactory objectDefinitionFactory;
private int constructorArgIndex;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDefinitionBuilder"/> class, private
/// to force use of factory methods.
/// </summary>
private ObjectDefinitionBuilder()
{
}
/// <summary>
/// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>.
/// </summary>
public static ObjectDefinitionBuilder GenericObjectDefinition()
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinition = new GenericObjectDefinition();
return builder;
}
/// <summary>
/// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>.
/// </summary>
/// <param name="objectType">the <see cref="Type"/> of the object that the definition is being created for</param>
public static ObjectDefinitionBuilder GenericObjectDefinition(Type objectType)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinition = new GenericObjectDefinition();
builder.objectDefinition.ObjectType = objectType;
return builder;
}
/// <summary>
/// Creates a new <see cref="ObjectDefinitionBuilder"/> used to construct a <see cref="Spring.Objects.Factory.Support.GenericObjectDefinition"/>.
/// </summary>
/// <param name="objectTypeName">the name of the <see cref="Type"/> of the object that the definition is being created for</param>
public static ObjectDefinitionBuilder GenericObjectDefinition(string objectTypeName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinition = new GenericObjectDefinition();
builder.objectDefinition.ObjectTypeName = objectTypeName;
return builder;
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectTypeName">The type name of the object.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
string objectTypeName)
{
return RootObjectDefinition(objectDefinitionFactory, objectTypeName, null);
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectTypeName">Name of the object type.</param>
/// <param name="factoryMethodName">Name of the factory method.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
string objectTypeName,
string factoryMethodName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinitionFactory = objectDefinitionFactory;
// Pass in null for parent name and also AppDomain to force object definition to be register by name and not type.
builder.objectDefinition =
objectDefinitionFactory.CreateObjectDefinition(objectTypeName, null, null);
builder.objectDefinition.FactoryMethodName = factoryMethodName;
return builder;
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectType">Type of the object.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
Type objectType)
{
return RootObjectDefinition(objectDefinitionFactory, objectType, null);
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a root object definition.
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="factoryMethodName">Name of the factory method.</param>
/// <returns>A new <code>ObjectDefinitionBuilder</code> instance.</returns>
public static ObjectDefinitionBuilder RootObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
Type objectType, string factoryMethodName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinitionFactory = objectDefinitionFactory;
builder.objectDefinition =
objectDefinitionFactory.CreateObjectDefinition(objectType.FullName, null, AppDomain.CurrentDomain);
builder.objectDefinition.ObjectType = objectType;
builder.objectDefinition.FactoryMethodName = factoryMethodName;
return builder;
}
/// <summary>
/// Create a new <code>ObjectDefinitionBuilder</code> used to construct a child object definition..
/// </summary>
/// <param name="objectDefinitionFactory">The object definition factory.</param>
/// <param name="parentObjectName">Name of the parent object.</param>
/// <returns></returns>
public static ObjectDefinitionBuilder ChildObjectDefinition(IObjectDefinitionFactory objectDefinitionFactory,
string parentObjectName)
{
ObjectDefinitionBuilder builder = new ObjectDefinitionBuilder();
builder.objectDefinitionFactory = objectDefinitionFactory;
builder.objectDefinition =
objectDefinitionFactory.CreateObjectDefinition(null, parentObjectName, AppDomain.CurrentDomain);
return builder;
}
/// <summary>
/// Gets the current object definition in its raw (unvalidated) form.
/// </summary>
/// <value>The raw object definition.</value>
public AbstractObjectDefinition RawObjectDefinition
{
get { return objectDefinition; }
}
/// <summary>
/// Validate and gets the object definition.
/// </summary>
/// <value>The object definition.</value>
public AbstractObjectDefinition ObjectDefinition
{
get
{
objectDefinition.Validate();
return objectDefinition;
}
}
//TODO add expression support.
/// <summary>
/// Adds the property value under the given name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddPropertyValue(string name, object value)
{
objectDefinition.PropertyValues.Add(new PropertyValue(name, value));
return this;
}
/// <summary>
/// Adds a reference to the specified object name under the property specified.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="objectName">Name of the object.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddPropertyReference(string name, string objectName)
{
objectDefinition.PropertyValues.Add(new PropertyValue(name, new RuntimeObjectReference(objectName)));
return this;
}
/// <summary>
/// Adds an index constructor arg value. The current index is tracked internally and all addtions are
/// at the present point
/// </summary>
/// <param name="value">The constructor arg value.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddConstructorArg(object value)
{
objectDefinition.ConstructorArgumentValues.AddIndexedArgumentValue(constructorArgIndex++,value);
return this;
}
/// <summary>
/// Adds a reference to the named object as a constructor argument.
/// </summary>
/// <param name="objectName">Name of the object.</param>
/// <returns></returns>
public ObjectDefinitionBuilder AddConstructorArgReference(string objectName)
{
return AddConstructorArg(new RuntimeObjectReference(objectName));
}
/// <summary>
/// Sets the name of the factory method to use for this definition.
/// </summary>
/// <param name="factoryMethod">The factory method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetFactoryMethod(string factoryMethod)
{
objectDefinition.FactoryMethodName = factoryMethod;
return this;
}
/// <summary>
/// Sets the name of the factory object to use for this definition.
/// </summary>
/// <param name="factoryObject">The factory object.</param>
/// <param name="factoryMethod">The factory method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetFactoryObject(string factoryObject, string factoryMethod)
{
objectDefinition.FactoryObjectName = factoryObject;
objectDefinition.FactoryMethodName = factoryMethod;
return this;
}
/// <summary>
/// Sets whether or not this definition describes a singleton object.
/// </summary>
/// <param name="singleton">if set to <c>true</c> [singleton].</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetSingleton(bool singleton)
{
objectDefinition.IsSingleton = singleton;
return this;
}
/// <summary>
/// Sets whether objects or not this definition is abstract.
/// </summary>
/// <param name="flag">if set to <c>true</c> [flag].</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetAbstract(bool flag)
{
objectDefinition.IsAbstract = flag;
return this;
}
/// <summary>
/// Sets whether objects for this definition should be lazily initialized or not.
/// </summary>
/// <param name="lazy">if set to <c>true</c> [lazy].</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetLazyInit(bool lazy)
{
objectDefinition.IsLazyInit = lazy;
return this;
}
/// <summary>
/// Sets the autowire mode for this definition.
/// </summary>
/// <param name="autowireMode">The autowire mode.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetAutowireMode(AutoWiringMode autowireMode)
{
objectDefinition.AutowireMode = autowireMode;
return this;
}
/// <summary>
/// Sets the autowire candidate value for this definition.
/// </summary>
/// <param name="autowireCandidate">The autowire candidate value</param>
/// <returns></returns>
public ObjectDefinitionBuilder SetAutowireCandidate(bool autowireCandidate)
{
objectDefinition.IsAutowireCandidate = autowireCandidate;
return this;
}
/// <summary>
/// Sets the primary value for this definition.
/// </summary>
/// <param name="primary">If object is primary</param>
/// <returns></returns>
public ObjectDefinitionBuilder SetPrimary(bool primary)
{
objectDefinition.IsPrimary = primary;
return this;
}
/// <summary>
/// Sets the dependency check mode for this definition.
/// </summary>
/// <param name="dependencyCheck">The dependency check.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetDependencyCheck(DependencyCheckingMode dependencyCheck)
{
objectDefinition.DependencyCheck = dependencyCheck;
return this;
}
/// <summary>
/// Sets the name of the destroy method for this definition.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetDestroyMethodName(string methodName)
{
objectDefinition.DestroyMethodName = methodName;
return this;
}
/// <summary>
/// Sets the name of the init method for this definition.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetInitMethodName(string methodName)
{
objectDefinition.InitMethodName = methodName;
return this;
}
/// <summary>
/// Sets the resource description for this definition.
/// </summary>
/// <param name="resourceDescription">The resource description.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder SetResourceDescription(string resourceDescription)
{
objectDefinition.ResourceDescription = resourceDescription;
return this;
}
/// <summary>
/// Adds the specified object name to the list of objects that this definition depends on.
/// </summary>
/// <param name="objectName">Name of the object.</param>
/// <returns>The current <code>ObjectDefinitionBuilder</code>.</returns>
public ObjectDefinitionBuilder AddDependsOn(string objectName)
{
if (objectDefinition.DependsOn == null)
{
objectDefinition.DependsOn = new[] {objectName};
}
else
{
var list = new List<string>(objectDefinition.DependsOn.Count + 1);
list.AddRange(objectDefinition.DependsOn);
list.Add(objectName);
objectDefinition.DependsOn = list;
}
return this;
}
}
} | spring-projects/spring-net | src/Spring/Spring.Core/Objects/Factory/Support/ObjectDefinitionBuilder.cs | C# | apache-2.0 | 17,503 |
package alicloud
import (
"fmt"
"testing"
"github.com/alibaba/terraform-provider/alicloud/connectivity"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAlicloudSslVpnClientCert_basic(t *testing.T) {
var sslVpnClientCert vpc.DescribeSslVpnClientCertResponse
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
// module name
IDRefreshName: "alicloud_ssl_vpn_client_cert.foo",
Providers: testAccProviders,
CheckDestroy: testAccCheckSslVpnClientCertDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSslVpnClientCertConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckSslVpnClientCertExists("alicloud_ssl_vpn_client_cert.foo", &sslVpnClientCert),
resource.TestCheckResourceAttr(
"alicloud_ssl_vpn_client_cert.foo", "name", "tf-testAccSslVpnClientCertConfig"),
resource.TestCheckResourceAttrSet(
"alicloud_ssl_vpn_client_cert.foo", "ssl_vpn_server_id"),
),
},
},
})
}
func TestAccAlicloudSslVpnClientCert_update(t *testing.T) {
var sslVpnClientCert vpc.DescribeSslVpnClientCertResponse
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckSslVpnClientCertDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSslVpnClientCertConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckSslVpnClientCertExists("alicloud_ssl_vpn_client_cert.foo", &sslVpnClientCert),
resource.TestCheckResourceAttr(
"alicloud_ssl_vpn_client_cert.foo", "name", "tf-testAccSslVpnClientCertConfig"),
resource.TestCheckResourceAttrSet(
"alicloud_ssl_vpn_client_cert.foo", "ssl_vpn_server_id"),
),
},
resource.TestStep{
Config: testAccSslVpnClientCertConfigUpdate,
Check: resource.ComposeTestCheckFunc(
testAccCheckSslVpnClientCertExists("alicloud_ssl_vpn_client_cert.foo", &sslVpnClientCert),
resource.TestCheckResourceAttr(
"alicloud_ssl_vpn_client_cert.foo", "name", "tf-testAccSslVpnClientCertUpdate"),
resource.TestCheckResourceAttrSet(
"alicloud_ssl_vpn_client_cert.foo", "ssl_vpn_server_id"),
),
},
},
})
}
func testAccCheckSslVpnClientCertExists(n string, vpn *vpc.DescribeSslVpnClientCertResponse) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No VPN ID is set")
}
client := testAccProvider.Meta().(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
instance, err := vpnGatewayService.DescribeSslVpnClientCert(rs.Primary.ID)
if err != nil {
return err
}
*vpn = instance
return nil
}
}
func testAccCheckSslVpnClientCertDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*connectivity.AliyunClient)
vpnGatewayService := VpnGatewayService{client}
for _, rs := range s.RootModule().Resources {
if rs.Type != "alicloud_ssl_vpn_client_cert" {
continue
}
instance, err := vpnGatewayService.DescribeSslVpnClientCert(rs.Primary.ID)
if err != nil {
if NotFoundError(err) {
continue
}
return err
}
if instance.SslVpnClientCertId != "" {
return fmt.Errorf("Ssl VPN client cert %s still exist", instance.SslVpnClientCertId)
}
}
return nil
}
const testAccSslVpnClientCertConfig = `
variable "name" {
default = "tf-testAccSslVpnClientCertConfig"
}
resource "alicloud_vpc" "foo" {
cidr_block = "172.16.0.0/12"
name = "${var.name}"
}
data "alicloud_zones" "default" {
"available_resource_creation"= "VSwitch"
}
resource "alicloud_vswitch" "foo" {
vpc_id = "${alicloud_vpc.foo.id}"
cidr_block = "172.16.0.0/21"
availability_zone = "${data.alicloud_zones.default.zones.0.id}"
name = "${var.name}"
}
resource "alicloud_vpn_gateway" "foo" {
name = "${var.name}"
vpc_id = "${alicloud_vpc.foo.id}"
bandwidth = "10"
enable_ssl = true
instance_charge_type = "PostPaid"
description = "test_create_description"
}
resource "alicloud_ssl_vpn_server" "foo" {
name = "${var.name}"
vpn_gateway_id = "${alicloud_vpn_gateway.foo.id}"
client_ip_pool = "192.168.0.0/16"
local_subnet = "172.16.0.0/21"
protocol = "UDP"
cipher = "AES-128-CBC"
port = "1194"
compress = "false"
}
resource "alicloud_ssl_vpn_client_cert" "foo" {
ssl_vpn_server_id = "${alicloud_ssl_vpn_server.foo.id}"
name = "${var.name}"
}
`
const testAccSslVpnClientCertConfigUpdate = `
variable "name" {
default = "tf-testAccSslVpnClientCertUpdate"
}
resource "alicloud_vpc" "foo" {
cidr_block = "172.16.0.0/12"
name = "${var.name}"
}
data "alicloud_zones" "default" {
"available_resource_creation"= "VSwitch"
}
resource "alicloud_vswitch" "foo" {
vpc_id = "${alicloud_vpc.foo.id}"
cidr_block = "172.16.0.0/21"
availability_zone = "${data.alicloud_zones.default.zones.0.id}"
name = "${var.name}"
}
resource "alicloud_vpn_gateway" "foo" {
name = "${var.name}"
vpc_id = "${alicloud_vpc.foo.id}"
bandwidth = "10"
enable_ssl = true
instance_charge_type = "PostPaid"
description = "test_update_description"
}
resource "alicloud_ssl_vpn_server" "foo" {
name = "${var.name}"
vpn_gateway_id = "${alicloud_vpn_gateway.foo.id}"
client_ip_pool = "192.168.0.0/16"
local_subnet = "172.16.0.0/21"
protocol = "UDP"
cipher = "AES-128-CBC"
port = "1194"
compress = "false"
}
resource "alicloud_ssl_vpn_client_cert" "foo" {
ssl_vpn_server_id = "${alicloud_ssl_vpn_server.foo.id}"
name = "${var.name}"
}
`
| xiaozhu36/terraform-provider | alicloud/resource_alicloud_ssl_vpn_client_cert_test.go | GO | apache-2.0 | 5,719 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Mon Apr 29 15:10:36 CEST 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.solr.cloud.Overseer (Solr 4.3.0 API)
</TITLE>
<META NAME="date" CONTENT="2013-04-29">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.cloud.Overseer (Solr 4.3.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/cloud//class-useOverseer.html" target="_top"><B>FRAMES</B></A>
<A HREF="Overseer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.solr.cloud.Overseer</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.solr.cloud"><B>org.apache.solr.cloud</B></A></TD>
<TD>
Classes for dealing with ZooKeeper when operating in <a href="http://wiki.apache.org/solr/SolrCloud">SolrCloud</a> mode. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.solr.cloud"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A> in <A HREF="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</A> declared as <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud">Overseer</A></CODE></FONT></TD>
<TD><CODE><B>ZkController.</B><B><A HREF="../../../../../org/apache/solr/cloud/ZkController.html#overseer">overseer</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/solr/cloud/Overseer.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/solr/cloud//class-useOverseer.html" target="_top"><B>FRAMES</B></A>
<A HREF="Overseer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2000-2013 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML>
| iluminati182006/ReutersSolr | docs/solr-core/org/apache/solr/cloud/class-use/Overseer.html | HTML | apache-2.0 | 8,149 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_11) on Mon Apr 07 19:10:16 CEST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class at.irian.ankor.big.json.BigListSerializer (Ankor - Project 0.2-SNAPSHOT API)</title>
<meta name="date" content="2014-04-07">
<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="Uses of Class at.irian.ankor.big.json.BigListSerializer (Ankor - Project 0.2-SNAPSHOT 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><a href="../../../../../../at/irian/ankor/big/json/BigListSerializer.html" title="class in at.irian.ankor.big.json">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?at/irian/ankor/big/json/class-use/BigListSerializer.html" target="_top">Frames</a></li>
<li><a href="BigListSerializer.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 at.irian.ankor.big.json.BigListSerializer" class="title">Uses of Class<br>at.irian.ankor.big.json.BigListSerializer</h2>
</div>
<div class="classUseContainer">No usage of at.irian.ankor.big.json.BigListSerializer</div>
<!-- ======= 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><a href="../../../../../../at/irian/ankor/big/json/BigListSerializer.html" title="class in at.irian.ankor.big.json">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?at/irian/ankor/big/json/class-use/BigListSerializer.html" target="_top">Frames</a></li>
<li><a href="BigListSerializer.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 © 2014. All rights reserved.</small></p>
</body>
</html>
| ankor-io/ankor-framework | website/ankorsite/static/javadoc/apidocs-0.2/at/irian/ankor/big/json/class-use/BigListSerializer.html | HTML | apache-2.0 | 4,445 |
using System;
using Windows.ApplicationModel.Resources;
namespace Okra.Data.Helpers
{
internal static class ResourceHelper
{
// *** Constants ***
private const string RESOURCEMAP_ERROR = "Okra.Data/Errors";
private const string RESOURCE_NOT_FOUND_ERROR = "Exception_ArgumentException_ResourceStringNotFound";
// *** Static Fields ***
private static ResourceLoader errorResourceLoader;
// *** Methods ***
public static string GetErrorResource(string resourceName)
{
if (errorResourceLoader == null)
errorResourceLoader = ResourceLoader.GetForViewIndependentUse(RESOURCEMAP_ERROR);
string errorResource = errorResourceLoader.GetString(resourceName);
if (string.IsNullOrEmpty(errorResource) && resourceName != RESOURCE_NOT_FOUND_ERROR)
throw new ArgumentException(GetErrorResource(RESOURCE_NOT_FOUND_ERROR));
return errorResource;
}
}
}
| OkraFramework/Okra.Data | src/Okra.Data/Helpers/ResourceHelper.cs | C# | apache-2.0 | 1,010 |
package pro.luxun.luxunanimation.presenter.adapter;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wufeiyang on 16/5/7.
*/
public abstract class BaseRecyclerAdapter<T, V extends View> extends RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder<V>> {
protected List<T> mItems = new ArrayList<>();
@Override
public BaseViewHolder<V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new BaseViewHolder<>(onCreateItemView(parent, viewType));
}
@Override
public int getItemCount() {
return mItems.size();
}
@UiThread
public void refresh(List<T> datas){
mItems.clear();
add(datas);
}
@UiThread
public void add(List<T> datas){
mItems.addAll(datas);
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
V v = (V) holder.itemView;
onBindView(v, mItems.get(position));
}
protected abstract V onCreateItemView(ViewGroup parent, int viewType);
protected abstract void onBindView(V v, T t);
public static class BaseViewHolder<V extends View> extends RecyclerView.ViewHolder{
public BaseViewHolder(V itemView) {
super(itemView);
}
}
}
| ayaseruri/luxunPro | app/src/main/java/pro/luxun/luxunanimation/presenter/adapter/BaseRecyclerAdapter.java | Java | apache-2.0 | 1,444 |
---
title: gocloud.dev/internal/testing/terraform
type: pkg
---
| google/go-cloud | internal/website/content/internal/testing/terraform/_index.md | Markdown | apache-2.0 | 64 |
# Tragopogon dshimilensis K.Koch 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/Magnoliopsida/Asterales/Asteraceae/Tragopogon/Tragopogon porrifolius/ Syn. Tragopogon dshimilensis/README.md | Markdown | apache-2.0 | 187 |
package cn.xmut.experiment.service.impl;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import cn.xmut.experiment.dao.IExperimentDao;
import cn.xmut.experiment.dao.impl.jdbc.ExperimentDaoImpl;
import cn.xmut.experiment.domain.Experiment;
import cn.xmut.experiment.domain.ShowExperiment;
import cn.xmut.experiment.service.IExperimentService;
public class ExperimentServiceImpl implements IExperimentService {
IExperimentDao experimentDao = new ExperimentDaoImpl();
public boolean addExperiment(Experiment experiment, String docName,String dirPath, FileItem fileItem) {
return experimentDao.addExperiment(experiment, docName, dirPath, fileItem);
}
public boolean updateExperiment(Experiment experiment) {
return experimentDao.updateExperiment(experiment);
}
public String getDocPath(int experimentId) {
return experimentDao.getDocPath(experimentId);
}
public Experiment getExperiment(int experimentId) {
return experimentDao.getExperiment(experimentId);
}
public List<ShowExperiment> queryPass(Experiment experiment) {
return experimentDao.queryPass(experiment);
}
public List<ShowExperiment> queryNodistribute(Experiment experiment) {
return experimentDao.queryNodistribute(experiment);
}
public List<ShowExperiment> expertQueryNoExtimate(Experiment experiment, String expertId) {
return experimentDao.expertQueryNoExtimate(experiment, expertId);
}
public List<ShowExperiment> managerQueryNoExtimate(Experiment experiment) {
return experimentDao.managerQueryNoExtimate(experiment);
}
public List<ShowExperiment> managerQueryNoPass(Experiment experiment) {
return experimentDao.managerQueryNoPass(experiment);
}
public boolean delExperiment(Experiment experiment) {
return experimentDao.delExperiment(experiment);
}
public List<ShowExperiment> headmanQueryNoPass(Experiment experiment) {
return experimentDao.headmanQueryNoPass(experiment);
}
}
| bingoogolapple/J2EENote | experiment/src/cn/xmut/experiment/service/impl/ExperimentServiceImpl.java | Java | apache-2.0 | 1,988 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_121) on Sun Oct 15 23:06:23 CEST 2017 -->
<title>Class Hierarchy</title>
<meta name="date" content="2017-10-15">
<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="Class Hierarchy";
}
}
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>Package</li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.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">
<h1 class="title">Hierarchy For All Packages</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="org/shanerx/faketrollplus/core/package-tree.html">org.shanerx.faketrollplus.core</a>, </li>
<li><a href="org/shanerx/faketrollplus/core/data/package-tree.html">org.shanerx.faketrollplus.core.data</a>, </li>
<li><a href="org/shanerx/faketrollplus/utils/function/package-tree.html">org.shanerx.faketrollplus.utils.function</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/GuiUser.html" title="class in org.shanerx.faketrollplus.core"><span class="typeNameLink">GuiUser</span></a></li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/LocalUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">LocalUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/RemoteUserCache.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">RemoteUserCache</span></a> (implements org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data">UserCache</a>)</li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/TrollPlayer.html" title="class in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">TrollPlayer</span></a></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.shanerx.faketrollplus.utils.function.<a href="org/shanerx/faketrollplus/utils/function/EmptyConsumer.html" title="interface in org.shanerx.faketrollplus.utils.function"><span class="typeNameLink">EmptyConsumer</span></a></li>
<li type="circle">org.shanerx.faketrollplus.utils.function.<a href="org/shanerx/faketrollplus/utils/function/Test.html" title="interface in org.shanerx.faketrollplus.utils.function"><span class="typeNameLink">Test</span></a></li>
<li type="circle">org.shanerx.faketrollplus.core.data.<a href="org/shanerx/faketrollplus/core/data/UserCache.html" title="interface in org.shanerx.faketrollplus.core.data"><span class="typeNameLink">UserCache</span></a></li>
</ul>
<h2 title="Enum Hierarchy">Enum Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
<ul>
<li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/TrollEffect.html" title="enum in org.shanerx.faketrollplus.core"><span class="typeNameLink">TrollEffect</span></a> (implements java.io.Serializable)</li>
<li type="circle">org.shanerx.faketrollplus.core.<a href="org/shanerx/faketrollplus/core/GuiType.html" title="enum in org.shanerx.faketrollplus.core"><span class="typeNameLink">GuiType</span></a></li>
</ul>
</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>Package</li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.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 ======= -->
</body>
</html>
| SparklingComet/FakeTrollPlus | doc/overview-tree.html | HTML | apache-2.0 | 6,781 |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* 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
* 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.
*/
namespace YAF.Utils.Helpers
{
using System.Text.RegularExpressions;
/// <summary>
/// The URL helper.
/// </summary>
public static class UrlHelper
{
/// <summary>
/// Counts the URLs.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Returns how many URLs the message contains</returns>
public static int CountUrls(string message)
{
return
Regex.Matches(
message,
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)")
.Count;
}
}
} | Pathfinder-Fr/YAFNET | yafsrc/YAF.Utils/Helpers/UrlHelper.cs | C# | apache-2.0 | 1,676 |
/*
*
* (C) Copyright IBM Corp. and others 1998-2013 - All Rights Reserved
*
*/
#ifndef __SUBTABLEPROCESSOR2_H
#define __SUBTABLEPROCESSOR2_H
/**
* \file
* \internal
*/
#include "LETypes.h"
#include "MorphTables.h"
U_NAMESPACE_BEGIN
class LEGlyphStorage;
class SubtableProcessor2 : public UMemory {
public:
virtual void process(LEGlyphStorage &glyphStorage) = 0;
virtual ~SubtableProcessor2();
protected:
SubtableProcessor2(const MorphSubtableHeader2 *morphSubtableHeader);
SubtableProcessor2();
le_uint32 length;
SubtableCoverage2 coverage;
FeatureFlags subtableFeatures;
const MorphSubtableHeader2 *subtableHeader;
private:
SubtableProcessor2(const SubtableProcessor2 &other); // forbid copying of this class
SubtableProcessor2 &operator=(const SubtableProcessor2 &other); // forbid copying of this class
};
U_NAMESPACE_END
#endif
| indashnet/InDashNet.Open.UN2000 | android/external/icu4c/layout/SubtableProcessor2.h | C | apache-2.0 | 894 |
{%extends "base.html"%}
{% block breadcrumb %}
{% endblock %}
{%block about_this_page %}
<h2>Attachments for Site {{site.number}}</h2>
{% if user.staff %}
<p>
<a href="{{ webapp2.uri_for('SiteView', id=site.key.integer_id()) }}">
Go back to Site #{{ site.number }}.
</a>
</p>
{% endif %}
{% if user.captain %}
<p>
<a href="{{ webapp2.uri_for('CaptainHome') }}">
Go back to your Captain home page.
</a>
</p>
{% endif %}
{% endblock %}
{% block body %}
{% include "site_attachments.html" %}
{% endblock %}
| babybunny/rebuildingtogethercaptain | gae/room/templates/site_list_attachments.html | HTML | apache-2.0 | 520 |
/*!
* Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
overflow-x: hidden;
font-family: "Roboto Slab", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.text-muted {
color: #777;
}
.text-primary {
color: #fed136;
}
p {
font-size: 14px;
line-height: 1.75;
font-family: "Merriweather", serif;
}
p.large {
font-size: 16px;
}
a,
a:hover,
a:focus,
a:active,
a.active {
outline: 0;
}
a {
color: #fed136;
}
a:hover,
a:focus,
a:active,
a.active {
color: #fed136;
}
h1,
h2,
h3,
h4,
h5,
h6 {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
}
.img-centered {
margin: 0 auto;
}
.bg-light-gray {
background-color: #f7f7f7;
}
.bg-darkest-gray {
background-color: #222;
}
.btn-primary {
border-color: #fed136;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #fff;
background-color: #fed136;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
border-color: #f6bf01;
color: #fff;
background-color: #fec503;
}
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
border-color: #fed136;
background-color: #fed136;
}
.btn-primary .badge {
color: #fed136;
background-color: #fff;
}
.btn-xl {
padding: 20px 40px;
border-color: #fed136;
border-radius: 3px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: 700;
color: #fff;
background-color: #fed136;
}
.btn-xl:hover,
.btn-xl:focus,
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
border-color: #f6bf01;
color: #fff;
background-color: #fec503;
}
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
background-image: none;
}
.btn-xl.disabled,
.btn-xl[disabled],
fieldset[disabled] .btn-xl,
.btn-xl.disabled:hover,
.btn-xl[disabled]:hover,
fieldset[disabled] .btn-xl:hover,
.btn-xl.disabled:focus,
.btn-xl[disabled]:focus,
fieldset[disabled] .btn-xl:focus,
.btn-xl.disabled:active,
.btn-xl[disabled]:active,
fieldset[disabled] .btn-xl:active,
.btn-xl.disabled.active,
.btn-xl[disabled].active,
fieldset[disabled] .btn-xl.active {
border-color: #fed136;
background-color: #fed136;
}
.btn-xl .badge {
color: #fed136;
background-color: #fff;
}
.navbar-default {
border-color: transparent;
background-color: #222;
}
.navbar-default .navbar-brand {
font-family: "Jockey One", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #fed136;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus,
.navbar-default .navbar-brand:active,
.navbar-default .navbar-brand.active {
color: #fed136;
}
.navbar-default .navbar-collapse {
border-color: rgba(255, 255, 255, 0.02);
}
.navbar-default .navbar-toggle {
border-color: #fed136;
background-color: #fed136;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #fed136;
}
.navbar-default .nav li a {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 400;
letter-spacing: 1px;
color: #fff;
}
.navbar-default .nav li a:hover,
.navbar-default .nav li a:focus {
outline: 0;
color: #fed136;
}
.navbar-default .navbar-nav > .active > a {
border-radius: 0;
color: #fff;
background-color: #fed136;
}
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #fff;
background-color: #fec503;
}
@media (min-width: 768px) {
.navbar-default {
padding: 25px 0;
border: 0;
background-color: transparent;
-webkit-transition: padding .3s;
-moz-transition: padding .3s;
transition: padding .3s;
}
.navbar-default .navbar-brand {
font-size: 2em;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
.navbar-default .navbar-nav > .active > a {
border-radius: 3px;
}
.navbar-default.navbar-shrink {
padding: 10px 0;
background-color: #222;
}
.navbar-default.navbar-shrink .navbar-brand {
font-size: 1.5em;
}
}
header {
text-align: center;
color: #fff;
background-attachment: scroll;
background-image: url('../img/globe2.jpg');
background-position: center center;
background-repeat: none;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
header .intro-text {
padding-top: 100px;
padding-bottom: 50px;
}
header .intro-text .intro-lead-in {
margin-bottom: 25px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 22px;
font-style: normal;
line-height: 22px;
}
header .intro-text .intro-heading {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 50px;
font-weight: 700;
line-height: 50px;
margin-bottom: 0px;
}
@media (min-width: 768px) {
header .intro-text {
padding-top: 300px;
padding-bottom: 200px;
}
header .intro-text .intro-lead-in {
margin-bottom: 25px;
font-family: "Merriweather", serif;
font-size: 40px;
font-style: italic;
line-height: 40px;
}
header .intro-text .intro-heading {
margin-bottom: 50px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 75px;
font-weight: 700;
line-height: 75px;
}
}
section {
padding: 100px 0;
}
section h2.section-heading {
margin-top: 0;
margin-bottom: 15px;
font-size: 40px;
}
section h3.section-subheading {
margin-bottom: 75px;
text-transform: none;
font-size: 16px;
font-style: italic;
font-weight: 400;
font-family: "Merriweather", serif;
}
@media (min-width: 768px) {
section {
padding: 150px 0;
}
}
.service-heading {
margin: 15px 0;
text-transform: none;
}
#portfolio .portfolio-item {
right: 0;
margin: 0 0 15px;
}
#portfolio .portfolio-item .portfolio-link {
display: block;
position: relative;
margin: 0 auto;
max-width: 400px;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
background: rgba(254, 209, 54, 0.9);
-webkit-transition: all ease .5s;
-moz-transition: all ease .5s;
transition: all ease .5s;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover:hover {
opacity: 1;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content {
position: absolute;
top: 50%;
width: 100%;
height: 20px;
margin-top: -12px;
text-align: center;
font-size: 20px;
color: #fff;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content i {
margin-top: -12px;
}
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h3,
#portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h4 {
margin: 0;
}
#portfolio .portfolio-item .portfolio-caption {
margin: 0 auto;
padding: 25px;
max-width: 400px;
text-align: center;
background-color: #fff;
}
#portfolio .portfolio-item .portfolio-caption h4 {
margin: 0;
text-transform: none;
}
#portfolio .portfolio-item .portfolio-caption p {
margin: 0;
font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
font-style: italic;
}
#portfolio * {
z-index: 2;
}
@media (min-width: 767px) {
#portfolio .portfolio-item {
margin: 0 0 30px;
}
}
.timeline {
position: relative;
padding: 0;
list-style: none;
}
.timeline:before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 40px;
width: 2px;
margin-left: -1.5px;
background-color: #f1f1f1;
}
.timeline > li {
position: relative;
margin-bottom: 50px;
min-height: 50px;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li .timeline-panel {
float: right;
position: relative;
width: 100%;
padding: 0 20px 0 100px;
text-align: left;
}
.timeline > li .timeline-panel:before {
right: auto;
left: -15px;
border-right-width: 15px;
border-left-width: 0;
}
.timeline > li .timeline-panel:after {
right: auto;
left: -14px;
border-right-width: 14px;
border-left-width: 0;
}
.timeline > li .timeline-image {
z-index: 100;
position: absolute;
left: 0;
width: 80px;
height: 80px;
margin-left: 0;
border: 7px solid #f1f1f1;
border-radius: 100%;
text-align: center;
color: #fff;
background-color: #fed136;
}
.timeline > li .timeline-image h4 {
margin-top: 12px;
font-size: 10px;
line-height: 14px;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
padding: 0 20px 0 100px;
text-align: left;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
right: auto;
left: -15px;
border-right-width: 15px;
border-left-width: 0;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
right: auto;
left: -14px;
border-right-width: 14px;
border-left-width: 0;
}
.timeline > li:last-child {
margin-bottom: 0;
}
.timeline .timeline-heading h4 {
margin-top: 0;
color: inherit;
}
.timeline .timeline-heading h4.subheading {
text-transform: none;
}
.timeline .timeline-body > p,
.timeline .timeline-body > ul {
margin-bottom: 0;
}
@media (min-width: 768px) {
.timeline:before {
left: 50%;
}
.timeline > li {
margin-bottom: 100px;
min-height: 100px;
}
.timeline > li .timeline-panel {
float: left;
width: 41%;
padding: 0 20px 20px 30px;
text-align: right;
}
.timeline > li .timeline-image {
left: 50%;
width: 100px;
height: 100px;
margin-left: -50px;
}
.timeline > li .timeline-image h4 {
margin-top: 16px;
font-size: 13px;
line-height: 18px;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
padding: 0 30px 20px 20px;
text-align: left;
}
}
@media (min-width: 992px) {
.timeline > li {
min-height: 150px;
}
.timeline > li .timeline-panel {
padding: 0 20px 20px;
}
.timeline > li .timeline-image {
width: 150px;
height: 150px;
margin-left: -75px;
}
.timeline > li .timeline-image h4 {
margin-top: 30px;
font-size: 18px;
line-height: 26px;
}
.timeline > li.timeline-inverted > .timeline-panel {
padding: 0 20px 20px;
}
}
@media (min-width: 1200px) {
.timeline > li {
min-height: 170px;
}
.timeline > li .timeline-panel {
padding: 0 20px 20px 100px;
}
.timeline > li .timeline-image {
width: 170px;
height: 170px;
margin-left: -85px;
}
.timeline > li .timeline-image h4 {
margin-top: 40px;
}
.timeline > li.timeline-inverted > .timeline-panel {
padding: 0 100px 20px 20px;
}
}
.team-member {
text-align: center;
margin-bottom: -10px;
}
.team-member img {
margin: 0 auto;
border: 5px solid #fff;
}
.team-member h4 {
margin-top: 25px;
margin-bottom: 0;
text-transform: none;
}
.team-member p {
margin-top: 0;
background-color: #fed136;
padding: 15px;
}
aside.clients img {
margin: 50px auto;
}
section#contact {
background-color: #222;
background-image: url(../img/map-image.png);
background-position: center;
background-repeat: no-repeat;
padding-top: 50px;
padding-bottom: 50px;
}
section#contact .section-heading {
color: #fff;
}
section#contact .form-group {
margin-bottom: 25px;
}
section#contact .form-group input,
section#contact .form-group textarea {
padding: 20px;
}
section#contact .form-group input.form-control {
height: auto;
}
section#contact .form-group textarea.form-control {
height: 236px;
}
section#contact .form-control:focus {
border-color: #fed136;
box-shadow: none;
}
section#contact::-webkit-input-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact:-moz-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact::-moz-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact:-ms-input-placeholder {
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: #bbb;
}
section#contact .text-danger {
color: #e74c3c;
}
footer {
padding: 25px 0;
text-align: center;
}
footer span.copyright {
text-transform: none;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 40px;
text-align: left;
}
footer ul.quicklinks {
margin-bottom: 0;
text-transform: uppercase;
text-transform: none;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 40px;
}
ul.social-buttons {
margin-bottom: 0;
}
ul.social-buttons li a {
display: block;
width: 40px;
height: 40px;
border-radius: 100%;
font-size: 20px;
line-height: 40px;
outline: 0;
color: #fff;
background-color: #222;
-webkit-transition: all .3s;
-moz-transition: all .3s;
transition: all .3s;
}
ul.social-buttons li a:hover,
ul.social-buttons li a:focus,
ul.social-buttons li a:active {
background-color: #fed136;
}
.btn:focus,
.btn:active,
.btn.active,
.btn:active:focus {
outline: 0;
}
.portfolio-modal .modal-content {
padding: 100px 0;
min-height: 100%;
border: 0;
border-radius: 0;
text-align: center;
background-clip: border-box;
-webkit-box-shadow: none;
box-shadow: none;
}
.portfolio-modal .modal-content h2 {
margin-bottom: 15px;
font-size: 3em;
}
.portfolio-modal .modal-content p {
margin-bottom: 30px;
}
.portfolio-modal .modal-content p.item-intro {
margin: 20px 0 30px;
font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 16px;
font-style: italic;
}
.portfolio-modal .modal-content ul.list-inline {
margin-top: 0;
margin-bottom: 30px;
}
.portfolio-modal .modal-content img {
margin-bottom: 30px;
}
.portfolio-modal .close-modal {
position: absolute;
top: 25px;
right: 25px;
width: 75px;
height: 75px;
background-color: transparent;
cursor: pointer;
}
.portfolio-modal .close-modal:hover {
opacity: .3;
}
.portfolio-modal .close-modal .lr {
z-index: 1051;
width: 1px;
height: 75px;
margin-left: 35px;
background-color: #222;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.portfolio-modal .close-modal .lr .rl {
z-index: 1052;
width: 1px;
height: 75px;
background-color: #222;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.portfolio-modal .modal-backdrop {
display: none;
opacity: 0;
}
::-moz-selection {
text-shadow: none;
background: #fed136;
}
::selection {
text-shadow: none;
background: #fed136;
}
img::selection {
background: 0 0;
}
img::-moz-selection {
background: 0 0;
}
body {
webkit-tap-highlight-color: #fed136;
}
.margins {
margin-left: 60px;
margin-right: 60px;
}
.photo {
margin-bottom: 0px;
margin-top: 0px;
padding-top: 70px;
padding-left: 0px;
margin-right: 0px;
left: 0px;
}
.professor {
padding-top: 100px;
padding-bottom: 0;
}
.biografia {
padding-bottom: 0px;
margin-bottom: 50px;
}
.depoimento {
margin-top: 30px;
}
.testemunho {
margin-top: 17px;
}
.testemunho h4 {
margin-bottom: 0;
}
section#pacotes {
background-color: #222;
}
section#pacotes .section-heading {
color: #fff;
}
section#contact h3 {
color: #fff;
}
section#contact p {
color: #fff;
}
.demo {
margin-left: 50px;
padding: 20px 40px;
border-color: #c6ccd2;
border-radius: 3px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: 700;
color: #fff;
background-color: #c6ccd2;
}
.demo:hover {
color: #fff;
background-color: #767676;
}
.email {
line-height: 30px;
font-weight: 400;
height: 65px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 22px;
}
section#demo {
padding-top: 55px;
padding-bottom: 55px;
background-color: #fed136;
}
.enviar {
margin-left: 0px;
padding: 20px 40px;
border-color: #c6ccd2;
border-radius: 3px;
text-transform: uppercase;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: 700;
color: #fff;
background-color: #3996cc;
}
.enviar:hover {
color: #fff;
background-color: #3386b7;
}
section#demo p {
color: #222;
margin-top: 10px;
font-size: 14px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
section#demo h3 {
text-transform: none;
margin-top: 0;
}
.logo {
color: #fed136;
text-transform: none;
font-size: 21px;
font-family: "Jockey One", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.glyphicon {
color: #fff;
}
section#contact .col-md-10,
.col-lg-10 {
margin-left: 0px;
padding-left: 3px;
}
.fa {
color: #222;
border: 10px;
background-color: #fff;
padding: 3px 6px 2px 5px;
border-radius: 9px;
margin-right: 0px;
margin-left: -3px;
}
.pacote {
background-color: #3996cc;
padding: 14px 8px 13px;
color: #fff;
text-align: center;
margin: 0;
}
section#pacotes p {
color: #222;
margin-top: 0;
font-size: 14px;
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
padding: 8px;
font-weight: 200;
text-align: center;
border-top: 0;
border-bottom: 1px;
border-style: solid;
border-color: #ddd;
border-left: 0;
border-right: 0;
margin-bottom: 0;
}
section#pacotes h4 {
padding: 18px 8px;
color: #fff;
text-align: center;
background-color: #767676;
text-transform: none;
font-size: 35px;
margin: 0;
}
section#pacotes h5 {
padding: 15px 8px;
color: #222;
text-align: center;
background-color: #f6f6f6;
text-transform: none;
margin: 0;
font-size: 17px;
}
section#pacotes p.large {
color: #f7f7f7;
border: none;
text-align: left;
font-weight: 100;
font-size: 12px;
margin-top: 5px;
}
section#pacotes .col-md-10 {
padding-right: 0;
padding-left: 0;
}
.super {
border: 15px;
color: #e52323;
border-color: #fed136;
background-color: #df9898;
}
.pacote-coluna {
background-color: #fff;
padding-left: 0;
padding-right: 0;
border: 0.5px;
border-style: solid;
border-color: #ddd;
}
.pacote-max {
background-color: #fff;
padding-left: 0;
padding-right: 0;
border: 9px;
border-style: solid;
border-color: #fed136;
margin-top: -9px;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 7px;
border-bottom-left-radius: 7px;
}
.valor {
background-color: #fed136;
padding-left: 0;
padding-right: 0;
border: 9px;
border-style: solid;
border-color: #fed136;
margin-top: -9px;
border-top-left-radius: 7px;
border-top-right-radius: 7px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
height: 29px;
}
.valor h5 {
background-color: #fed136;
font-size: 14px;
}
.valor h6 {
margin-top: 0;
text-align: center;
margin-bottom: 0;
}
header h1 {
text-transform: none;
font-style: normal;
font-weight: 100;
margin-top: -26px;
margin-bottom: 0px;
}
header .row {
margin-top: 0px;
}
section#portfolio p {
margin-bottom: 67px;
}
section#portfolio {
padding-bottom: 68px;
}
section#about strong {
text-align: right;
text-transform: none;
font-size: 18px;
font-style: italic;
font-family: "Merriweather", serif;
}
section#services img {
border: 5px;
border-color: #f7f7f7;
border-style: solid;
border-radius: 52px;
}
| hichamidiomas/hichamidiomas.github.io | css/_pgbackup/agency_1424038683.css | CSS | apache-2.0 | 20,625 |
/**
* @file
* Declares the any type.
*/
#pragma once
#include "../values/forward.hpp"
#include <ostream>
namespace puppet { namespace runtime { namespace types {
// Forward declaration of recursion_guard
struct recursion_guard;
/**
* Represents the Puppet Any type.
*/
struct any
{
/**
* Gets the name of the type.
* @return Returns the name of the type (i.e. Any).
*/
static char const* name();
/**
* Creates a generalized version of the type.
* @return Returns the generalized type.
*/
values::type generalize() const;
/**
* Determines if the given value is an instance of this type.
* @param value The value to determine if it is an instance of this type.
* @param guard The recursion guard to use for aliases.
* @return Returns true if the given value is an instance of this type or false if not.
*/
bool is_instance(values::value const& value, recursion_guard& guard) const;
/**
* Determines if the given type is assignable to this type.
* @param other The other type to check for assignability.
* @param guard The recursion guard to use for aliases.
* @return Returns true if the given type is assignable to this type or false if the given type is not assignable to this type.
*/
bool is_assignable(values::type const& other, recursion_guard& guard) const;
/**
* Writes a representation of the type to the given stream.
* @param stream The stream to write to.
* @param expand True to specify that type aliases should be expanded or false if not.
*/
void write(std::ostream& stream, bool expand = true) const;
};
/**
* Stream insertion operator for any type.
* @param os The output stream to write the type to.
* @param type The type to write.
* @return Returns the given output stream.
*/
std::ostream& operator<<(std::ostream& os, any const& type);
/**
* Equality operator for any.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Always returns true (Any type is always equal to Any).
*/
bool operator==(any const& left, any const& right);
/**
* Inequality operator for any.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Always returns false (Any type is always equal to Any).
*/
bool operator!=(any const& left, any const& right);
/**
* Hashes the any type.
* @param type The any type to hash.
* @return Returns the hash value for the type.
*/
size_t hash_value(any const& type);
}}} // namespace puppet::runtime::types
| peterhuene/puppetcpp | lib/include/puppet/runtime/types/any.hpp | C++ | apache-2.0 | 2,856 |
package im.mange.jetpac.html
import im.mange.jetpac.{Styleable, Renderable, R}
import net.liftweb.http.SHtml.ajaxInvoke
import net.liftweb.http.js.JsCmd
//TODO: ultimately Tr or ClickableTr
//TODO: do the style in the same way as the inputs onClick etc ...
@deprecated("Use Tr instead", "28/08/2015")
case class ClickableRow(id: Option[String], onClick: () ⇒ JsCmd, cells: Renderable*) extends Renderable with Styleable {
def render = <tr id={id.getOrElse("")} class={classes.render} style={styles.render} onclick={ajaxInvoke(onClick).toJsCmd}>{R(cells).render}</tr>
}
| alltonp/jetboot | src/main/scala/im/mange/jetpac/html/ClickableRow.scala | Scala | apache-2.0 | 575 |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: testsetfieldasstring()</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - [email protected] -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_functions';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logFunction('testsetfieldasstring');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Function and Method Cross Reference</h3>
<h2><a href="index.html#testsetfieldasstring">testsetfieldasstring()</a></h2>
<b>Defined at:</b><ul>
<li><a href="../tests/simpletest/test/acceptance_test.php.html#testsetfieldasstring">/tests/simpletest/test/acceptance_test.php</a> -> <a onClick="logFunction('testsetfieldasstring', '/tests/simpletest/test/acceptance_test.php.source.html#l185')" href="../tests/simpletest/test/acceptance_test.php.source.html#l185"> line 185</a></li>
</ul>
<b>No references found.</b><br><br>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| inputx/code-ref-doc | bonfire/_functions/testsetfieldasstring.html | HTML | apache-2.0 | 4,787 |
package server
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strings"
"sync"
"sync/atomic"
"text/template"
"time"
"github.com/TV4/graceful"
"github.com/gogap/config"
"github.com/gogap/go-wkhtmltox/wkhtmltox"
"github.com/gorilla/mux"
"github.com/phyber/negroni-gzip/gzip"
"github.com/rs/cors"
"github.com/spf13/cast"
"github.com/urfave/negroni"
)
const (
defaultTemplateText = `{"code":{{.Code}},"message":"{{.Message}}"{{if .Result}},"result":{{.Result|jsonify}}{{end}}}`
)
var (
htmlToX *wkhtmltox.WKHtmlToX
renderTmpls = make(map[string]*template.Template)
defaultTmpl *template.Template
)
type ConvertData struct {
Data []byte `json:"data"`
}
type ConvertArgs struct {
To string `json:"to"`
Fetcher wkhtmltox.FetcherOptions `json:"fetcher"`
Converter json.RawMessage `json:"converter"`
Template string `json:"template"`
}
type TemplateArgs struct {
To string
ConvertResponse
Response *RespHelper
}
type ConvertResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Result interface{} `json:"result"`
}
type serverWrapper struct {
tls bool
certFile string
keyFile string
reqNumber int64
addr string
n *negroni.Negroni
timeout time.Duration
}
func (p *serverWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&p.reqNumber, 1)
defer atomic.AddInt64(&p.reqNumber, -1)
p.n.ServeHTTP(w, r)
}
func (p *serverWrapper) ListenAndServe() (err error) {
if p.tls {
err = http.ListenAndServeTLS(p.addr, p.certFile, p.keyFile, p)
} else {
err = http.ListenAndServe(p.addr, p)
}
return
}
func (p *serverWrapper) Shutdown(ctx context.Context) error {
num := atomic.LoadInt64(&p.reqNumber)
schema := "HTTP"
if p.tls {
schema = "HTTPS"
}
beginTime := time.Now()
for num > 0 {
time.Sleep(time.Second)
timeDiff := time.Now().Sub(beginTime)
if timeDiff > p.timeout {
break
}
}
log.Printf("[%s] Shutdown finished, Address: %s\n", schema, p.addr)
return nil
}
type WKHtmlToXServer struct {
conf config.Configuration
servers []*serverWrapper
}
func New(conf config.Configuration) (srv *WKHtmlToXServer, err error) {
serviceConf := conf.GetConfig("service")
wkHtmlToXConf := conf.GetConfig("wkhtmltox")
htmlToX, err = wkhtmltox.New(wkHtmlToXConf)
if err != nil {
return
}
// init templates
defaultTmpl, err = template.New("default").Funcs(funcMap).Parse(defaultTemplateText)
if err != nil {
return
}
err = loadTemplates(
serviceConf.GetConfig("templates"),
)
if err != nil {
return
}
// init http server
c := cors.New(
cors.Options{
AllowedOrigins: serviceConf.GetStringList("cors.allowed-origins"),
AllowedMethods: serviceConf.GetStringList("cors.allowed-methods"),
AllowedHeaders: serviceConf.GetStringList("cors.allowed-headers"),
ExposedHeaders: serviceConf.GetStringList("cors.exposed-headers"),
AllowCredentials: serviceConf.GetBoolean("cors.allow-credentials"),
MaxAge: int(serviceConf.GetInt64("cors.max-age")),
OptionsPassthrough: serviceConf.GetBoolean("cors.options-passthrough"),
Debug: serviceConf.GetBoolean("cors.debug"),
},
)
r := mux.NewRouter()
pathPrefix := serviceConf.GetString("path", "/")
r.PathPrefix(pathPrefix).Path("/convert").
Methods("POST").
HandlerFunc(handleHtmlToX)
r.PathPrefix(pathPrefix).Path("/ping").
Methods("GET", "HEAD").HandlerFunc(
func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
rw.Write([]byte("pong"))
},
)
n := negroni.Classic()
n.Use(c) // use cors
if serviceConf.GetBoolean("gzip-enabled", true) {
n.Use(gzip.Gzip(gzip.DefaultCompression))
}
n.UseHandler(r)
gracefulTimeout := serviceConf.GetTimeDuration("graceful.timeout", time.Second*3)
enableHTTP := serviceConf.GetBoolean("http.enabled", true)
enableHTTPS := serviceConf.GetBoolean("https.enabled", false)
var servers []*serverWrapper
if enableHTTP {
listenAddr := serviceConf.GetString("http.address", "127.0.0.1:8080")
httpServer := &serverWrapper{
n: n,
timeout: gracefulTimeout,
addr: listenAddr,
}
servers = append(servers, httpServer)
}
if enableHTTPS {
listenAddr := serviceConf.GetString("http.address", "127.0.0.1:443")
certFile := serviceConf.GetString("https.cert")
keyFile := serviceConf.GetString("https.key")
httpsServer := &serverWrapper{
n: n,
timeout: gracefulTimeout,
addr: listenAddr,
tls: true,
certFile: certFile,
keyFile: keyFile,
}
servers = append(servers, httpsServer)
}
srv = &WKHtmlToXServer{
conf: conf,
servers: servers,
}
return
}
func (p *WKHtmlToXServer) Run() (err error) {
wg := sync.WaitGroup{}
wg.Add(len(p.servers))
for i := 0; i < len(p.servers); i++ {
go func(srv *serverWrapper) {
defer wg.Done()
shcema := "HTTP"
if srv.tls {
shcema = "HTTPS"
}
log.Printf("[%s] Listening on %s\n", shcema, srv.addr)
graceful.ListenAndServe(srv)
}(p.servers[i])
}
wg.Wait()
return
}
func writeResp(rw http.ResponseWriter, convertArgs ConvertArgs, resp ConvertResponse) {
var tmpl *template.Template
if len(convertArgs.Template) == 0 {
tmpl = defaultTmpl
} else {
var exist bool
tmpl, exist = renderTmpls[convertArgs.Template]
if !exist {
tmpl = defaultTmpl
}
}
respHelper := newRespHelper(rw)
args := TemplateArgs{
To: convertArgs.To,
ConvertResponse: resp,
Response: respHelper,
}
buf := bytes.NewBuffer(nil)
err := tmpl.Execute(buf, args)
if err != nil {
log.Println(err)
}
if !respHelper.Holding() {
rw.Write(buf.Bytes())
}
}
func handleHtmlToX(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
decoder.UseNumber()
args := ConvertArgs{}
err := decoder.Decode(&args)
if err != nil {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil})
return
}
if len(args.Converter) == 0 {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, "converter is nil", nil})
return
}
to := strings.ToUpper(args.To)
var opts wkhtmltox.ConvertOptions
if to == "IMAGE" {
opts = &wkhtmltox.ToImageOptions{}
} else if to == "PDF" {
opts = &wkhtmltox.ToPDFOptions{}
} else {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, "argument of to is illegal (image|pdf)", nil})
return
}
err = json.Unmarshal(args.Converter, opts)
if err != nil {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil})
return
}
var convData []byte
convData, err = htmlToX.Convert(args.Fetcher, opts)
if err != nil {
writeResp(rw, args, ConvertResponse{http.StatusBadRequest, err.Error(), nil})
return
}
writeResp(rw, args, ConvertResponse{0, "", ConvertData{Data: convData}})
return
}
func loadTemplates(tmplsConf config.Configuration) (err error) {
if tmplsConf == nil {
return
}
tmpls := tmplsConf.Keys()
for _, name := range tmpls {
file := tmplsConf.GetString(name + ".template")
tmpl := template.New(name).Funcs(funcMap)
var data []byte
data, err = ioutil.ReadFile(file)
if err != nil {
return
}
tmpl, err = tmpl.Parse(string(data))
if err != nil {
return
}
renderTmpls[name] = tmpl
}
return
}
type RespHelper struct {
rw http.ResponseWriter
hold bool
}
func newRespHelper(rw http.ResponseWriter) *RespHelper {
return &RespHelper{
rw: rw,
hold: false,
}
}
func (p *RespHelper) SetHeader(key, value interface{}) error {
k := cast.ToString(key)
v := cast.ToString(value)
p.rw.Header().Set(k, v)
return nil
}
func (p *RespHelper) Hold(v interface{}) error {
h := cast.ToBool(v)
p.hold = h
return nil
}
func (p *RespHelper) Holding() bool {
return p.hold
}
func (p *RespHelper) Write(data []byte) error {
p.rw.Write(data)
return nil
}
func (p *RespHelper) WriteHeader(code interface{}) error {
c, err := cast.ToIntE(code)
if err != nil {
return err
}
p.rw.WriteHeader(c)
return nil
}
| gogap/go-wkhtmltox | server/server.go | GO | apache-2.0 | 8,166 |
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.collection.primitive;
public interface PrimitiveLongIntVisitor<E extends Exception>
{
/**
* Visit the given entry.
*
* @param key The key of the entry.
* @param value The value of the entry.
* @return 'true' to signal that the iteration should be stopped, 'false' to signal that the iteration should
* continue if there are more entries to look at.
* @throws E any thrown exception of type 'E' will bubble up through the 'visit' method.
*/
boolean visited( long key, int value ) throws E;
}
| HuangLS/neo4j | community/primitive-collections/src/main/java/org/neo4j/collection/primitive/PrimitiveLongIntVisitor.java | Java | apache-2.0 | 1,354 |
package org.anyline.entity;
import com.fasterxml.jackson.databind.JsonNode;
import org.anyline.util.*;
import org.anyline.util.regular.Regular;
import org.anyline.util.regular.RegularUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
public class DataSet implements Collection<DataRow>, Serializable {
private static final long serialVersionUID = 6443551515441660101L;
protected static final Logger log = LoggerFactory.getLogger(DataSet.class);
private boolean result = true; // 执行结果
private Exception exception = null; // 异常
private String message = null; // 提示信息
private PageNavi navi = null; // 分页
private List<String> head = null; // 表头
private List<DataRow> rows = null; // 数据
private List<String> primaryKeys = null; // 主键
private String datalink = null; // 数据连接
private String dataSource = null; // 数据源(表|视图|XML定义SQL)
private String schema = null;
private String table = null;
private long createTime = 0; //创建时间
private long expires = -1; //过期时间(毫秒) 从创建时刻计时expires毫秒后过期
private boolean isFromCache = false; //是否来自缓存
private boolean isAsc = false;
private boolean isDesc = false;
private Map<String, Object> queryParams = new HashMap<String, Object>();//查询条件
/**
* 创建索引
*
* @param key key
* @return return
* crateIndex("ID");
* crateIndex("ID:ASC");
*/
public DataSet creatIndex(String key) {
return this;
}
public DataSet() {
rows = new ArrayList<DataRow>();
createTime = System.currentTimeMillis();
}
public DataSet(List<Map<String, Object>> list) {
rows = new ArrayList<DataRow>();
if (null == list)
return;
for (Map<String, Object> map : list) {
DataRow row = new DataRow(map);
rows.add(row);
}
}
public static DataSet build(Collection<?> list, String ... fields) {
return parse(list, fields);
}
/**
* list解析成DataSet
* @param list list
* @param fields 如果list是二维数据
* fields 下标对应的属性(字段/key)名称 如"ID","CODE","NAME"
* 如果不输入则以下标作为DataRow的key 如row.put("0","100").put("1","A01").put("2","张三");
* 如果属性数量超出list长度,取null值存入DataRow
*
* 如果list是一组数组
* fileds对应条目的属性值 如果不输入 则以条目的属性作DataRow的key 如"USER_ID:id","USER_NM:name"
*
* @return DataSet
*/
public static DataSet parse(Collection<?> list, String ... fields) {
DataSet set = new DataSet();
if (null != list) {
for (Object obj : list) {
DataRow row = null;
if(obj instanceof Collection){
row = DataRow.parseList((Collection)obj, fields);
}else {
row = DataRow.parse(obj, fields);
}
set.add(row);
}
}
return set;
}
public static DataSet parseJson(DataRow.KEY_CASE keyCase, String json) {
if (null != json) {
try {
return parseJson(keyCase, BeanUtil.JSON_MAPPER.readTree(json));
} catch (Exception e) {
}
}
return null;
}
public static DataSet parseJson(String json) {
return parseJson(DataRow.KEY_CASE.CONFIG, json);
}
public static DataSet parseJson(DataRow.KEY_CASE keyCase, JsonNode json) {
DataSet set = new DataSet();
if (null != json) {
if (json.isArray()) {
Iterator<JsonNode> items = json.iterator();
while (items.hasNext()) {
JsonNode item = items.next();
set.add(DataRow.parseJson(keyCase, item));
}
}
}
return set;
}
public static DataSet parseJson(JsonNode json) {
return parseJson(DataRow.KEY_CASE.CONFIG, json);
}
public DataSet Camel(){
for(DataRow row:rows){
row.Camel();
}
return this;
}
public DataSet camel(){
for(DataRow row:rows){
row.camel();
}
return this;
}
public DataSet setIsNew(boolean bol) {
for (DataRow row : rows) {
row.setIsNew(bol);
}
return this;
}
/**
* 移除每个条目中指定的key
*
* @param keys keys
* @return DataSet
*/
public DataSet remove(String... keys) {
for (DataRow row : rows) {
for (String key : keys) {
row.remove(key);
}
}
return this;
}
public DataSet trim(){
for(DataRow row:rows){
row.trim();
}
return this;
}
/**
* 添加主键
*
* @param applyItem 是否应用到集合中的DataRow 默认true
* @param pks pks
* @return return
*/
public DataSet addPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
addPrimaryKey(applyItem, list);
}
return this;
}
public DataSet addPrimaryKey(String... pks) {
return addPrimaryKey(true, pks);
}
public DataSet addPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
if (null == pks) {
return this;
}
for (String pk : pks) {
if (BasicUtil.isEmpty(pk)) {
continue;
}
pk = key(pk);
if (!primaryKeys.contains(pk)) {
primaryKeys.add(pk);
}
}
if (applyItem) {
for (DataRow row : rows) {
row.setPrimaryKey(false, primaryKeys);
}
}
return this;
}
public DataSet addPrimaryKey(Collection<String> pks) {
return addPrimaryKey(true, pks);
}
/**
* 设置主键
*
* @param applyItem applyItem
* @param pks pks
* @return return
*/
public DataSet setPrimaryKey(boolean applyItem, String... pks) {
if (null != pks) {
List<String> list = new ArrayList<>();
for (String pk : pks) {
list.add(pk);
}
setPrimaryKey(applyItem, list);
}
return this;
}
public DataSet setPrimaryKey(String... pks) {
return setPrimaryKey(true, pks);
}
public DataSet setPrimaryKey(boolean applyItem, Collection<String> pks) {
if (null == pks) {
return this;
}
this.primaryKeys = new ArrayList<>();
addPrimaryKey(applyItem, pks);
return this;
}
public DataSet setPrimaryKey(Collection<String> pks) {
return setPrimaryKey(true, pks);
}
public DataSet set(int index, DataRow item) {
rows.set(index, item);
return this;
}
/**
* 是否有主键
*
* @return return
*/
public boolean hasPrimaryKeys() {
if (null != primaryKeys && primaryKeys.size() > 0) {
return true;
} else {
return false;
}
}
/**
* 提取主键
*
* @return return
*/
public List<String> getPrimaryKeys() {
if (null == primaryKeys) {
primaryKeys = new ArrayList<>();
}
return primaryKeys;
}
/**
* 添加表头
*
* @param col col
* @return return
*/
public DataSet addHead(String col) {
if (null == head) {
head = new ArrayList<>();
}
if ("ROW_NUMBER".equals(col)) {
return this;
}
if (head.contains(col)) {
return this;
}
head.add(col);
return this;
}
/**
* 表头
*
* @return return
*/
public List<String> getHead() {
return head;
}
public int indexOf(Object obj) {
return rows.indexOf(obj);
}
/**
* 从begin开始截断到end,方法执行将改变原DataSet长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataSet truncates(int begin, int end) {
if (!rows.isEmpty()) {
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
rows = rows.subList(begin, end);
}
return this;
}
/**
* 从begin开始截断到最后一个
*
* @param begin 开始位置
* @return DataSet
*/
public DataSet truncates(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return truncates(begin, end);
} else {
return truncates(begin, rows.size() - 1);
}
}
/**
* 从begin开始截断到最后一个并返回其中第一个DataRow
*
* @param begin 开始位置
* @return DataRow
*/
public DataRow truncate(int begin) {
return truncate(begin, rows.size() - 1);
}
/**
* 从begin开始截断到end位置并返回其中第一个DataRow
*
* @param begin 开始位置
* @param end 结束位置
* @return DataRow
*/
public DataRow truncate(int begin, int end) {
truncates(begin, end);
if (rows.size() > 0) {
return rows.get(0);
} else {
return null;
}
}
/**
* 从begin开始截取到最后一个
*
* @param begin 开始位置
* 如果输入负数则取后n个,如果造成数量不足,则取全部
* @return DataSet
*/
public DataSet cuts(int begin) {
if (begin < 0) {
begin = rows.size() + begin;
int end = rows.size() - 1;
return cuts(begin, end);
} else {
return cuts(begin, rows.size() - 1);
}
}
/**
* 从begin开始截取到end位置,方法执行时会创建新的DataSet并不改变原有set长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataSet cuts(int begin, int end) {
DataSet result = new DataSet();
if (rows.isEmpty()) {
return result;
}
if (begin < 0) {
begin = 0;
}
if (end >= rows.size()) {
end = rows.size() - 1;
}
if (begin >= rows.size()) {
begin = rows.size() - 1;
}
if (end <= 0) {
end = 0;
}
for (int i = begin; i <= end; i++) {
result.add(rows.get(i));
}
return result;
}
/**
* 从begin开始截取到最后一个,并返回其中第一个DataRow
*
* @param begin 开始位置
* @return DataSet
*/
public DataRow cut(int begin) {
return cut(begin, rows.size() - 1);
}
/**
* 从begin开始截取到end位置,并返回其中第一个DataRow,方法执行时会创建新的DataSet并不改变原有set长度
*
* @param begin 开始位置
* @param end 结束位置
* @return DataSet
*/
public DataRow cut(int begin, int end) {
DataSet result = cuts(begin, end);
if (result.size() > 0) {
return result.getRow(0);
}
return null;
}
/**
* 记录数量
*
* @return return
*/
public int size() {
int result = 0;
if (null != rows)
result = rows.size();
return result;
}
public int getSize() {
return size();
}
/**
* 是否出现异常
*
* @return return
*/
public boolean isException() {
return null != exception;
}
public boolean isFromCache() {
return isFromCache;
}
public DataSet setIsFromCache(boolean bol) {
this.isFromCache = bol;
return this;
}
/**
* 返回数据是否为空
*
* @return return
*/
public boolean isEmpty() {
boolean result = true;
if (null == rows) {
result = true;
} else if (rows instanceof Collection) {
result = ((Collection<?>) rows).isEmpty();
}
return result;
}
/**
* 读取一行数据
*
* @param index index
* @return return
*/
public DataRow getRow(int index) {
DataRow row = null;
if (null != rows && index < rows.size()) {
row = rows.get(index);
}
if (null != row) {
row.setContainer(this);
}
return row;
}
public boolean exists(String ... params){
DataRow row = getRow(0, params);
return row != null;
}
public DataRow getRow(String... params) {
return getRow(0, params);
}
public DataRow getRow(DataRow params) {
return getRow(0, params);
}
public DataRow getRow(List<String> params) {
String[] kvs = BeanUtil.list2array(params);
return getRow(0, kvs);
}
public DataRow getRow(int begin, String... params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
public DataRow getRow(int begin, DataRow params) {
DataSet set = getRows(begin, 1, params);
if (set.size() > 0) {
return set.getRow(0);
}
return null;
}
/**
* 根据keys去重
*
* @param keys keys
* @return DataSet
*/
public DataSet distinct(String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
DataRow row = rows.get(i);
//查看result中是否已存在
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public DataSet distinct(List<String> keys) {
DataSet result = new DataSet();
if (null != rows) {
for (DataRow row:rows) {
//查看result中是否已存在
String[] params = packParam(row, keys);
if (result.getRow(params) == null) {
DataRow tmp = new DataRow();
for (String key : keys) {
tmp.put(key, row.get(key));
}
result.addRow(tmp);
}
}
}
result.cloneProperty(this);
return result;
}
public Object clone() {
DataSet set = new DataSet();
List<DataRow> rows = new ArrayList<DataRow>();
for (DataRow row : this.rows) {
rows.add((DataRow) row.clone());
}
set.setRows(rows);
set.cloneProperty(this);
return set;
}
private DataSet cloneProperty(DataSet from) {
return cloneProperty(from, this);
}
public static DataSet cloneProperty(DataSet from, DataSet to) {
if (null != from && null != to) {
to.exception = from.exception;
to.message = from.message;
to.navi = from.navi;
to.head = from.head;
to.primaryKeys = from.primaryKeys;
to.dataSource = from.dataSource;
to.datalink = from.datalink;
to.schema = from.schema;
to.table = from.table;
}
return to;
}
/**
* 指定key转换成number
* @param keys keys
* @return DataRow
*/
public DataSet convertNumber(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertNumber(keys);
}
}
return this;
}
public DataSet convertString(String ... keys){
if(null != keys) {
for(DataRow row:rows){
row.convertString(keys);
}
}
return this;
}
public DataSet skip(boolean skip){
for(DataRow row:rows){
row.skip = skip;
}
return this;
}
/**
* 筛选符合条件的集合
* 注意如果String类型 1与1.0比较不相等, 可以先调用convertNumber转换一下数据类型
* @param params key1,value1,key2:value2,key3,value3
* "NM:zh%","AGE:>20","NM","%zh%"
* @param begin begin
* @param qty 最多筛选多少个 0表示不限制
* @return return
*/
public DataSet getRows(int begin, int qty, String... params) {
DataSet set = new DataSet();
Map<String, String> kvs = new HashMap<String, String>();
int len = params.length;
int i = 0;
String srcFlagTag = "srcFlag"; //参数含有{}的 在kvs中根据key值+tag 放入一个新的键值对,如时间格式TIME:{10:10}
while (i < len) {
String p1 = params[i];
if (BasicUtil.isEmpty(p1)) {
i++;
continue;
} else if (p1.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(p1);
kvs.put(ks[0], ks[1]);
i++;
continue;
} else {
if (i + 1 < len) {
String p2 = params[i + 1];
if (BasicUtil.isEmpty(p2) || !p2.contains(":")) {
kvs.put(p1, p2);
i += 2;
continue;
} else if (p2.startsWith("{") && p2.endsWith("}")) {
p2 = p2.substring(1, p2.length() - 1);
kvs.put(p1, p2);
kvs.put(p1 + srcFlagTag, "true");
i += 2;
continue;
} else {
String ks[] = BeanUtil.parseKeyValue(p2);
kvs.put(ks[0], ks[1]);
i += 2;
continue;
}
}
}
i++;
}
return getRows(begin, qty, kvs);
}
public DataSet getRows(int begin, int qty, DataRow kvs) {
Map<String,String> map = new HashMap<String,String>();
for(String k:kvs.keySet()){
map.put(k, kvs.getString(k));
}
return getRows(begin, qty, map);
}
public DataSet getRows(int begin, int qty, Map<String, String> kvs) {
DataSet set = new DataSet();
String srcFlagTag = "srcFlag"; //参数含有{}的 在kvs中根据key值+tag 放入一个新的键值对
BigDecimal d1;
BigDecimal d2;
for (DataRow row:rows) {
if(row.skip){
continue;
}
boolean chk = true;//对比结果
for (String k : kvs.keySet()) {
boolean srcFlag = false;
if (k.endsWith(srcFlagTag)) {
continue;
} else {
String srcFlagValue = kvs.get(k + srcFlagTag);
if (BasicUtil.isNotEmpty(srcFlagValue)) {
srcFlag = true;
}
}
String v = kvs.get(k);
Object value = row.get(k);
if(!row.containsKey(k) && null == value){
//注意这里有可能是个复合key
chk = false;
break;
}
if (null == v) {
if (null != value) {
chk = false;
break;
}else{
continue;
}
} else {
if (null == value) {
chk = false;
break;
}
//与SQL.COMPARE_TYPE保持一致
int compare = 10;
if (v.startsWith("=")) {
compare = 10;
v = v.substring(1);
} else if (v.startsWith(">")) {
compare = 20;
v = v.substring(1);
} else if (v.startsWith(">=")) {
compare = 21;
v = v.substring(2);
} else if (v.startsWith("<")) {
compare = 30;
v = v.substring(1);
} else if (v.startsWith("<=")) {
compare = 31;
v = v.substring(2);
} else if (v.startsWith("%") && v.endsWith("%")) {
compare = 50;
v = v.substring(1, v.length() - 1);
} else if (v.endsWith("%")) {
compare = 51;
v = v.substring(0, v.length() - 1);
} else if (v.startsWith("%")) {
compare = 52;
v = v.substring(1);
}
if(compare <= 31 && value instanceof Number) {
try {
d1 = new BigDecimal(value.toString());
d2 = new BigDecimal(v);
int cr = d1.compareTo(d2);
if (compare == 10) {
if (cr != 0) {
chk = false;
break;
}
} else if (compare == 20) {
if (cr <= 0) {
chk = false;
break;
}
} else if (compare == 21) {
if (cr < 0) {
chk = false;
break;
}
} else if (compare == 30) {
if (cr >= 0) {
chk = false;
break;
}
} else if (compare == 31) {
if (cr > 0) {
chk = false;
break;
}
}
}catch (NumberFormatException e){
chk = false;
break;
}
}
String str = value + "";
str = str.toLowerCase();
v = v.toLowerCase();
if (srcFlag) {
v = "{" + v + "}";
}
if (compare == 10) {
if (!v.equals(str)) {
chk = false;
break;
}
} else if (compare == 50) {
if (!str.contains(v)) {
chk = false;
break;
}
} else if (compare == 51) {
if (!str.startsWith(v)) {
chk = false;
break;
}
} else if (compare == 52) {
if (!str.endsWith(v)) {
chk = false;
break;
}
}
}
}//end for kvs
if (chk) {
set.add(row);
if (qty > 0 && set.size() >= qty) {
break;
}
}
}//end for rows
set.cloneProperty(this);
return set;
}
public DataSet getRows(int begin, String... params) {
return getRows(begin, -1, params);
}
public DataSet getRows(String... params) {
return getRows(0, params);
}
public DataSet getRows(DataSet set, String key) {
String kvs[] = new String[set.size()];
int i = 0;
for (DataRow row : set) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
kvs[i++] = key + ":" + value;
}
}
return getRows(kvs);
}
public DataSet getRows(DataRow row, String... keys) {
List<String> list = new ArrayList<>();
int i = 0;
for (String key : keys) {
String value = row.getString(key);
if (BasicUtil.isNotEmpty(value)) {
list.add(key + ":" + value);
}
}
String[] kvs = BeanUtil.list2array(list);
return getRows(kvs);
}
/**
* 数字格式化
*
* @param format format
* @param cols cols
* @return return
*/
public DataSet formatNumber(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatNumber(format, cols);
}
return this;
}
public DataSet numberFormat(String target, String key, String format){
for(DataRow row: rows){
numberFormat(target, key, format);
}
return this;
}
public DataSet numberFormat(String key, String format){
return numberFormat(key, key, format);
}
/**
* 日期格式化
*
* @param format format
* @param cols cols
* @return return
*/
public DataSet formatDate(String format, String... cols) {
if (null == cols || BasicUtil.isEmpty(format)) {
return this;
}
int size = size();
for (int i = 0; i < size; i++) {
DataRow row = getRow(i);
row.formatDate(format, cols);
}
return this;
}
public DataSet dateFormat(String target, String key, String format){
for(DataRow row: rows){
dateFormat(target, key, format);
}
return this;
}
public DataSet dateFormat(String key, String format){
return dateFormat(key, key, format);
}
/**
* 提取符合指定属性值的集合
*
* @param begin begin
* @param end end
* @param key key
* @param value value
* @return return
*/
public DataSet filter(int begin, int end, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
int size = size();
if (begin < 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
tmpValue = getString(i, key, "");
if ((null == value && null == tmpValue)
|| (null != value && value.equals(tmpValue))) {
set.add(getRow(i));
}
}
set.cloneProperty(this);
return set;
}
public DataSet getRows(int fr, int to) {
DataSet set = new DataSet();
int size = this.size();
if (fr < 0) {
fr = 0;
}
for (int i = fr; i < size && i <= to; i++) {
set.addRow(getRow(i));
}
return set;
}
/**
* 合计
* @param begin 开始
* @param end 结束
* @param key key
* @return BigDecimal
*/
public BigDecimal sum(int begin, int end, String key) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (begin <= 0) {
begin = 0;
}
for (int i = begin; i < size && i <= end; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(getDecimal(i, key, 0));
}
}
return result;
}
public BigDecimal sum(String key) {
BigDecimal result = BigDecimal.ZERO;
result = sum(0, size() - 1, key);
return result;
}
/**
* 多列合计
* @param result 保存合计结果
* @param keys keys
* @return DataRow
*/
public DataRow sums(DataRow result, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, sum(key));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, sum(key));
}
}
}
return result;
}
public DataRow sums(String... keys) {
return sums(new DataRow(), keys);
}
/**
* 多列平均值
*
* @param result 保存合计结果
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, avg(key));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, avg(key));
}
}
}
return result;
}
public DataRow avgs(String... keys) {
return avgs(new DataRow(), keys);
}
/**
* 多列平均值
* @param result 保存合计结果
* @param scale scale
* @param round round
* @param keys keys
* @return DataRow
*/
public DataRow avgs(DataRow result, int scale, int round, String... keys) {
if(null == result){
result = new DataRow();
}
if (size() > 0) {
if (null != keys) {
for (String key : keys) {
result.put(key, avg(key, scale, round));
}
} else {
List<String> numberKeys = getRow(0).numberKeys();
for (String key : numberKeys) {
result.put(key, avg(key, scale, round));
}
}
}
return result;
}
public DataRow avgs(int scale, int round, String... keys) {
return avgs(new DataRow(), scale, round, keys);
}
/**
* 最大值
*
* @param top 多少行
* @param key key
* @return return
*/
public BigDecimal maxDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) > 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal maxDecimal(String key) {
return maxDecimal(size(), key);
}
public int maxInt(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int maxInt(String key) {
return maxInt(size(), key);
}
public double maxDouble(int top, String key) {
BigDecimal result = maxDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double maxDouble(String key) {
return maxDouble(size(), key);
}
// public BigDecimal max(int top, String key){
// BigDecimal result = maxDecimal(top, key);
// return result;
// }
// public BigDecimal max(String key){
// return maxDecimal(size(), key);
// }
/**
* 最小值
*
* @param top 多少行
* @param key key
* @return return
*/
public BigDecimal minDecimal(int top, String key) {
BigDecimal result = null;
int size = rows.size();
if (size > top) {
size = top;
}
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp && (null == result || tmp.compareTo(result) < 0)) {
result = tmp;
}
}
return result;
}
public BigDecimal minDecimal(String key) {
return minDecimal(size(), key);
}
public int minInt(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.intValue();
}
public int minInt(String key) {
return minInt(size(), key);
}
public double minDouble(int top, String key) {
BigDecimal result = minDecimal(top, key);
if (null == result) {
return 0;
}
return result.doubleValue();
}
public double minDouble(String key) {
return minDouble(size(), key);
}
// public BigDecimal min(int top, String key){
// BigDecimal result = minDecimal(top, key);
// return result;
// }
// public BigDecimal min(String key){
// return minDecimal(size(), key);
// }
/**
* key对应的value最大的一行
*
* @param key key
* @return return
*/
public DataRow max(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(size - 1);
} else if (isDesc) {
row = getRow(0);
} else {
asc(key);
row = getRow(size - 1);
}
return row;
}
public DataRow min(String key) {
int size = size();
if (size == 0) {
return null;
}
DataRow row = null;
if (isAsc) {
row = getRow(0);
} else if (isDesc) {
row = getRow(size - 1);
} else {
asc(key);
row = getRow(0);
}
return row;
}
/**
* 平均值 空数据不参与加法但参与除法
*
* @param top 多少行
* @param key key
* @param scale scale
* @param round round
* @return return
*/
public BigDecimal avg(int top, String key, int scale, int round) {
BigDecimal result = BigDecimal.ZERO;
int size = rows.size();
if (size > top) {
size = top;
}
int count = 0;
for (int i = 0; i < size; i++) {
BigDecimal tmp = getDecimal(i, key, 0);
if (null != tmp) {
result = result.add(tmp);
}
count++;
}
if (count > 0) {
result = result.divide(new BigDecimal(count), scale, round);
}
return result;
}
public BigDecimal avg(String key, int scale, int round) {
BigDecimal result = avg(size(), key, scale ,round);
return result;
}
public BigDecimal avg(String key) {
BigDecimal result = avg(size(), key, 2, BigDecimal.ROUND_HALF_UP);
return result;
}
public DataSet addRow(DataRow row) {
if (null != row) {
rows.add(row);
}
return this;
}
public DataSet addRow(int idx, DataRow row) {
if (null != row) {
rows.add(idx, row);
}
return this;
}
/**
* 合并key例的值 以connector连接
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concat(String key, String connector) {
return BasicUtil.concat(getStrings(key), connector);
}
public String concatNvl(String key, String connector) {
return BasicUtil.concat(getNvlStrings(key), connector);
}
/**
* 合并key例的值 以connector连接(不取null值)
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concatWithoutNull(String key, String connector) {
return BasicUtil.concat(getStringsWithoutNull(key), connector);
}
/**
* 合并key例的值 以connector连接(不取空值)
*
* @param key key
* @param connector connector
* @return return v1,v2,v3
*/
public String concatWithoutEmpty(String key, String connector) {
return BasicUtil.concat(getStringsWithoutEmpty(key), connector);
}
public String concatNvl(String key) {
return BasicUtil.concat(getNvlStrings(key), ",");
}
public String concatWithoutNull(String key) {
return BasicUtil.concat(getStringsWithoutNull(key), ",");
}
public String concatWithoutEmpty(String key) {
return BasicUtil.concat(getStringsWithoutEmpty(key), ",");
}
public String concat(String key) {
return BasicUtil.concat(getStrings(key), ",");
}
/**
* 提取单列值
*
* @param key key
* @return return
*/
public List<Object> fetchValues(String key) {
List<Object> result = new ArrayList<Object>();
for (int i = 0; i < size(); i++) {
result.add(get(i, key));
}
return result;
}
/**
* 取单列不重复的值
*
* @param key key
* @return return
*/
public List<String> fetchDistinctValue(String key) {
List<String> result = new ArrayList<>();
for (int i = 0; i < size(); i++) {
String value = getString(i, key, "");
if (result.contains(value)) {
continue;
}
result.add(value);
}
return result;
}
public List<String> fetchDistinctValues(String key) {
return fetchDistinctValue(key);
}
/**
* 分页
*
* @param link link
* @return return
*/
public String displayNavi(String link) {
String result = "";
if (null != navi) {
result = navi.getHtml();
}
return result;
}
public String navi(String link) {
return displayNavi(link);
}
public String displayNavi() {
return displayNavi(null);
}
public String navi() {
return displayNavi(null);
}
public DataSet put(int idx, String key, Object value) {
DataRow row = getRow(idx);
if (null != row) {
row.put(key, value);
}
return this;
}
public DataSet removes(String... keys) {
for (DataRow row : rows) {
row.removes(keys);
}
return this;
}
/**
* String
*
* @param index index
* @param key key
* @return String
* @throws Exception Exception
*/
public String getString(int index, String key) throws Exception {
return getRow(index).getString(key);
}
public String getString(int index, String key, String def) {
try {
return getString(index, key);
} catch (Exception e) {
return def;
}
}
public String getString(String key) throws Exception {
return getString(0, key);
}
public String getString(String key, String def) {
return getString(0, key, def);
}
public Object get(int index, String key) {
DataRow row = getRow(index);
if (null != row) {
return row.get(key);
}
return null;
}
public List<Object> gets(String key) {
List<Object> list = new ArrayList<Object>();
for (DataRow row : rows) {
list.add(row.getString(key));
}
return list;
}
public List<DataSet> getSets(String key) {
List<DataSet> list = new ArrayList<DataSet>();
for (DataRow row : rows) {
DataSet set = row.getSet(key);
if (null != set) {
list.add(set);
}
}
return list;
}
public List<String> getStrings(String key) {
List<String> result = new ArrayList<>();
for (DataRow row : rows) {
result.add(row.getString(key));
}
return result;
}
public List<Integer> getInts(String key) throws Exception {
List<Integer> result = new ArrayList<Integer>();
for (DataRow row : rows) {
result.add(row.getInt(key));
}
return result;
}
public List<Object> getObjects(String key) {
List<Object> result = new ArrayList<Object>();
for (DataRow row : rows) {
result.add(row.get(key));
}
return result;
}
public List<String> getDistinctStrings(String key) {
return fetchDistinctValue(key);
}
public List<String> getNvlStrings(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
} else {
result.add("");
}
}
return result;
}
public List<String> getStringsWithoutEmpty(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (BasicUtil.isNotEmpty(val)) {
result.add(val.toString());
}
}
return result;
}
public List<String> getStringsWithoutNull(String key) {
List<String> result = new ArrayList<>();
List<Object> list = fetchValues(key);
for (Object val : list) {
if (null != val) {
result.add(val.toString());
}
}
return result;
}
public BigDecimal getDecimal(int idx, String key) throws Exception {
return getRow(idx).getDecimal(key);
}
public BigDecimal getDecimal(int idx, String key, double def) {
return getDecimal(idx, key, new BigDecimal(def));
}
public BigDecimal getDecimal(int idx, String key, BigDecimal def) {
try {
BigDecimal val = getDecimal(idx, key);
if (null == val) {
return def;
}
return val;
} catch (Exception e) {
return def;
}
}
/**
* 抽取指定列生成新的DataSet 新的DataSet只包括指定列的值与分页信息,不包含其他附加信息(如来源表)
* @param keys keys
* @return DataSet
*/
public DataSet extract(String ... keys){
DataSet result = new DataSet();
for(DataRow row:rows){
DataRow item = row.extract(keys);
result.add(item);
}
result.navi = this.navi;
return result;
}
public DataSet extract(List<String> keys){
DataSet result = new DataSet();
for(DataRow row:rows){
DataRow item = row.extract(keys);
result.add(item);
}
result.navi = this.navi;
return result;
}
/**
* html格式(未实现)
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public String getHtmlString(int index, String key) throws Exception {
return getString(index, key);
}
public String getHtmlString(int index, String key, String def) {
return getString(index, key, def);
}
public String getHtmlString(String key) throws Exception {
return getHtmlString(0, key);
}
/**
* escape String
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public String getEscapeString(int index, String key) throws Exception {
return EscapeUtil.escape(getString(index, key)).toString();
}
public String getEscapeString(int index, String key, String def) {
try {
return getEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.escape(def).toString();
}
}
public String getDoubleEscapeString(int index, String key) throws Exception {
return EscapeUtil.doubleEscape(getString(index, key));
}
public String getDoubleEscapeString(int index, String key, String def) {
try {
return getDoubleEscapeString(index, key);
} catch (Exception e) {
return EscapeUtil.doubleEscape(def);
}
}
public String getEscapeString(String key) throws Exception {
return getEscapeString(0, key);
}
public String getDoubleEscapeString(String key) throws Exception {
return getDoubleEscapeString(0, key);
}
/**
* int
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public int getInt(int index, String key) throws Exception {
return getRow(index).getInt(key);
}
public int getInt(int index, String key, int def) {
try {
return getInt(index, key);
} catch (Exception e) {
return def;
}
}
public int getInt(String key) throws Exception {
return getInt(0, key);
}
public int getInt(String key, int def) {
return getInt(0, key, def);
}
/**
* double
*
* @param index index
* @param key key
* @return return
* @throws Exception Exception
*/
public double getDouble(int index, String key) throws Exception {
return getRow(index).getDouble(key);
}
public double getDouble(int index, String key, double def) {
try {
return getDouble(index, key);
} catch (Exception e) {
return def;
}
}
public double getDouble(String key) throws Exception {
return getDouble(0, key);
}
public double getDouble(String key, double def) {
return getDouble(0, key, def);
}
/**
* 在key列基础上 +value,如果原来没有key列则默认0并put到target
* @param target 计算结果key
* @param key key
* @param value value
* @return this
*/
public DataSet add(String target, String key, int value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, double value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, short value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, float value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.add(target, key, value);
}
return this;
}
public DataSet add(String key, int value){
return add(key, key, value);
}
public DataSet add(String key, double value){
return add(key, key, value);
}
public DataSet add(String key, short value){
return add(key, key, value);
}
public DataSet add(String key, float value){
return add(key, key, value);
}
public DataSet add(String key, BigDecimal value){
return add(key, key, value);
}
public DataSet subtract(String target, String key, int value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, double value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, short value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, float value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.subtract(target, key, value);
}
return this;
}
public DataSet subtract(String key, int value){
return subtract(key, key, value);
}
public DataSet subtract(String key, double value){
return subtract(key, key, value);
}
public DataSet subtract(String key, short value){
return subtract(key, key, value);
}
public DataSet subtract(String key, float value){
return subtract(key, key, value);
}
public DataSet subtract(String key, BigDecimal value){
return subtract(key, key, value);
}
public DataSet multiply(String target, String key, int value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, double value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, short value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, float value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String target, String key, BigDecimal value){
for(DataRow row:rows){
row.multiply(target, key, value);
}
return this;
}
public DataSet multiply(String key, int value){
return multiply(key,key,value);
}
public DataSet multiply(String key, double value){
return multiply(key,key,value);
}
public DataSet multiply(String key, short value){
return multiply(key,key,value);
}
public DataSet multiply(String key, float value){
return multiply(key,key,value);
}
public DataSet multiply(String key, BigDecimal value){
return multiply(key,key,value);
}
public DataSet divide(String target, String key, int value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, double value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, short value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, float value){
for(DataRow row:rows){
row.divide(target, key, value);
}
return this;
}
public DataSet divide(String target, String key, BigDecimal value, int mode){
for(DataRow row:rows){
row.divide(target, key, value, mode);
}
return this;
}
public DataSet divide(String key, int value){
return divide(key,key, value);
}
public DataSet divide(String key, double value){
return divide(key,key, value);
}
public DataSet divide(String key, short value){
return divide(key,key, value);
}
public DataSet divide(String key, float value){
return divide(key,key, value);
}
public DataSet divide(String key, BigDecimal value, int mode){
return divide(key,key, value, mode);
}
public DataSet round(String target, String key, int scale, int mode){
for (DataRow row:rows){
row.round(target, key, scale, mode);
}
return this;
}
public DataSet round(String key, int scale, int mode){
return round(key, key, scale, mode);
}
/**
* DataSet拆分成size部分
* @param page 拆成多少部分
* @return list
*/
public List<DataSet> split(int page){
List<DataSet> list = new ArrayList<>();
int size = this.size();
int vol = size / page;//每页多少行
for(int i=0; i<page; i++){
int fr = i*vol;
int to = (i+1)*vol-1;
if(i == page-1){
to = size-1;
}
DataSet set = this.cuts(fr, to);
list.add(set);
}
return list;
}
/**
* rows 列表中的数据格式化成json格式 不同与toJSON
* map.put("type", "list");
* map.put("result", result);
* map.put("message", message);
* map.put("rows", rows);
* map.put("success", result);
* map.put("navi", navi);
*/
public String toString() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("type", "list");
map.put("result", result);
map.put("message", message);
map.put("rows", rows);
map.put("success", result);
if(null != navi){
Map<String,Object> navi_ = new HashMap<String,Object>();
navi_.put("page", navi.getCurPage());
navi_.put("pages", navi.getTotalPage());
navi_.put("rows", navi.getTotalRow());
navi_.put("vol", navi.getPageRows());
map.put("navi", navi_);
}
return BeanUtil.map2json(map);
}
/**
* rows 列表中的数据格式化成json格式 不同与toString
*
* @return return
*/
public String toJson() {
return BeanUtil.object2json(this);
}
public String getJson() {
return toJSON();
}
public String toJSON() {
return toJson();
}
/**
* 根据指定列生成map
*
* @param key ID,{ID}_{NM}
* @return return
*/
public Map<String, DataRow> toMap(String key) {
Map<String, DataRow> maps = new HashMap<String, DataRow>();
for (DataRow row : rows) {
maps.put(row.getString(key), row);
}
return maps;
}
/**
* 子类
*
* @param idx idx
* @return return
*/
public Object getChildren(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getChildren();
}
return null;
}
public Object getChildren() {
return getChildren(0);
}
public DataSet setChildren(int idx, Object children) {
DataRow row = getRow(idx);
if (null != row) {
row.setChildren(children);
}
return this;
}
public DataSet setChildren(Object children) {
setChildren(0, children);
return this;
}
/**
* 父类
*
* @param idx idx
* @return return
*/
public Object getParent(int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.getParent();
}
return null;
}
public Object getParent() {
return getParent(0);
}
public DataSet setParent(int idx, Object parent) {
DataRow row = getRow(idx);
if (null != row) {
row.setParent(parent);
}
return this;
}
public DataSet setParent(Object parent) {
setParent(0, parent);
return this;
}
/**
* 转换成对象
*
* @param <T> T
* @param index index
* @param clazz clazz
* @return return
*/
public <T> T entity(int index, Class<T> clazz) {
DataRow row = getRow(index);
if (null != row) {
return row.entity(clazz);
}
return null;
}
/**
* 转换成对象集合
*
* @param <T> T
* @param clazz clazz
* @return return
*/
public <T> List<T> entity(Class<T> clazz) {
List<T> list = new ArrayList<T>();
if (null != rows) {
for (DataRow row : rows) {
list.add(row.entity(clazz));
}
}
return list;
}
public <T> T entity(Class<T> clazz, int idx) {
DataRow row = getRow(idx);
if (null != row) {
return row.entity(clazz);
}
return null;
}
public DataSet setDataSource(String dataSource) {
if (null == dataSource) {
return this;
}
this.dataSource = dataSource;
if (dataSource.contains(".") && !dataSource.contains(":")) {
schema = dataSource.substring(0, dataSource.indexOf("."));
table = dataSource.substring(dataSource.indexOf(".") + 1);
}
for (DataRow row : rows) {
if (BasicUtil.isEmpty(row.getDataSource())) {
row.setDataSource(dataSource);
}
}
return this;
}
/**
* 合并
* @param set DataSet
* @param keys 根据keys去重
* @return DataSet
*/
public DataSet union(DataSet set, String... keys) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
if (null == keys || keys.length == 0) {
keys = new String[1];
keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY");
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
if (!result.contains(item, keys)) {
result.add(item);
}
}
return result;
}
/**
* 合并合并不去重
*
* @param set set
* @return return
*/
public DataSet unionAll(DataSet set) {
DataSet result = new DataSet();
if (null != rows) {
int size = rows.size();
for (int i = 0; i < size; i++) {
result.add(rows.get(i));
}
}
int size = set.size();
for (int i = 0; i < size; i++) {
DataRow item = set.getRow(i);
result.add(item);
}
return result;
}
/**
* 是否包含这一行
*
* @param row row
* @param keys keys
* @return return
*/
public boolean contains(DataRow row, String... keys) {
if (null == rows || rows.size() == 0 || null == row) {
return false;
}
if (null == keys || keys.length == 0) {
keys = new String[1];
keys[0] = ConfigTable.getString("DEFAULT_PRIMARY_KEY", "ID");
}
String params[] = packParam(row, keys);
return exists(params);
}
public String[] packParam(DataRow row, String... keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.length * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* 根据数据与属性列表 封装kvs
* ["ID","1","CODE","A01"]
* @param row 数据 DataRow
* @param keys 属性 ID,CODE
* @return kvs
*/
public String[] packParam(DataRow row, List<String> keys) {
if (null == keys || null == row) {
return null;
}
String params[] = new String[keys.size() * 2];
int idx = 0;
for (String key : keys) {
if (null == key) {
continue;
}
String ks[] = BeanUtil.parseKeyValue(key);
params[idx++] = ks[0];
params[idx++] = row.getString(ks[1]);
}
return params;
}
/**
* 从items中按相应的key提取数据 存入
* dispatch("children",items, "DEPAT_CD")
* dispatchs("children",items, "CD:BASE_CD")
*
* @param field 默认"ITEMS"
* @param unique 是否只分配一次(同一个条目不能分配到多个组中)
* @param recursion 是否递归
* @param items items
* @param keys keys ID:DEPT_ID或ID
* @return return
*/
public DataSet dispatchs(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
if(null == keys || keys.length == 0){
throw new RuntimeException("未指定对应关系");
}
if (null == items) {
return this;
}
if (BasicUtil.isEmpty(field)) {
field = "ITEMS";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] kvs = packParam(row, reverseKey(keys));
DataSet set = items.getRows(kvs);
if (recursion) {
set.dispatchs(field, unique, recursion, items, keys);
}
if(unique) {
set.skip(true);
}
row.put(field, set);
}
}
items.skip(false);
return this;
}
public DataSet dispatchs(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs("ITEMS", unique, recursion, items, keys);
}
public DataSet dispatchs(String field, DataSet items, String... keys) {
return dispatchs(field,false, false, items, keys);
}
public DataSet dispatchs(DataSet items, String... keys) {
return dispatchs("ITEMS", items, keys);
}
public DataSet dispatchs(boolean unique, boolean recursion, String... keys) {
return dispatchs("ITEMS", unique, recursion, this, keys);
}
public DataSet dispatchs(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
if(null == keys || keys.length == 0){
throw new RuntimeException("未指定对应关系");
}
if (null == items) {
return this;
}
if (BasicUtil.isEmpty(field)) {
field = "ITEM";
}
for (DataRow row : rows) {
if (null == row.get(field)) {
String[] params = packParam(row, reverseKey(keys));
DataRow result = items.getRow(params);
if(unique){
result.skip = true;
}
row.put(field, result);
}
}
items.skip(false);
return this;
}
public DataSet dispatch(String field, DataSet items, String... keys) {
return dispatch(field, false, false, items, keys);
}
public DataSet dispatch(DataSet items, String... keys) {
return dispatch("ITEM", items, keys);
}
public DataSet dispatch(boolean unique, boolean recursion, String... keys) {
return dispatch("ITEM", unique, recursion, this, keys);
}
public DataSet dispatch(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, this, keys);
}
/**
* 直接调用dispatchs
* @param field 默认"ITEMS"
* @param unique 是否只分配一次(同一个条目不能分配到多个组中)
* @param recursion 是否递归
* @param items items
* @param keys keys ID:DEPT_ID或ID
* @return return
*/
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatchs( unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItems(String field, DataSet items, String... keys) {
return dispatchs(field, items, keys);
}
@Deprecated
public DataSet dispatchItems(DataSet items, String... keys) {
return dispatchs(items, keys);
}
@Deprecated
public DataSet dispatchItems(boolean unique, boolean recursion, String... keys) {
return dispatchs( unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItems(String field, boolean unique, boolean recursion, String... keys) {
return dispatchs(field, unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, DataSet items, String... keys) {
return dispatch(field, unique, recursion, items, keys);
}
@Deprecated
public DataSet dispatchItem(String field, DataSet items, String... keys) {
return dispatch(field, items, keys);
}
@Deprecated
public DataSet dispatchItem(DataSet items, String... keys) {
return dispatch(items, keys);
}
@Deprecated
public DataSet dispatchItem(boolean unique, boolean recursion, String... keys) {
return dispatch(unique, recursion, keys);
}
@Deprecated
public DataSet dispatchItem(String field, boolean unique, boolean recursion, String... keys) {
return dispatch(field, unique, recursion, keys);
}
/**
* 根据keys列建立关联,并将关联出来的结果拼接到集合的条目上,如果有重复则覆盖条目
*
* @param items 被查询的集合
* @param keys 关联条件列
* @return return
*/
public DataSet join(DataSet items, String... keys) {
if (null == items || null == keys || keys.length == 0) {
return this;
}
for (DataRow row : rows) {
String[] params = packParam(row, reverseKey(keys));
DataRow result = items.getRow(params);
if (null != result) {
row.copy(result, result.keys());
}
}
return this;
}
public DataSet toLowerKey() {
for (DataRow row : rows) {
row.toLowerKey();
}
return this;
}
public DataSet toUpperKey() {
for (DataRow row : rows) {
row.toUpperKey();
}
return this;
}
/**
* 按keys分组
*
* @param keys keys
* @return return
*/
public DataSet group(String... keys) {
DataSet result = distinct(keys);
result.dispatchs(true,false, this, keys);
return result;
}
public DataSet or(DataSet set, String... keys) {
return this.union(set, keys);
}
public DataSet getRows(Map<String, String> kvs) {
return getRows(0, -1, kvs);
}
/**
* 多个集合的交集
*
* @param distinct 是否根据keys抽取不重复的集合
* @param sets 集合
* @param keys 判断依据
* @return DataSet
*/
public static DataSet intersection(boolean distinct, List<DataSet> sets, String... keys) {
DataSet result = null;
if (null != sets && sets.size() > 0) {
for (DataSet set : sets) {
if (null == result) {
result = set;
} else {
result = result.intersection(distinct, set, keys);
}
}
}
if (null == result) {
result = new DataSet();
}
return result;
}
public static DataSet intersection(List<DataSet> sets, String... keys) {
return intersection(false, sets, keys);
}
/**
* 交集
*
* @param distinct 是否根据keys抽取不重复的集合(根据keys去重)
* @param set set
* @param keys 根据keys列比较是否相等,如果列名不一致"ID:USER_ID",ID表示当前DataSet的列,USER_ID表示参数中DataSet的列
* @return return
*/
public DataSet intersection(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
if (null == set) {
return result;
}
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (set.contains(row, kv)) { //符合交集
if(!result.contains(row, kv)){//result中没有
result.add((DataRow) row.clone());
}else {
if(!distinct){//result中有但不要求distinct
result.add((DataRow) row.clone());
}
}
}
}
return result;
}
public DataSet intersection(DataSet set, String... keys) {
return intersection(false, set, keys);
}
public DataSet and(boolean distinct, DataSet set, String... keys) {
return intersection(distinct, set, keys);
}
public DataSet and(DataSet set, String... keys) {
return intersection(false, set, keys);
}
/**
* 补集
* 在this中,但不在set中
* this作为超集 set作为子集
*
* @param distinct 是否根据keys抽取不重复的集合
* @param set set
* @param keys keys
* @return return
*/
public DataSet complement(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet complement(DataSet set, String... keys) {
return complement(false, set, keys);
}
/**
* 差集
* 从当前集合中删除set中存在的row,生成新的DataSet并不修改当前对象
* this中有 set中没有的
*
* @param distinct 是否根据keys抽取不重复的集合
* @param set set
* @param keys CD,"CD:WORK_CD"
* @return return
*/
public DataSet difference(boolean distinct, DataSet set, String... keys) {
DataSet result = new DataSet();
for (DataRow row : rows) {
String[] kv = reverseKey(keys);
if (null == set || !set.contains(row, kv)) {
if (!distinct || !result.contains(row, kv)) {
result.add((DataRow) row.clone());
}
}
}
return result;
}
public DataSet difference(DataSet set, String... keys) {
return difference(false, set, keys);
}
/**
* 颠倒kv-vk
*
* @param keys kv
* @return String[]
*/
private String[] reverseKey(String[] keys) {
if (null == keys) {
return new String[0];
}
int size = keys.length;
String result[] = new String[size];
for (int i = 0; i < size; i++) {
String key = keys[i];
if (BasicUtil.isNotEmpty(key) && key.contains(":")) {
String ks[] = BeanUtil.parseKeyValue(key);
key = ks[1] + ":" + ks[0];
}
result[i] = key;
}
return result;
}
/**
* 清除指定列全为空的行,如果不指定keys,则清除所有列都为空的行
*
* @param keys keys
* @return DataSet
*/
public DataSet removeEmptyRow(String... keys) {
int size = this.size();
for (int i = size - 1; i >= 0; i--) {
DataRow row = getRow(i);
if (null == keys || keys.length == 0) {
if (row.isEmpty()) {
this.remove(row);
}
} else {
boolean isEmpty = true;
for (String key : keys) {
if (row.isNotEmpty(key)) {
isEmpty = false;
break;
}
}
if (isEmpty) {
this.remove(row);
}
}
}
return this;
}
public DataSet changeKey(String key, String target, boolean remove) {
for(DataRow row:rows){
row.changeKey(key, target, remove);
}
return this;
}
public DataSet changeKey(String key, String target) {
return changeKey(key, target, true);
}
/**
* 删除rows中的columns列
*
* @param columns 检测的列,如果不输入则检测所有列
* @return DataSet
*/
public DataSet removeColumn(String... columns) {
if (null != columns) {
for (String column : columns) {
for (DataRow row : rows) {
row.remove(column);
}
}
}
return this;
}
/**
* 删除rows中值为空(null|'')的列
*
* @param columns 检测的列,如果不输入则检测所有列
* @return DataSet
*/
public DataSet removeEmptyColumn(String... columns) {
for (DataRow row : rows) {
row.removeEmpty(columns);
}
return this;
}
/**
* NULL > ""
*
* @return DataSet
*/
public DataSet nvl() {
for (DataRow row : rows) {
row.nvl();
}
return this;
}
/* ********************************************** 实现接口 *********************************************************** */
public boolean add(DataRow e) {
return rows.add((DataRow) e);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public boolean addAll(Collection c) {
return rows.addAll(c);
}
public void clear() {
rows.clear();
}
public boolean contains(Object o) {
return rows.contains(o);
}
public boolean containsAll(Collection<?> c) {
return rows.containsAll(c);
}
public Iterator<DataRow> iterator() {
return rows.iterator();
}
public boolean remove(Object o) {
return rows.remove(o);
}
public boolean removeAll(Collection<?> c) {
return rows.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return rows.retainAll(c);
}
public Object[] toArray() {
return rows.toArray();
}
@SuppressWarnings("unchecked")
public Object[] toArray(Object[] a) {
return rows.toArray(a);
}
public String getSchema() {
return schema;
}
public DataSet setSchema(String schema) {
this.schema = schema;
return this;
}
public String getTable() {
return table;
}
public DataSet setTable(String table) {
if (null != table && table.contains(".")) {
String[] tbs = table.split("\\.");
this.table = tbs[1];
this.schema = tbs[0];
} else {
this.table = table;
}
return this;
}
/**
* 验证是否过期
* 根据当前时间与创建时间对比
* 过期返回 true
*
* @param millisecond 过期时间(毫秒) millisecond 过期时间(毫秒)
* @return boolean
*/
public boolean isExpire(int millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire(long millisecond) {
if (System.currentTimeMillis() - createTime > millisecond) {
return true;
}
return false;
}
public boolean isExpire() {
if (getExpires() == -1) {
return false;
}
if (System.currentTimeMillis() - createTime > getExpires()) {
return true;
}
return false;
}
public long getCreateTime() {
return createTime;
}
public List<DataRow> getRows() {
return rows;
}
/************************** getter setter ***************************************/
/**
* 过期时间(毫秒)
*
* @return long
*/
public long getExpires() {
return expires;
}
public DataSet setExpires(long millisecond) {
this.expires = millisecond;
return this;
}
public DataSet setExpires(int millisecond) {
this.expires = millisecond;
return this;
}
public boolean isResult() {
return result;
}
public boolean isSuccess() {
return result;
}
public DataSet setResult(boolean result) {
this.result = result;
return this;
}
public Exception getException() {
return exception;
}
public DataSet setException(Exception exception) {
this.exception = exception;
return this;
}
public String getMessage() {
return message;
}
public DataSet setMessage(String message) {
this.message = message;
return this;
}
public PageNavi getNavi() {
return navi;
}
public DataSet setNavi(PageNavi navi) {
this.navi = navi;
return this;
}
public DataSet setRows(List<DataRow> rows) {
this.rows = rows;
return this;
}
public String getDataSource() {
String ds = table;
if (BasicUtil.isNotEmpty(ds) && BasicUtil.isNotEmpty(schema)) {
ds = schema + "." + ds;
}
if (BasicUtil.isEmpty(ds)) {
ds = dataSource;
}
return ds;
}
public DataSet order(final String... keys) {
return asc(keys);
}
public DataSet put(String key, Object value, boolean pk, boolean override) {
for (DataRow row : rows) {
row.put(key, value, pk, override);
}
return this;
}
public DataSet put(String key, Object value, boolean pk) {
for (DataRow row : rows) {
row.put(key, value, pk);
}
return this;
}
public DataSet put(String key, Object value) {
for (DataRow row : rows) {
row.put(key, value);
}
return this;
}
/**
* 行转列
* 表结构(编号, 姓名, 年度, 科目, 分数, 等级)
* @param pks 唯一标识key(如编号,姓名)
* @param classKeys 分类key(如年度,科目)
* @param valueKeys 取值key(如分数,等级),如果不指定key则将整行作为value
* @return
* 如果指定key
* 返回结构 [
* {编号:01,姓名:张三,2010-数学-分数:100},
* {编号:01,姓名:张三,2010-数学-等级:A},
* {编号:01,姓名:张三,2010-物理-分数:100}
* ]
* 如果只有一个valueKey则返回[
* {编号:01,姓名:张三,2010-数学:100},
* {编号:01,姓名:张三,2010-物理:90}
* ]
* 不指定valuekey则返回 [
* {编号:01,姓名:张三,2010-数学:{分数:100,等级:A}},
* {编号:01,姓名:张三,2010-物理:{分数:100,等级:A}}
* ]
*/
public DataSet pivot(List<String> pks, List<String> classKeys, List<String> valueKeys) {
DataSet result = distinct(pks);
DataSet classValues = distinct(classKeys); //[{年度:2010,科目:数学},{年度:2010,科目:物理},{年度:2011,科目:数学}]
for (DataRow row : result) {
for (DataRow classValue : classValues) {
DataRow params = new DataRow();
params.copy(row, pks).copy(classValue);
DataRow valueRow = getRow(params);
if(null != valueRow){
valueRow.skip = true;
}
String finalKey = concatValue(classValue,"-");//2010-数学
if(null != valueKeys && valueKeys.size() > 0){
if(valueKeys.size() == 1){
if (null != valueRow) {
row.put(finalKey, valueRow.get(valueKeys.get(0)));
} else {
row.put(finalKey, null);
}
}else {
for (String valueKey : valueKeys) {
//{2010-数学-分数:100;2010-数学-等级:A}
if (null != valueRow) {
row.put(finalKey + "-" + valueKey, valueRow.get(valueKey));
} else {
row.put(finalKey + "-" + valueKey, null);
}
}
}
}else{
if (null != valueRow){
row.put(finalKey, valueRow);
}else{
row.put(finalKey, null);
}
}
}
}
skip(false);
return result;
}
public DataSet pivot(String[] pks, String[] classKeys, String[] valueKeys) {
return pivot(Arrays.asList(pks),Arrays.asList(classKeys),Arrays.asList(valueKeys));
}
/**
* 行转列
* @param pk 唯一标识key(如姓名)多个key以,分隔如(编号,姓名)
* @param classKey 分类key(如科目)多个key以,分隔如(科目,年度)
* @param valueKey 取值key(如分数)多个key以,分隔如(分数,等级)
* @return
* 表结构(姓名,科目,分数)
* 返回结构 [{姓名:张三,数学:100,物理:90,英语:80},{姓名:李四,数学:100,物理:90,英语:80}]
*/
public DataSet pivot(String pk, String classKey, String valueKey) {
List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(",")));
List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(",")));
List<String> valueKeys = new ArrayList<>(Arrays.asList(valueKey.trim().split(",")));
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(String pk, String classKey) {
List<String> pks = new ArrayList<>(Arrays.asList(pk.trim().split(",")));
List<String> classKeys = new ArrayList<>(Arrays.asList(classKey.trim().split(",")));
List<String> valueKeys = new ArrayList<>();
return pivot(pks, classKeys, valueKeys);
}
public DataSet pivot(List<String> pks, List<String> classKeys, String ... valueKeys) {
List<String> list = new ArrayList<>();
if(null != valueKeys){
for(String item:valueKeys){
list.add(item);
}
}
return pivot(pks, classKeys, valueKeys);
}
private String concatValue(DataRow row, String split){
StringBuilder builder = new StringBuilder();
List<String> keys = row.keys();
for(String key:keys){
if(builder.length() > 0){
builder.append(split);
}
builder.append(row.getString(key));
}
return builder.toString();
}
private String[] kvs(DataRow row){
List<String> keys = row.keys();
int size = keys.size();
String[] kvs = new String[size*2];
for(int i=0; i<size; i++){
String k = keys.get(i);
String v = row.getStringNvl(k);
kvs[i*2] = k;
kvs[i*2+1] = v;
}
return kvs;
}
/**
* 排序
*
* @param keys keys
* @return DataSet
*/
public DataSet asc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return -1;
} else {
if (null == v2) {
return 1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal num1 = new BigDecimal(v1.toString());
BigDecimal num2 = new BigDecimal(v2.toString());
result = num1.compareTo(num2);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date1.compareTo(date2);
} else {
result = v1.toString().compareTo(v2.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = true;
isDesc = false;
return this;
}
public DataSet desc(final String... keys) {
Collections.sort(rows, new Comparator<DataRow>() {
public int compare(DataRow r1, DataRow r2) {
int result = 0;
for (String key : keys) {
Object v1 = r1.get(key);
Object v2 = r2.get(key);
if (null == v1) {
if (null == v2) {
continue;
}
return 1;
} else {
if (null == v2) {
return -1;
}
}
if (BasicUtil.isNumber(v1) && BasicUtil.isNumber(v2)) {
BigDecimal val1 = new BigDecimal(v1.toString());
BigDecimal val2 = new BigDecimal(v2.toString());
result = val2.compareTo(val1);
} else if (v1 instanceof Date && v2 instanceof Date) {
Date date1 = (Date)v1;
Date date2 = (Date)v2;
result = date2.compareTo(date1);
} else {
result = v2.toString().compareTo(v1.toString());
}
if (result != 0) {
return result;
}
}
return 0;
}
});
isAsc = false;
isDesc = true;
return this;
}
public DataSet addAllUpdateColumns() {
for (DataRow row : rows) {
row.addAllUpdateColumns();
}
return this;
}
public DataSet clearUpdateColumns() {
for (DataRow row : rows) {
row.clearUpdateColumns();
}
return this;
}
public DataSet removeNull(String... keys) {
for (DataRow row : rows) {
row.removeNull(keys);
}
return this;
}
private static String key(String key) {
if (null != key && ConfigTable.IS_UPPER_KEY) {
key = key.toUpperCase();
}
return key;
}
/**
* 替换所有NULL值
*
* @param value value
* @return return
*/
public DataSet replaceNull(String value) {
for (DataRow row : rows) {
row.replaceNull(value);
}
return this;
}
/**
* 替换所有空值
*
* @param value value
* @return return
*/
public DataSet replaceEmpty(String value) {
for (DataRow row : rows) {
row.replaceEmpty(value);
}
return this;
}
/**
* 替换所有NULL值
*
* @param key key
* @param value value
* @return return
*/
public DataSet replaceNull(String key, String value) {
for (DataRow row : rows) {
row.replaceNull(key, value);
}
return this;
}
/**
* 替换所有空值
*
* @param key key
* @param value value
* @return return
*/
public DataSet replaceEmpty(String key, String value) {
for (DataRow row : rows) {
row.replaceEmpty(key, value);
}
return this;
}
public DataSet replace(String key, String oldChar, String newChar) {
if (null == key || null == oldChar || null == newChar) {
return this;
}
for (DataRow row : rows) {
row.replace(key, oldChar, newChar);
}
return this;
}
public DataSet replace(String oldChar, String newChar) {
for (DataRow row : rows) {
row.replace(oldChar, newChar);
}
return this;
}
/* ************************* 类sql操作 ************************************** */
/**
* 随机取一行
* @return DataRow
*/
public DataRow random() {
DataRow row = null;
int size = size();
if (size > 0) {
row = getRow(BasicUtil.getRandomNumber(0, size - 1));
}
return row;
}
/**
* 随机取qty行
* @param qty 行数
* @return DataSet
*/
public DataSet randoms(int qty) {
DataSet set = new DataSet();
int size = size();
if (qty < 0) {
qty = 0;
}
if (qty > size) {
qty = size;
}
for (int i = 0; i < qty; i++) {
while (true) {
int idx = BasicUtil.getRandomNumber(0, size - 1);
DataRow row = set.getRow(idx);
if (!set.contains(row)) {
set.add(row);
break;
}
}
}
set.cloneProperty(this);
return set;
}
/**
* 随机取min到max行
* @param min min
* @param max max
* @return DataSet
*/
public DataSet randoms(int min, int max) {
int qty = BasicUtil.getRandomNumber(min, max);
return randoms(qty);
}
public DataSet unique(String... keys) {
return distinct(keys);
}
/**
* 根据正则提取集合
* @param key key
* @param regex 正则
* @param mode 匹配方式
* @return DataSet
*/
public DataSet regex(String key, String regex, Regular.MATCH_MODE mode) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : this) {
tmpValue = row.getString(key);
if (RegularUtil.match(tmpValue, regex, mode)) {
set.add(row);
}
}
set.cloneProperty(this);
return set;
}
public DataSet regex(String key, String regex) {
return regex(key, regex, Regular.MATCH_MODE.MATCH);
}
public boolean checkRequired(String... keys) {
for (DataRow row : rows) {
if (!row.checkRequired(keys)) {
return false;
}
}
return true;
}
public Map<String, Object> getQueryParams() {
return queryParams;
}
public DataSet setQueryParams(Map<String, Object> params) {
this.queryParams = params;
return this;
}
public Object getQueryParam(String key) {
return queryParams.get(key);
}
public DataSet addQueryParam(String key, Object param) {
queryParams.put(key, param);
return this;
}
public String getDatalink() {
return datalink;
}
public void setDatalink(String datalink) {
this.datalink = datalink;
}
public class Select implements Serializable {
private static final long serialVersionUID = 1L;
private boolean ignoreCase = true; //是否忽略大小写
/**
* 是否忽略NULL 如果设置成true 在执行equal notEqual like contains进 null与null比较返回false
* 左右出现NULL时直接返回false
* true会导致一行数据 equal notEqual都筛选不到
*/
private boolean ignoreNull = true;
public DataSet setIgnoreCase(boolean bol) {
this.ignoreCase = bol;
return DataSet.this;
}
public DataSet setIgnoreNull(boolean bol) {
this.ignoreNull = bol;
return DataSet.this;
}
/**
* 筛选key=value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet equals(String key, String value) {
return equals(DataSet.this, key, value);
}
private DataSet equals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = tmpValue.equalsIgnoreCase(value);
} else {
chk = tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key != value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet notEquals(String key, String value) {
return notEquals(DataSet.this, key, value);
}
private DataSet notEquals(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
boolean chk = false;
if (ignoreCase) {
chk = !tmpValue.equalsIgnoreCase(value);
} else {
chk = !tmpValue.equals(value);
}
if (chk) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key列的值是否包含value的子集
*
* @param key key
* @param value value
* @return DataSet
*/
public DataSet contains(String key, String value) {
return contains(DataSet.this, key, value);
}
private DataSet contains(DataSet src, String key, String value) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == value) {
continue;
}
} else {
if (null == tmpValue && null == value) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == value) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
value = value.toLowerCase();
}
if (tmpValue.contains(value)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
/**
* 筛选key列的值like pattern的子集,pattern遵循sql通配符的规则,%表示任意个字符,_表示一个字符
*
* @param key 列
* @param pattern 表达式
* @return DataSet
*/
public DataSet like(String key, String pattern) {
return like(DataSet.this, key, pattern);
}
private DataSet like(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null != pattern) {
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
}
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet notLike(String key, String pattern) {
return notLike(DataSet.this, key, pattern);
}
private DataSet notLike(DataSet src, String key, String pattern) {
DataSet set = new DataSet();
if (null == pattern) {
return set;
}
pattern = pattern.replace("!", "^").replace("_", "\\s|\\S").replace("%", "(\\s|\\S)*");
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == pattern) {
continue;
}
} else {
if (null == tmpValue && null == pattern) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == pattern) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
pattern = pattern.toLowerCase();
}
if (!RegularUtil.match(tmpValue, pattern, Regular.MATCH_MODE.MATCH)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet startWith(String key, String prefix) {
return startWith(DataSet.this, key, prefix);
}
private DataSet startWith(DataSet src, String key, String prefix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == prefix) {
continue;
}
} else {
if (null == tmpValue && null == prefix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == prefix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
prefix = prefix.toLowerCase();
}
if (tmpValue.startsWith(prefix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet endWith(String key, String suffix) {
return endWith(DataSet.this, key, suffix);
}
private DataSet endWith(DataSet src, String key, String suffix) {
DataSet set = new DataSet();
String tmpValue;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull) {
if (null == tmpValue || null == suffix) {
continue;
}
} else {
if (null == tmpValue && null == suffix) {
set.add(row);
continue;
}
}
if (null != tmpValue) {
if (null == suffix) {
continue;
}
if (ignoreCase) {
tmpValue = tmpValue.toLowerCase();
suffix = suffix.toLowerCase();
}
if (tmpValue.endsWith(suffix)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet in(String key, T... values) {
return in(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet in(String key, Collection<T> values) {
return in(DataSet.this, key, values);
}
private <T> DataSet in(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
for (DataRow row : src) {
if (BasicUtil.containsString(ignoreNull, ignoreCase, values, row.getString(key))) {
set.add(row);
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet notIn(String key, T... values) {
return notIn(DataSet.this, key, BeanUtil.array2list(values));
}
public <T> DataSet notIn(String key, Collection<T> values) {
return notIn(DataSet.this, key, values);
}
private <T> DataSet notIn(DataSet src, String key, Collection<T> values) {
DataSet set = new DataSet();
if (null != values) {
String tmpValue = null;
for (DataRow row : src) {
tmpValue = row.getString(key);
if (ignoreNull && null == tmpValue) {
continue;
}
if (!BasicUtil.containsString(ignoreNull, ignoreCase, values, tmpValue)) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public DataSet isNull(String... keys) {
return isNull(DataSet.this, keys);
}
private DataSet isNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNull(set, key);
}
}
return set;
}
private DataSet isNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null == row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet isNotNull(String... keys) {
return isNotNull(DataSet.this, keys);
}
private DataSet isNotNull(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotNull(set, key);
}
}
return set;
}
private DataSet isNotNull(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(null != row.get(key)){
set.add(row);
}
}
return set;
}
public DataSet notNull(String... keys) {
return isNotNull(keys);
}
public DataSet isEmpty(String... keys) {
return isEmpty(DataSet.this, keys);
}
private DataSet isEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isEmpty(set, key);
}
}
return set;
}
private DataSet isEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet empty(String... keys) {
return isEmpty(keys);
}
public DataSet isNotEmpty(String... keys) {
return isNotEmpty(DataSet.this, keys);
}
private DataSet isNotEmpty(DataSet src, String... keys) {
DataSet set = src;
if (null != keys) {
for (String key : keys) {
set = isNotEmpty(set, key);
}
}
return set;
}
private DataSet isNotEmpty(DataSet src, String key) {
DataSet set = new DataSet();
for(DataRow row:src){
if(row.isNotEmpty(key)){
set.add(row);
}
}
return set;
}
public DataSet notEmpty(String... keys) {
return isNotEmpty(keys);
}
public <T> DataSet less(String key, T value) {
return less(DataSet.this, key, value);
}
private <T> DataSet less(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) < 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) < 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) < 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet lessEqual(String key, T value) {
return lessEqual(DataSet.this, key, value);
}
private <T> DataSet lessEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) <= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) <= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greater(String key, T value) {
return greater(DataSet.this, key, value);
}
private <T> DataSet greater(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) > 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) > 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) > 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet greaterEqual(String key, T value) {
return greaterEqual(DataSet.this, key, value);
}
private <T> DataSet greaterEqual(DataSet src, String key, T value) {
DataSet set = new DataSet();
if (null == value) {
return set;
}
if (BasicUtil.isNumber(value)) {
BigDecimal number = new BigDecimal(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getDecimal(key, 0).compareTo(number) >= 0) {
set.add(row);
}
}
} else if (BasicUtil.isDate(value) || BasicUtil.isDateTime(value)) {
Date date = DateUtil.parse(value.toString());
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.isNotEmpty(key) &&
DateUtil.diff(DateUtil.DATE_PART_MILLISECOND, date, row.getDate(key, new Date())) >= 0) {
set.add(row);
}
}
} else {
for (DataRow row : src) {
if (null == row.get(key)) {
continue;
}
if (row.getString(key).compareTo(value.toString()) >= 0) {
set.add(row);
}
}
}
set.cloneProperty(src);
return set;
}
public <T> DataSet between(String key, T min, T max) {
return between(DataSet.this, key, min, max);
}
private <T> DataSet between(DataSet src, String key, T min, T max) {
DataSet set = greaterEqual(src, key, min);
set = lessEqual(set, key, max);
return set;
}
}
public Select select = new Select();
} | anylineorg/anyline | anyline-core/src/main/java/org/anyline/entity/DataSet.java | Java | apache-2.0 | 115,477 |
/*
* Copyright (c) 2015-2017 EpiData, Inc.
*/
package controllers
import play.api.mvc._
import securesocial.core.SecureSocial
/** Controller to display the Notebook. */
object Notebook extends Controller with SecureSocial {
def show = SecuredAction { implicit request =>
Ok(views.html.Notebook.show())
}
}
| epidataio/epidata-community | play/app/controllers/Notebook.scala | Scala | apache-2.0 | 320 |
package ua.job4j.loop;
/**
* Class Класс для вычисления факториала заданного числа.
* @author vfrundin
* @since 05.11.2017
* @version 1.0
*/
public class Factorial {
/**
* Метод должен вычислять факториал поданного на вход числа.
* @param n Число для которого нужно определить факториал.
* @return result - найденный факториал числа n.
*/
public int calc(int n) {
int result = 1;
if (n != 0) {
for (int i = 1; i <= n; i++) {
result *= i;
}
}
return result;
}
}
| Krok3/junior | chapter_001/src/main/java/ua/job4j/loop/Factorial.java | Java | apache-2.0 | 728 |
/*
Copyright 2013 KLab 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.
*/
#ifndef CKLBUIDebugItem_h
#define CKLBUIDebugItem_h
#include "CKLBUITask.h"
#include "CKLBNodeVirtualDocument.h"
/*!
* \class CKLBUIDebugItem
* \brief Debug Item Task Class
*
* CKLBUIDebugItem allows to display debug purpose items in the Game.
* A few properties (such as text, color, etc.) can be modified in runtime
* and used for debugging.
*/
class CKLBUIDebugItem : public CKLBUITask
{
friend class CKLBTaskFactory<CKLBUIDebugItem>;
private:
CKLBUIDebugItem();
virtual ~CKLBUIDebugItem();
bool init(CKLBUITask* pParent, CKLBNode* pNode, u32 order, float x, float y, u32 alpha, u32 color, const char* font, u32 size, const char* text, const char* callback,u32 id);
bool initCore(u32 order, float x, float y, u32 alpha, u32 color, const char* font, u32 size, const char* text, const char* callback,u32 id);
public:
static CKLBUIDebugItem* create(CKLBUITask* pParent, CKLBNode* pNode, u32 order, float x, float y, u32 alpha, u32 color, const char* font, u32 size, const char* text, const char* callback,u32 id);
u32 getClassID ();
bool initUI (CLuaState& lua);
void execute (u32 deltaT);
void dieUI ();
inline virtual void setOrder (u32 order) { m_order = order; m_update = true; }
inline virtual u32 getOrder () { return m_order; }
inline void setAlpha (u32 alpha) { m_alpha = alpha; m_update = true; }
inline u32 getAlpha () { return m_alpha; }
inline void setU24Color (u32 color) { m_color = color; m_update = true; }
inline u32 getU24Color () { return m_color; }
inline void setColor (u32 color) { m_alpha = color >> 24; m_color = color & 0xFFFFFF; m_update = true; }
inline u32 getColor () { return (m_alpha << 24) | m_color; }
inline void setFont (const char* font) { setStrC(m_font, font); m_update = true; }
inline const char* getFont () { return m_font; }
inline void setSize (u32 size) { m_size = size; m_update = true; }
inline u32 getSize () { return m_size; }
inline void setText (const char* text) { setStrC(m_text, text); m_update = true; }
inline const char* getText () { return m_text; }
private:
u32 m_order;
u8 m_format;
u8 m_alpha;
u32 m_color;
const char* m_font;
const char* m_text;
u32 m_size;
bool setup_node();
// 現在は VDocで仮実装しておく。
CKLBNodeVirtualDocument * m_pLabel;
bool m_update;
STextInfo m_txinfo;
const char * m_callback;
int m_ID;
int m_padId;
static PROP_V2 ms_propItems[];
};
#endif // CKLBUIDebugItem_h
| mhidaka/playgroundthon | Engine/source/UISystem/CKLBUIDebugItem.h | C | apache-2.0 | 3,395 |
/* Copyright (C) 2013-2022 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* 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 net.automatalib.graphs.base.compact;
import net.automatalib.commons.smartcollections.ResizingArrayStorage;
import org.checkerframework.checker.nullness.qual.Nullable;
public class CompactBidiGraph<@Nullable NP, @Nullable EP> extends AbstractCompactBidiGraph<NP, EP> {
private final ResizingArrayStorage<NP> nodeProperties;
public CompactBidiGraph() {
this.nodeProperties = new ResizingArrayStorage<>(Object.class);
}
public CompactBidiGraph(int initialCapacity) {
super(initialCapacity);
this.nodeProperties = new ResizingArrayStorage<>(Object.class, initialCapacity);
}
@Override
public void setNodeProperty(int node, @Nullable NP property) {
nodeProperties.ensureCapacity(node + 1);
nodeProperties.array[node] = property;
}
@Override
public NP getNodeProperty(int node) {
return node < nodeProperties.array.length ? nodeProperties.array[node] : null;
}
}
| LearnLib/automatalib | core/src/main/java/net/automatalib/graphs/base/compact/CompactBidiGraph.java | Java | apache-2.0 | 1,632 |
package com.github.binarywang.wxpay.service.impl;
import com.github.binarywang.wxpay.bean.request.*;
import com.github.binarywang.wxpay.bean.result.*;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.testbase.ApiTestModule;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
/**
* @author chenliang
* @date 2021-08-02 6:45 下午
*/
@Test
@Guice(modules = ApiTestModule.class)
public class WxEntrustPapServiceTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Inject
private WxPayService payService;
/**
* 公众号纯签约
*/
@Test
public void testMpSign() {
String contractCode = "222200002222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000014", ")");
WxMpEntrustRequest wxMpEntrust = WxMpEntrustRequest.newBuilder()
.planId("142323") //模板ID:跟微信申请
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.requestSerial(6L)
//.returnWeb(1)
.version("1.0")
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.outerId(displayAccount)
.build();
String url = null;
try {
url = this.payService.getWxEntrustPapService().mpSign(wxMpEntrust);
} catch (WxPayException e) {
e.printStackTrace();
}
logger.info(url);
}
/**
* 小程序纯签约
*/
@Test
public void testMaSign() {
String contractCode = "222220000022222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000001", ")");
WxMaEntrustRequest wxMaEntrustRequest = WxMaEntrustRequest.newBuilder()
.contractCode(contractCode)
.contractDisplayAccount(contractCode)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.outerId(displayAccount)
.planId("141535")
.requestSerial(2L)
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.build();
try {
String url = this.payService.getWxEntrustPapService().maSign(wxMaEntrustRequest);
logger.info(url);
} catch (WxPayException e) {
e.printStackTrace();
}
}
/**
* h5纯签约
*/
@Test
public void testH5Sign() {
String contractCode = "222111122222";
String displayAccount = Joiner.on("").join("陈*", "(", "100000000", ")");
WxH5EntrustRequest wxH5EntrustRequest = WxH5EntrustRequest.newBuilder()
.requestSerial(2L)
.clientIp("127.0.0.1")
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.notifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.planId("141535")
.returnAppid("1")
.timestamp(String.valueOf(System.currentTimeMillis() / 1000))
.version("1.0")
.outerId(displayAccount)
.build();
try {
WxH5EntrustResult wxH5EntrustResult = this.payService.getWxEntrustPapService().h5Sign(wxH5EntrustRequest);
logger.info(wxH5EntrustResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testPaySign() {
String contractCode = "2222211110000222";
String displayAccount = Joiner.on("").join("陈*", "(", "10000005", ")");
String outTradeNo = "11100111101";
WxPayEntrustRequest wxPayEntrustRequest = WxPayEntrustRequest.newBuilder()
.attach("local")
.body("产品名字")
.contractAppId(this.payService.getConfig().getAppId())
.contractCode(contractCode)
.contractDisplayAccount(displayAccount)
.contractMchId(this.payService.getConfig().getMchId())
//签约回调
.contractNotifyUrl("http://domain.com/api/wxpay/sign/callback.do")
.detail("产品是好")
.deviceInfo("oneplus 7 pro")
//.goodsTag()
//.limitPay()
//支付回调
.notifyUrl("http://domain.com/api/wxpay/pay/callback.do")
.openId("oIvLdt8Q-_aKy4Vo6f4YI6gsIhMc") //openId
.outTradeNo(outTradeNo)
.planId("141535")
//.productId()
.requestSerial(3L)
.spbillCreateIp("127.0.0.1")
//.timeExpire()
//.timeStart()
.totalFee(1)
.tradeType("MWEB")
.contractOuterId(displayAccount)
.build();
try {
WxPayEntrustResult wxPayEntrustResult = this.payService.getWxEntrustPapService().paySign(wxPayEntrustRequest);
logger.info(wxPayEntrustResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testWithhold() {
String outTradeNo = "101010101";
WxWithholdRequest withholdRequest = WxWithholdRequest.newBuilder()
.attach("local")
.body("产品名字")
.contractId("202011065409471222") // 微信返回的签约协议号
.detail("产品描述")
.feeType("CNY")
//.goodsTag()
.notifyUrl("http://domain.com/api/wxpay/withhold/callback.do")
.outTradeNo(outTradeNo)
.spbillCreateIp("127.0.0.1")
.totalFee(1)
.tradeType("PAP")
.build();
try {
WxWithholdResult wxWithholdResult = this.payService.getWxEntrustPapService().withhold(withholdRequest);
logger.info(wxWithholdResult.toString());
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testPreWithhold() {
WxPreWithholdRequest.EstimateAmount estimateAmount = new WxPreWithholdRequest.EstimateAmount();
estimateAmount.setAmount(1);
estimateAmount.setCurrency("CNY");
WxPreWithholdRequest wxPreWithholdRequest = WxPreWithholdRequest.newBuilder()
.appId("wx73dssxxxxxx")
.contractId("202010275173070001")
.estimateAmount(estimateAmount)
.mchId("1600010102")
.build();
try {
String httpResponseModel = this.payService.getWxEntrustPapService().preWithhold(wxPreWithholdRequest);
logger.info(httpResponseModel);
} catch (WxPayException e) {
e.printStackTrace();
}
}
@Test
public void testQuerySign() {
String outTradeNo = "1212121212";
WxSignQueryRequest wxSignQueryRequest = WxSignQueryRequest.newBuilder()
//.contractId("202010275173073211")
.contractCode(outTradeNo)
.planId(1432112)
.version("1.0")
.build();
try {
WxSignQueryResult wxSignQueryResult = this.payService.getWxEntrustPapService().querySign(wxSignQueryRequest);
logger.info(wxSignQueryResult.toString());
} catch (WxPayException e) {
logger.info("异常码:" + e.getErrCode());
logger.info("异常:" + e);
}
}
@Test
public void testTerminationContract() {
WxTerminatedContractRequest wxTerminatedContractRequest = WxTerminatedContractRequest.newBuilder()
.contractId("202010275173070231")
.contractTerminationRemark("测试解约")
.version("1.0")
.build();
try {
WxTerminationContractResult wxTerminationContractResult = this.payService.getWxEntrustPapService().terminationContract(wxTerminatedContractRequest);
logger.info(wxTerminationContractResult.toString());
} catch (WxPayException e) {
logger.error(e.getMessage());
}
}
}
| Wechat-Group/WxJava | weixin-java-pay/src/test/java/com/github/binarywang/wxpay/service/impl/WxEntrustPapServiceTest.java | Java | apache-2.0 | 7,346 |
package org.clinical3PO.common.security;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.clinical3PO.common.security.model.User;
import org.clinical3PO.common.security.service.UserService;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
User user = userService.loadUserByUsername(username);
if (user == null) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
| Clinical3PO/Platform | dev/clinical3PO/app/src/main/java/org/clinical3PO/common/security/CustomAuthenticationProvider.java | Java | apache-2.0 | 1,572 |
---
layout: interior
title: The Heart of Wichita
speaker: Alex Pemberton
permalink: alex-pemberton
image: img/20160607/alex_pemberton.jpg
event: 20160607
video: ctGrTBgGcN0
favorite: The prominent and hidden architectural gems, such as The Orpheum, the Kress building, Carthalite, Proudfoot & Bird buildings, and Frank Lloyd Wright’s Allen-Lambe House and Corbin Education building.
about: A native Kansan, Alex has been living in Wichita since 2010 and now refers to it as the hometown he chose. Despite this, he still pronounces the Arkansas River like the state and Greenwich Road like the neighborhood in New York. When not helping entrepreneurs and property owners find solutions to their commercial real estate needs as an advisor at NAI Martens, you can find him volunteer coaching a youth baseball team for League 42, taking in Wichita’s burgeoning live music and visual arts scenes, attending entrepreneurship- and civic-oriented events, or cruising his Vespa down Douglas Avenue. A graduate of Wichita State University with majors in entrepreneurship, management, and economics with a real estate emphasis, he builds a spreadsheet to inform virtually every life decision.
twitter:
facebook: alex.pemberton.14
instagram:
linkedin: alexpembertonict
website:
email: [email protected]
telephone:
--- | Wichitalks/wichitalks.github.io | _posts/20160607-Wichitalks/2016-06-07-Alex-Pemberton.md | Markdown | apache-2.0 | 1,321 |
<?php
/**
* This file is part of the SevenShores/NetSuite library
* AND originally from the NetSuite PHP Toolkit.
*
* New content:
* @package ryanwinchester/netsuite-php
* @copyright Copyright (c) Ryan Winchester
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @link https://github.com/ryanwinchester/netsuite-php
*
* Original content:
* @copyright Copyright (c) NetSuite Inc.
* @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt
* @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
*
* generated: 2020-04-10 09:56:55 PM UTC
*/
namespace NetSuite\Classes;
class NSSoapFault {
/**
* @var \NetSuite\Classes\FaultCodeType
*/
public $code;
/**
* @var string
*/
public $message;
static $paramtypesmap = array(
"code" => "FaultCodeType",
"message" => "string",
);
}
| RyanWinchester/netsuite-php | src/Classes/NSSoapFault.php | PHP | apache-2.0 | 1,021 |
/**
* 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.
*/
import { NgModule } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { ConfigureRowsComponent } from './configure-rows.component';
import { ShowHideAlertEntriesComponent } from './show-hide/show-hide-alert-entries.component';
import { SwitchModule } from 'app/shared/switch/switch.module';
import { QueryBuilder } from '../alerts-list/query-builder';
import { ShowHideService } from './show-hide/show-hide.service';
@NgModule({
imports: [ SharedModule, SwitchModule ],
declarations: [ ConfigureRowsComponent, ShowHideAlertEntriesComponent ],
exports: [ ConfigureRowsComponent ],
providers: [ QueryBuilder, ShowHideService ],
})
export class ConfigureRowsModule {
constructor(private showHideService: ShowHideService) {}
}
| anandsubbu/incubator-metron | metron-interface/metron-alerts/src/app/alerts/configure-rows/configure-rows.module.ts | TypeScript | apache-2.0 | 1,591 |
package com.example.mywechat.utils;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
/**
* ActivityCollector ÀàÓÃÓÚ¹ÜÀíËùÓеĻ
* @author dzhiqin
*
*/
public class ActivityCollector {
public static List<Activity> activities=new ArrayList<Activity>();
public static void addActivity(Activity activity){
activities.add(activity);
}
public static void removeActivity(Activity activity){
activities.remove(activity);
}
/**
* ¹Ø±ÕËùÓл
*/
public static void finishAll(){
for(Activity activity:activities){
if(!activity.isFinishing()){
activity.finish();
}
}
}
public ActivityCollector() {
// TODO ×Ô¶¯Éú³ÉµÄ¹¹Ô캯Êý´æ¸ù
}
}
| dzhiqin/MyWeChat | src/com/example/mywechat/utils/ActivityCollector.java | Java | apache-2.0 | 697 |
# Teloschistes flavicans var. pallidus Sambo VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Teloschistes flavicans var. pallidus Sambo
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Teloschistaceae/Teloschistes/Teloschistes flavicans/Teloschistes flavicans pallidus/README.md | Markdown | apache-2.0 | 213 |
# 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.
def strip_region_tags(sample_text):
"""Remove blank lines and region tags from sample text"""
magic_lines = [
line for line in sample_text.split("\n") if len(line) > 0 and "# [" not in line
]
return "\n".join(magic_lines)
| googleapis/python-bigquery | samples/magics/_helpers.py | Python | apache-2.0 | 823 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Cleidimar Viana
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.seamusdawkins.tablayout.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.seamusdawkins.tablayout.R;
public class FirstFragment extends Fragment {
TextView tv;
RelativeLayout rl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
tv = (TextView) rootView.findViewById(R.id.action);
tv.setText(R.string.str_first);
return rootView;
}
}
| cleidimarviana/Tabs-Material | app/src/main/java/com/seamusdawkins/tablayout/fragments/FirstFragment.java | Java | apache-2.0 | 1,928 |
<font class='sw'>Connexion ($var['msize'] bytes).</font>
| BigBlueHat/atmailopen | html/french/msg/poprelogin.html | HTML | apache-2.0 | 57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.