text
stringlengths 2
1.04M
| meta
dict |
---|---|
// Copyright (C) 2006 Google 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.
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* <p>
* For a fairly comprehensive set of languages see the
* <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
* file that came with this source. At a minimum, the lexer should work on a
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
* and a subset of Perl, but, because of commenting conventions, doesn't work on
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
* printer needs to do more substantial DOM manipulations to support that, so
* some css styles may not be preserved.
* </ol>
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in, but if you wish, you can add
* another class to the {@code <pre>} or {@code <code>} element to specify the
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
* starts with "lang-" followed by a file extension, specifies the file type.
* See the "lang-*.js" files in this directory for code that implements
* per-language file handlers.
* <p>
* Change log:<br>
* cbeust, 2006/08/22
* <blockquote>
* Java annotations (start with "@") are now captured as literals ("lit")
* </blockquote>
* @requires console
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window, define */
/** @define {boolean} */
var IN_GLOBAL_SCOPE = true;
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events.
* If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
window['PR_SHOULD_USE_CONTINUATION'] = true;
/**
* Pretty print a chunk of code.
* @param {string} sourceCodeHtml The HTML to pretty print.
* @param {string} opt_langExtension The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param {number|boolean} opt_numberLines True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
* @return {string} code as html, but prettier
*/
var prettyPrintOne;
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function} opt_whenDone called when prettifying is done.
* @param {HTMLElement|HTMLDocument} opt_root an element or document
* containing all the elements to pretty print.
* Defaults to {@code document.body}.
*/
var prettyPrint;
(function () {
var win = window;
// Keyword lists for various languages.
// We use things that coerce to strings to make them compact when minified
// and to defeat aggressive optimizers that fold large string constants.
var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
"double,enum,extern,float,goto,inline,int,long,register,short,signed," +
"sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
"new,operator,private,protected,public,this,throw,true,try,typeof"];
var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
"concept,concept_map,const_cast,constexpr,decltype,delegate," +
"dynamic_cast,explicit,export,friend,generic,late_check," +
"mutable,namespace,nullptr,property,reinterpret_cast,static_assert," +
"static_cast,template,typeid,typename,using,virtual,where"];
var JAVA_KEYWORDS = [COMMON_KEYWORDS,
"abstract,assert,boolean,byte,extends,final,finally,implements,import," +
"instanceof,interface,null,native,package,strictfp,super,synchronized," +
"throws,transient"];
var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
"as,base,by,checked,decimal,delegate,descending,dynamic,event," +
"fixed,foreach,from,group,implicit,in,internal,into,is,let," +
"lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
"sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
"var,virtual,where"];
var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
"for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
"throw,true,try,unless,until,when,while,yes";
var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
"debugger,eval,export,function,get,null,set,undefined,var,with," +
"Infinity,NaN"];
var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
"goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
"sub,undef,unless,until,use,wantarray,while,BEGIN,END";
var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
"elif,except,exec,finally,from,global,import,in,is,lambda," +
"nonlocal,not,or,pass,print,raise,try,with,yield," +
"False,True,None"];
var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
"rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
"BEGIN,END"];
var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "as,assert,const,copy,drop," +
"enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv," +
"pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"];
var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
"function,in,local,set,then,until"];
var ALL_KEYWORDS = [
CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,
PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
// token style names. correspond to css classes
/**
* token style for a string literal
* @const
*/
var PR_STRING = 'str';
/**
* token style for a keyword
* @const
*/
var PR_KEYWORD = 'kwd';
/**
* token style for a comment
* @const
*/
var PR_COMMENT = 'com';
/**
* token style for a type
* @const
*/
var PR_TYPE = 'typ';
/**
* token style for a literal value. e.g. 1, null, true.
* @const
*/
var PR_LITERAL = 'lit';
/**
* token style for a punctuation string.
* @const
*/
var PR_PUNCTUATION = 'pun';
/**
* token style for plain text.
* @const
*/
var PR_PLAIN = 'pln';
/**
* token style for an sgml tag.
* @const
*/
var PR_TAG = 'tag';
/**
* token style for a markup declaration such as a DOCTYPE.
* @const
*/
var PR_DECLARATION = 'dec';
/**
* token style for embedded source.
* @const
*/
var PR_SOURCE = 'src';
/**
* token style for an sgml attribute name.
* @const
*/
var PR_ATTRIB_NAME = 'atn';
/**
* token style for an sgml attribute value.
* @const
*/
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
* @const
*/
var PR_NOCODE = 'nocode';
/**
* A set of tokens that can precede a regular expression literal in
* javascript
* http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
* has the full list, but I've removed ones that might be problematic when
* seen in languages that don't support regular expression literals.
*
* <p>Specifically, I've removed any keywords that can't precede a regexp
* literal in a syntactically legal javascript program, and I've removed the
* "in" keyword since it's not a keyword in many languages, and might be used
* as a count of inches.
*
* <p>The link above does not accurately describe EcmaScript rules since
* it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
* very well in practice.
*
* @private
* @const
*/
var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
// CAVEAT: this does not properly handle the case where a regular
// expression immediately follows another since a regular expression may
// have flags for case-sensitivity and the like. Having regexp tokens
// adjacent is not valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
/**
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
* matches the union of the sets of strings matched by the input RegExp.
* Since it matches globally, if the input strings have a start-of-input
* anchor (/^.../), it is ignored for the purposes of unioning.
* @param {Array.<RegExp>} regexs non multiline, non-global regexs.
* @return {RegExp} a global regex.
*/
function combinePrefixPatterns(regexs) {
var capturedGroupIndex = 0;
var needToFoldCase = false;
var ignoreCase = false;
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.ignoreCase) {
ignoreCase = true;
} else if (/[a-z]/i.test(regex.source.replace(
/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
needToFoldCase = true;
ignoreCase = false;
break;
}
}
var escapeCharToCodeUnit = {
'b': 8,
't': 9,
'n': 0xa,
'v': 0xb,
'f': 0xc,
'r': 0xd
};
function decodeEscape(charsetPart) {
var cc0 = charsetPart.charCodeAt(0);
if (cc0 !== 92 /* \\ */) {
return cc0;
}
var c1 = charsetPart.charAt(1);
cc0 = escapeCharToCodeUnit[c1];
if (cc0) {
return cc0;
} else if ('0' <= c1 && c1 <= '7') {
return parseInt(charsetPart.substring(1), 8);
} else if (c1 === 'u' || c1 === 'x') {
return parseInt(charsetPart.substring(2), 16);
} else {
return charsetPart.charCodeAt(1);
}
}
function encodeEscape(charCode) {
if (charCode < 0x20) {
return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
}
var ch = String.fromCharCode(charCode);
return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
? "\\" + ch : ch;
}
function caseFoldCharset(charSet) {
var charsetParts = charSet.substring(1, charSet.length - 1).match(
new RegExp(
'\\\\u[0-9A-Fa-f]{4}'
+ '|\\\\x[0-9A-Fa-f]{2}'
+ '|\\\\[0-3][0-7]{0,2}'
+ '|\\\\[0-7]{1,2}'
+ '|\\\\[\\s\\S]'
+ '|-'
+ '|[^-\\\\]',
'g'));
var ranges = [];
var inverse = charsetParts[0] === '^';
var out = ['['];
if (inverse) { out.push('^'); }
for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
var p = charsetParts[i];
if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups.
out.push(p);
} else {
var start = decodeEscape(p);
var end;
if (i + 2 < n && '-' === charsetParts[i + 1]) {
end = decodeEscape(charsetParts[i + 2]);
i += 2;
} else {
end = start;
}
ranges.push([start, end]);
// If the range might intersect letters, then expand it.
// This case handling is too simplistic.
// It does not deal with non-latin case folding.
// It works for latin source code identifiers though.
if (!(end < 65 || start > 122)) {
if (!(end < 65 || start > 90)) {
ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
}
if (!(end < 97 || start > 122)) {
ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
}
}
}
}
// [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
// -> [[1, 12], [14, 14], [16, 17]]
ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
var consolidatedRanges = [];
var lastRange = [];
for (var i = 0; i < ranges.length; ++i) {
var range = ranges[i];
if (range[0] <= lastRange[1] + 1) {
lastRange[1] = Math.max(lastRange[1], range[1]);
} else {
consolidatedRanges.push(lastRange = range);
}
}
for (var i = 0; i < consolidatedRanges.length; ++i) {
var range = consolidatedRanges[i];
out.push(encodeEscape(range[0]));
if (range[1] > range[0]) {
if (range[1] + 1 > range[0]) { out.push('-'); }
out.push(encodeEscape(range[1]));
}
}
out.push(']');
return out.join('');
}
function allowAnywhereFoldCaseAndRenumberGroups(regex) {
// Split into character sets, escape sequences, punctuation strings
// like ('(', '(?:', ')', '^'), and runs of characters that do not
// include any of the above.
var parts = regex.source.match(
new RegExp(
'(?:'
+ '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
+ '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
+ '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
+ '|\\\\[0-9]+' // a back-reference or octal escape
+ '|\\\\[^ux0-9]' // other escape sequence
+ '|\\(\\?[:!=]' // start of a non-capturing group
+ '|[\\(\\)\\^]' // start/end of a group, or line start
+ '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
+ ')',
'g'));
var n = parts.length;
// Maps captured group numbers to the number they will occupy in
// the output or to -1 if that has not been determined, or to
// undefined if they need not be capturing in the output.
var capturedGroups = [];
// Walk over and identify back references to build the capturedGroups
// mapping.
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
// groups are 1-indexed, so max group index is count of '('
++groupIndex;
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue) {
if (decimalValue <= groupIndex) {
capturedGroups[decimalValue] = -1;
} else {
// Replace with an unambiguous escape sequence so that
// an octal escape sequence does not turn into a backreference
// to a capturing group from an earlier regex.
parts[i] = encodeEscape(decimalValue);
}
}
}
}
// Renumber groups and reduce capturing groups to non-capturing groups
// where possible.
for (var i = 1; i < capturedGroups.length; ++i) {
if (-1 === capturedGroups[i]) {
capturedGroups[i] = ++capturedGroupIndex;
}
}
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
++groupIndex;
if (!capturedGroups[groupIndex]) {
parts[i] = '(?:';
}
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue && decimalValue <= groupIndex) {
parts[i] = '\\' + capturedGroups[decimalValue];
}
}
}
// Remove any prefix anchors so that the output will match anywhere.
// ^^ really does mean an anchored match though.
for (var i = 0; i < n; ++i) {
if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
}
// Expand letters to groups to handle mixing of case-sensitive and
// case-insensitive patterns if necessary.
if (regex.ignoreCase && needToFoldCase) {
for (var i = 0; i < n; ++i) {
var p = parts[i];
var ch0 = p.charAt(0);
if (p.length >= 2 && ch0 === '[') {
parts[i] = caseFoldCharset(p);
} else if (ch0 !== '\\') {
// TODO: handle letters in numeric escapes.
parts[i] = p.replace(
/[a-zA-Z]/g,
function (ch) {
var cc = ch.charCodeAt(0);
return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
});
}
}
}
return parts.join('');
}
var rewritten = [];
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.global || regex.multiline) { throw new Error('' + regex); }
rewritten.push(
'(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
}
return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
}
/**
* Split markup into a string of source code and an array mapping ranges in
* that string to the text nodes in which they appear.
*
* <p>
* The HTML DOM structure:</p>
* <pre>
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
* </pre>
* <p>
* corresponds to the HTML
* {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p>
*
* <p>
* It will produce the output:</p>
* <pre>
* {
* sourceCode: "print 'Hello '\n + 'World';",
* // 1 2
* // 012345678901234 5678901234567
* spans: [0, #1, 6, #2, 14, #3, 15, #4]
* }
* </pre>
* <p>
* where #1 is a reference to the {@code "print "} text node above, and so
* on for the other text nodes.
* </p>
*
* <p>
* The {@code} spans array is an array of pairs. Even elements are the start
* indices of substrings, and odd elements are the text nodes (or BR elements)
* that contain the text for those substrings.
* Substrings continue until the next index or the end of the source.
* </p>
*
* @param {Node} node an HTML DOM subtree containing source-code.
* @param {boolean} isPreformatted true if white-space in text nodes should
* be considered significant.
* @return {Object} source code and the text nodes in which they occur.
*/
function extractSourceSpans(node, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var chunks = [];
var length = 0;
var spans = [];
var k = 0;
function walk(node) {
var type = node.nodeType;
if (type == 1) { // Element
if (nocode.test(node.className)) { return; }
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
var nodeName = node.nodeName.toLowerCase();
if ('br' === nodeName || 'li' === nodeName) {
chunks[k] = '\n';
spans[k << 1] = length++;
spans[(k++ << 1) | 1] = node;
}
} else if (type == 3 || type == 4) { // Text
var text = node.nodeValue;
if (text.length) {
if (!isPreformatted) {
text = text.replace(/[ \t\r\n]+/g, ' ');
} else {
text = text.replace(/\r\n?/g, '\n'); // Normalize newlines.
}
// TODO: handle tabs here?
chunks[k] = text;
spans[k << 1] = length;
length += text.length;
spans[(k++ << 1) | 1] = node;
}
}
}
walk(node);
return {
sourceCode: chunks.join('').replace(/\n$/, ''),
spans: spans
};
}
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
* @param {number} basePos the index of sourceCode within the chunk of source
* whose decorations are already present on out.
*/
function appendDecorations(basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
var job = {
sourceCode: sourceCode,
basePos: basePos
};
langHandler(job);
out.push.apply(out, job.decorations);
}
var notWs = /\S/;
/**
* Given an element, if it contains only one child element and any text nodes
* it contains contain only space characters, return the sole child element.
* Otherwise returns undefined.
* <p>
* This is meant to return the CODE element in {@code <pre><code ...>} when
* there is a single child element that contains all the non-space textual
* content, but not to return anything where there are multiple child elements
* as in {@code <pre><code>...</code><code>...</code></pre>} or when there
* is textual content.
*/
function childContentWrapper(element) {
var wrapper = undefined;
for (var c = element.firstChild; c; c = c.nextSibling) {
var type = c.nodeType;
wrapper = (type === 1) // Element Node
? (wrapper ? element : c)
: (type === 3) // Text Node
? (notWs.test(c.nodeValue) ? element : wrapper)
: wrapper;
}
return wrapper === element ? undefined : wrapper;
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
*
* Style is a style constant like PR_PLAIN, or can be a string of the
* form 'lang-FOO', where FOO is a language extension describing the
* language of the portion of the token in $1 after pattern executes.
* E.g., if style is 'lang-lisp', and group 1 contains the text
* '(hello (world))', then that portion of the token will be passed to the
* registered lisp handler for formatting.
* The text before and after group 1 will be restyled using this decorator
* so decorators should take care that this doesn't result in infinite
* recursion. For example, the HTML lexer rule for SCRIPT elements looks
* something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
* '<script>foo()<\/script>', which would cause the current decorator to
* be called with '<script>' which would not match the same rule since
* group 1 must not be empty, so it would be instead styled as PR_TAG by
* the generic tag rule. The handler registered for the 'js' extension would
* then be called with 'foo()', and finally, the current decorator would
* be called with '<\/script>' which would not match the original rule and
* so the generic tag rule would identify it as a tag.
*
* Pattern must only match prefixes, and if it matches a prefix, then that
* match is considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
* @return {function (Object)} a
* function that takes source code and returns a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
var tokenizer;
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
var allRegexs = [];
var regexKeys = {};
for (var i = 0, n = allPatterns.length; i < n; ++i) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
var regex = patternParts[1];
var k = '' + regex;
if (!regexKeys.hasOwnProperty(k)) {
allRegexs.push(regex);
regexKeys[k] = null;
}
}
allRegexs.push(/[\0-\uffff]/);
tokenizer = combinePrefixPatterns(allRegexs);
})();
var nPatterns = fallthroughStylePatterns.length;
/**
* Lexes job.sourceCode and produces an output array job.decorations of
* style classes preceded by the position at which they start in
* job.sourceCode in order.
*
* @param {Object} job an object like <pre>{
* sourceCode: {string} sourceText plain text,
* basePos: {int} position of job.sourceCode in the larger chunk of
* sourceCode.
* }</pre>
*/
var decorate = function (job) {
var sourceCode = job.sourceCode, basePos = job.basePos;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
};
return decorate;
}
/** returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings.
* It has no special handling for double delimiter escapes as in basic, or
* the tripled delimiters used in python, but should work on those regardless
* although in those cases a single string literal may be broken up into
* multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
* @return {function (Object)} a function that examines the source code
* in the input job and builds the decoration list.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
// fallthroughStylePatterns.push([PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
var hc = options['hashComments'];
if (hc) {
if (options['cStyleComments']) {
if (hc > 1) { // multiline hash comments
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
} else {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
}
// #include <stdio.h>
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
var regexLiterals = options['regexLiterals'];
if (regexLiterals) {
/**
* @const
*/
var regexExcls = regexLiterals > 1
? '' // Multiline regex literals
: '\n\r';
/**
* @const
*/
var regexAny = regexExcls ? '.' : '[\\S\\s]';
/**
* @const
*/
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*' + regexExcls + '])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C' + regexExcls + ']'
// escape sequences (\x5C),
+ '|\\x5C' + regexAny
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
+ '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var types = options['types'];
if (types) {
fallthroughStylePatterns.push([PR_TYPE, types]);
}
var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
var punctuation =
// The Bash man page says
// A word is a sequence of characters considered as a single
// unit by GRUB. Words are separated by metacharacters,
// which are the following plus space, tab, and newline: { }
// | & $ ; < >
// ...
// A word beginning with # causes that word and all remaining
// characters on that line to be ignored.
// which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
// comment but empirically
// $ echo {#}
// {#}
// $ echo \$#
// $#
// $ echo }#
// }#
// so /(?:^|[|&;<>\s])/ is more appropriate.
// http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
// suggests that this definition is compatible with a
// default mode that tries to use a single token definition
// to recognize both bash/python style comments and C
// preprocessor directives.
// This definition of punctuation does not include # in the list of
// follow-on exclusions, so # will not be broken before if preceeded
// by a punctuation character. We could try to exclude # after
// [|&;<>] but that doesn't seem to cause many major problems.
// If that does turn out to be a problem, we should change the below
// when hc is truthy to include # in the run of punctuation characters
// only when not followint [|&;<>].
'^.[^\\s\\w.$@\'"`/\\\\]*';
if (options['regexLiterals']) {
punctuation += '(?!\s*\/)';
}
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
// Don't treat escaped quotes in bash as starting strings.
// See issue 144.
[PR_PLAIN, /^\\[\s\S]?/, null],
[PR_PUNCTUATION, new RegExp(punctuation), null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
var decorateSource = sourceDecorator({
'keywords': ALL_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'multiLineStrings': true,
'regexLiterals': true
});
/**
* Given a DOM subtree, wraps it in a list, and puts each line into its own
* list item.
*
* @param {Node} node modified in place. Its content is pulled into an
* HTMLOListElement, and each line is moved into a separate list item.
* This requires cloning elements, so the input might not have unique
* IDs after numbering.
* @param {boolean} isPreformatted true iff white-space in text nodes should
* be treated as significant.
*/
function numberLines(node, opt_startLineNum, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var lineBreak = /\r\n?|\n/;
var document = node.ownerDocument;
var li = document.createElement('li');
while (node.firstChild) {
li.appendChild(node.firstChild);
}
// An array of lines. We split below, so this is initialized to one
// un-split line.
var listItems = [li];
function walk(node) {
var type = node.nodeType;
if (type == 1 && !nocode.test(node.className)) { // Element
if ('br' === node.nodeName) {
breakAfter(node);
// Discard the <BR> since it is now flush against a </LI>.
if (node.parentNode) {
node.parentNode.removeChild(node);
}
} else {
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
}
} else if ((type == 3 || type == 4) && isPreformatted) { // Text
var text = node.nodeValue;
var match = text.match(lineBreak);
if (match) {
var firstLine = text.substring(0, match.index);
node.nodeValue = firstLine;
var tail = text.substring(match.index + match[0].length);
if (tail) {
var parent = node.parentNode;
parent.insertBefore(
document.createTextNode(tail), node.nextSibling);
}
breakAfter(node);
if (!firstLine) {
// Don't leave blank text nodes in the DOM.
node.parentNode.removeChild(node);
}
}
}
}
// Split a line after the given node.
function breakAfter(lineEndNode) {
// If there's nothing to the right, then we can skip ending the line
// here, and move root-wards since splitting just before an end-tag
// would require us to create a bunch of empty copies.
while (!lineEndNode.nextSibling) {
lineEndNode = lineEndNode.parentNode;
if (!lineEndNode) { return; }
}
function breakLeftOf(limit, copy) {
// Clone shallowly if this node needs to be on both sides of the break.
var rightSide = copy ? limit.cloneNode(false) : limit;
var parent = limit.parentNode;
if (parent) {
// We clone the parent chain.
// This helps us resurrect important styling elements that cross lines.
// E.g. in <i>Foo<br>Bar</i>
// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
var parentClone = breakLeftOf(parent, 1);
// Move the clone and everything to the right of the original
// onto the cloned parent.
var next = limit.nextSibling;
parentClone.appendChild(rightSide);
for (var sibling = next; sibling; sibling = next) {
next = sibling.nextSibling;
parentClone.appendChild(sibling);
}
}
return rightSide;
}
var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
// Walk the parent chain until we reach an unattached LI.
for (var parent;
// Check nodeType since IE invents document fragments.
(parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
copiedListItem = parent;
}
// Put it on the list of lines for later processing.
listItems.push(copiedListItem);
}
// Split lines while there are lines left to split.
for (var i = 0; // Number of lines that have been split so far.
i < listItems.length; // length updated by breakAfter calls.
++i) {
walk(listItems[i]);
}
// Make sure numeric indices show correctly.
if (opt_startLineNum === (opt_startLineNum|0)) {
listItems[0].setAttribute('value', opt_startLineNum);
}
var ol = document.createElement('ol');
ol.className = 'linenums';
var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
for (var i = 0, n = listItems.length; i < n; ++i) {
li = listItems[i];
// Stick a class on the LIs so that stylesheets can
// color odd/even rows, or any other row pattern that
// is co-prime with 10.
li.className = 'L' + ((i + offset) % 10);
if (!li.firstChild) {
li.appendChild(document.createTextNode('\xA0'));
}
ol.appendChild(li);
}
node.appendChild(ol);
}
/**
* Breaks {@code job.sourceCode} around style boundaries in
* {@code job.decorations} and modifies {@code job.sourceNode} in place.
* @param {Object} job like <pre>{
* sourceCode: {string} source as plain text,
* sourceNode: {HTMLElement} the element containing the source,
* spans: {Array.<number|Node>} alternating span start indices into source
* and the text node or element (e.g. {@code <BR>}) corresponding to that
* span.
* decorations: {Array.<number|string} an array of style classes preceded
* by the position at which they start in job.sourceCode in order
* }</pre>
* @private
*/
function recombineTagsAndDecorations(job) {
var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
var newlineRe = /\n/g;
var source = job.sourceCode;
var sourceLength = source.length;
// Index into source after the last code-unit recombined.
var sourceIndex = 0;
var spans = job.spans;
var nSpans = spans.length;
// Index into spans after the last span which ends at or before sourceIndex.
var spanIndex = 0;
var decorations = job.decorations;
var nDecorations = decorations.length;
// Index into decorations after the last decoration which ends at or before
// sourceIndex.
var decorationIndex = 0;
// Remove all zero-length decorations.
decorations[nDecorations] = sourceLength;
var decPos, i;
for (i = decPos = 0; i < nDecorations;) {
if (decorations[i] !== decorations[i + 2]) {
decorations[decPos++] = decorations[i++];
decorations[decPos++] = decorations[i++];
} else {
i += 2;
}
}
nDecorations = decPos;
// Simplify decorations.
for (i = decPos = 0; i < nDecorations;) {
var startPos = decorations[i];
// Conflate all adjacent decorations that use the same style.
var startDec = decorations[i + 1];
var end = i + 2;
while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
end += 2;
}
decorations[decPos++] = startPos;
decorations[decPos++] = startDec;
i = end;
}
nDecorations = decorations.length = decPos;
var sourceNode = job.sourceNode;
var oldDisplay;
if (sourceNode) {
oldDisplay = sourceNode.style.display;
sourceNode.style.display = 'none';
}
try {
var decoration = null;
while (spanIndex < nSpans) {
var spanStart = spans[spanIndex];
var spanEnd = spans[spanIndex + 2] || sourceLength;
var decEnd = decorations[decorationIndex + 2] || sourceLength;
var end = Math.min(spanEnd, decEnd);
var textNode = spans[spanIndex + 1];
var styledText;
if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s
// Don't introduce spans around empty text nodes.
&& (styledText = source.substring(sourceIndex, end))) {
// This may seem bizarre, and it is. Emitting LF on IE causes the
// code to display with spaces instead of line breaks.
// Emitting Windows standard issue linebreaks (CRLF) causes a blank
// space to appear at the beginning of every line but the first.
// Emitting an old Mac OS 9 line separator makes everything spiffy.
if (isIE8OrEarlier) {
styledText = styledText.replace(newlineRe, '\r');
}
textNode.nodeValue = styledText;
var document = textNode.ownerDocument;
var span = document.createElement('span');
span.className = decorations[decorationIndex + 1];
var parentNode = textNode.parentNode;
parentNode.replaceChild(span, textNode);
span.appendChild(textNode);
if (sourceIndex < spanEnd) { // Split off a text node.
spans[spanIndex + 1] = textNode
// TODO: Possibly optimize by using '' if there's no flicker.
= document.createTextNode(source.substring(end, spanEnd));
parentNode.insertBefore(textNode, span.nextSibling);
}
}
sourceIndex = end;
if (sourceIndex >= spanEnd) {
spanIndex += 2;
}
if (sourceIndex >= decEnd) {
decorationIndex += 2;
}
}
} finally {
if (sourceNode) {
sourceNode.style.display = oldDisplay;
}
}
}
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
* @param {function (Object)} handler a function from source code to a list
* of decorations. Takes a single argument job which describes the
* state of the computation. The single parameter has the form
* {@code {
* sourceCode: {string} as plain text.
* decorations: {Array.<number|string>} an array of style classes
* preceded by the position at which they start in
* job.sourceCode in order.
* The language handler should assigned this field.
* basePos: {int} the position of source in the larger source chunk.
* All positions in the output decorations array are relative
* to the larger source chunk.
* } }
* @param {Array.<string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
function langHandlerForExtension(extension, source) {
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
extension = /^\s*</.test(source)
? 'default-markup'
: 'default-code';
}
return langHandlerRegistry[extension];
}
registerLangHandler(decorateSource, ['default-code']);
registerLangHandler(
createSimpleLexer(
[],
[
[PR_PLAIN, /^[^<?]+/],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
[PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
// Unescaped content in an unknown language
['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
['lang-', /^<%([\s\S]+?)(?:%>|$)/],
[PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
// Unescaped content in javascript. (Or possibly vbscript).
['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
// Contains unescaped stylesheet content
['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
]),
['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
registerLangHandler(
createSimpleLexer(
[
[PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
[PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
],
[
[PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
[PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
[PR_PUNCTUATION, /^[=<>\/]+/],
['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
]),
['in.tag']);
registerLangHandler(
createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
registerLangHandler(sourceDecorator({
'keywords': CPP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'types': C_TYPES
}), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
registerLangHandler(sourceDecorator({
'keywords': 'null,true,false'
}), ['json']);
registerLangHandler(sourceDecorator({
'keywords': CSHARP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'verbatimStrings': true,
'types': C_TYPES
}), ['cs']);
registerLangHandler(sourceDecorator({
'keywords': JAVA_KEYWORDS,
'cStyleComments': true
}), ['java']);
registerLangHandler(sourceDecorator({
'keywords': SH_KEYWORDS,
'hashComments': true,
'multiLineStrings': true
}), ['bash', 'bsh', 'csh', 'sh']);
registerLangHandler(sourceDecorator({
'keywords': PYTHON_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'tripleQuotedStrings': true
}), ['cv', 'py', 'python']);
registerLangHandler(sourceDecorator({
'keywords': PERL_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': 2 // multiline regex literals
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
'keywords': RUBY_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['rb', 'ruby']);
registerLangHandler(sourceDecorator({
'keywords': JSCRIPT_KEYWORDS,
'cStyleComments': true,
'regexLiterals': true
}), ['javascript', 'js']);
registerLangHandler(sourceDecorator({
'keywords': COFFEE_KEYWORDS,
'hashComments': 3, // ### style block comments
'cStyleComments': true,
'multilineStrings': true,
'tripleQuotedStrings': true,
'regexLiterals': true
}), ['coffee']);
registerLangHandler(sourceDecorator({
'keywords': RUST_KEYWORDS,
'cStyleComments': true,
'multilineStrings': true
}), ['rc', 'rs', 'rust']);
registerLangHandler(
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
function applyDecorator(job) {
var opt_langExtension = job.langExtension;
try {
// Extract tags, and convert the source code to plain text.
var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
/** Plain text. @type {string} */
var source = sourceAndSpans.sourceCode;
job.sourceCode = source;
job.spans = sourceAndSpans.spans;
job.basePos = 0;
// Apply the appropriate language handler
langHandlerForExtension(opt_langExtension, source)(job);
// Integrate the decorations and tags back into the source code,
// modifying the sourceNode in place.
recombineTagsAndDecorations(job);
} catch (e) {
if (win['console']) {
console['log'](e && e['stack'] || e);
}
}
}
/**
* Pretty print a chunk of code.
* @param sourceCodeHtml {string} The HTML to pretty print.
* @param opt_langExtension {string} The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param opt_numberLines {number|boolean} True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
*/
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
// The pre-tag is required for IE8 which strips newlines from innerHTML
// when it is injected into a <pre> tag.
// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = container.firstChild;
if (opt_numberLines) {
numberLines(container, opt_numberLines, true);
}
var job = {
langExtension: opt_langExtension,
numberLines: opt_numberLines,
sourceNode: container,
pre: 1
};
applyDecorator(job);
return container.innerHTML;
}
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function} opt_whenDone called when prettifying is done.
* @param {HTMLElement|HTMLDocument} opt_root an element or document
* containing all the elements to pretty print.
* Defaults to {@code document.body}.
*/
function $prettyPrint(opt_whenDone, opt_root) {
var root = opt_root || document.body;
var doc = root.ownerDocument || document;
function byTagName(tn) { return root.getElementsByTagName(tn); }
// fetch a list of nodes to rewrite
var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
var clock = Date;
if (!clock['now']) {
clock = { 'now': function () { return +(new Date); } };
}
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
var prettyPrintingJob;
var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
var prettyPrintRe = /\bprettyprint\b/;
var prettyPrintedRe = /\bprettyprinted\b/;
var preformattedTagNameRe = /pre|xmp/i;
var codeRe = /^code$/i;
var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
var EMPTY = {};
function doWork() {
var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
clock['now']() + 250 /* ms */ :
Infinity);
for (; k < elements.length && clock['now']() < endTime; k++) {
var cs = elements[k];
// Look for a preceding comment like
// <?prettify lang="..." linenums="..."?>
var attrs = EMPTY;
{
for (var preceder = cs; (preceder = preceder.previousSibling);) {
var nt = preceder.nodeType;
// <?foo?> is parsed by HTML 5 to a comment node (8)
// like <!--?foo?-->, but in XML is a processing instruction
var value = (nt === 7 || nt === 8) && preceder.nodeValue;
if (value
? !/^\??prettify\b/.test(value)
: (nt !== 3 || /\S/.test(preceder.nodeValue))) {
// Skip over white-space text nodes but not others.
break;
}
if (value) {
attrs = {};
value.replace(
/\b(\w+)=([\w:.%+-]+)/g,
function (_, name, value) { attrs[name] = value; });
break;
}
}
}
var className = cs.className;
if ((attrs !== EMPTY || prettyPrintRe.test(className))
// Don't redo this if we've already done it.
// This allows recalling pretty print to just prettyprint elements
// that have been added to the page since last call.
&& !prettyPrintedRe.test(className)) {
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p; p = p.parentNode) {
var tn = p.tagName;
if (preCodeXmpRe.test(tn)
&& p.className && prettyPrintRe.test(p.className)) {
nested = true;
break;
}
}
if (!nested) {
// Mark done. If we fail to prettyprint for whatever reason,
// we shouldn't try again.
cs.className += ' prettyprinted';
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler
// as passed to PR.registerLangHandler.
// HTML5 recommends that a language be specified using "language-"
// as the prefix instead. Google Code Prettify supports both.
// http://dev.w3.org/html5/spec-author-view/the-code-element.html
var langExtension = attrs['lang'];
if (!langExtension) {
langExtension = className.match(langExtensionRe);
// Support <pre class="prettyprint"><code class="language-c">
var wrapper;
if (!langExtension && (wrapper = childContentWrapper(cs))
&& codeRe.test(wrapper.tagName)) {
langExtension = wrapper.className.match(langExtensionRe);
}
if (langExtension) { langExtension = langExtension[1]; }
}
var preformatted;
if (preformattedTagNameRe.test(cs.tagName)) {
preformatted = 1;
} else {
var currentStyle = cs['currentStyle'];
var defaultView = doc.defaultView;
var whitespace = (
currentStyle
? currentStyle['whiteSpace']
: (defaultView
&& defaultView.getComputedStyle)
? defaultView.getComputedStyle(cs, null)
.getPropertyValue('white-space')
: 0);
preformatted = whitespace
&& 'pre' === whitespace.substring(0, 3);
}
// Look for a class like linenums or linenums:<n> where <n> is the
// 1-indexed number of the first line.
var lineNums = attrs['linenums'];
if (!(lineNums = lineNums === 'true' || +lineNums)) {
lineNums = className.match(/\blinenums\b(?::(\d+))?/);
lineNums =
lineNums
? lineNums[1] && lineNums[1].length
? +lineNums[1] : true
: false;
}
if (lineNums) { numberLines(cs, lineNums, preformatted); }
// do the pretty printing
prettyPrintingJob = {
langExtension: langExtension,
sourceNode: cs,
numberLines: lineNums,
pre: preformatted
};
applyDecorator(prettyPrintingJob);
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if ('function' === typeof opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
/**
* Contains functions for creating and registering new language handlers.
* @type {Object}
*/
var PR = win['PR'] = {
'createSimpleLexer': createSimpleLexer,
'registerLangHandler': registerLangHandler,
'sourceDecorator': sourceDecorator,
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
'PR_COMMENT': PR_COMMENT,
'PR_DECLARATION': PR_DECLARATION,
'PR_KEYWORD': PR_KEYWORD,
'PR_LITERAL': PR_LITERAL,
'PR_NOCODE': PR_NOCODE,
'PR_PLAIN': PR_PLAIN,
'PR_PUNCTUATION': PR_PUNCTUATION,
'PR_SOURCE': PR_SOURCE,
'PR_STRING': PR_STRING,
'PR_TAG': PR_TAG,
'PR_TYPE': PR_TYPE,
'prettyPrintOne':
IN_GLOBAL_SCOPE
? (win['prettyPrintOne'] = $prettyPrintOne)
: (prettyPrintOne = $prettyPrintOne),
'prettyPrint': prettyPrint =
IN_GLOBAL_SCOPE
? (win['prettyPrint'] = $prettyPrint)
: (prettyPrint = $prettyPrint)
};
// Make PR available via the Asynchronous Module Definition (AMD) API.
// Per https://github.com/amdjs/amdjs-api/wiki/AMD:
// The Asynchronous Module Definition (AMD) API specifies a
// mechanism for defining modules such that the module and its
// dependencies can be asynchronously loaded.
// ...
// To allow a clear indicator that a global define function (as
// needed for script src browser loading) conforms to the AMD API,
// any global define function SHOULD have a property called "amd"
// whose value is an object. This helps avoid conflict with any
// other existing JavaScript code that could have defined a define()
// function that does not conform to the AMD API.
if (typeof define === "function" && define['amd']) {
define("google-code-prettify", [], function () {
return PR;
});
}
})();
| {
"content_hash": "49ee5725ddb098873a53e91a80952345",
"timestamp": "",
"source": "github",
"line_count": 1654,
"max_line_length": 238,
"avg_line_length": 38.278113663845225,
"alnum_prop": 0.563052817791256,
"repo_name": "Kodemon/reach-yuidoc-theme",
"id": "2e4c62c170c27bd87c7a339ebde937e4a5501de2",
"size": "63312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/vendor/prettify/prettify.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33751"
}
],
"symlink_target": ""
} |
import enum
from typing import Dict, Set
@enum.unique
class NotificationType(enum.IntEnum):
"""
Constants regarding the different types of notification we can send to a device
See https://docs.google.com/document/d/1SV-hNCtgAn2hSMZaC973UdLHCFXCNpvq_RKq0UoY4yg/edit#
"""
# DO NOT CHANGE THESE CONSTANTS
UPCOMING_MATCH = 0
MATCH_SCORE = 1
LEVEL_STARTING = 2
ALLIANCE_SELECTION = 3
AWARDS = 4
MEDIA_POSTED = 5
DISTRICT_POINTS_UPDATED = 6
SCHEDULE_UPDATED = 7
FINAL_RESULTS = 8
PING = 9 # This type of message is sent when the user hits 'ping device' in their account overview
BROADCAST = 10 # Gives functionality for admins to send to many devices
MATCH_VIDEO = 11
EVENT_MATCH_VIDEO = 12 # Not user exposed
# These aren't notifications, but used for upstream API calls
UPDATE_FAVORITES = 100
UPDATE_SUBSCRIPTIONS = 101
# This is used for verification that the proper people are in control
VERIFICATION = 200
TYPE_NAMES: Dict[NotificationType, str] = {
NotificationType.UPCOMING_MATCH: "upcoming_match",
NotificationType.MATCH_SCORE: "match_score",
NotificationType.LEVEL_STARTING: "starting_comp_level",
NotificationType.ALLIANCE_SELECTION: "alliance_selection",
NotificationType.AWARDS: "awards_posted",
NotificationType.MEDIA_POSTED: "media_posted",
NotificationType.DISTRICT_POINTS_UPDATED: "district_points_updated",
NotificationType.SCHEDULE_UPDATED: "schedule_updated",
NotificationType.FINAL_RESULTS: "final_results",
NotificationType.PING: "ping",
NotificationType.BROADCAST: "broadcast",
NotificationType.MATCH_VIDEO: "match_video",
NotificationType.EVENT_MATCH_VIDEO: "event_match_video",
NotificationType.UPDATE_FAVORITES: "update_favorites",
NotificationType.UPDATE_SUBSCRIPTIONS: "update_subscriptions",
NotificationType.VERIFICATION: "verification",
}
RENDER_NAMES: Dict[NotificationType, str] = {
NotificationType.UPCOMING_MATCH: "Upcoming Match",
NotificationType.MATCH_SCORE: "Match Score",
NotificationType.LEVEL_STARTING: "Competition Level Starting",
NotificationType.ALLIANCE_SELECTION: "Alliance Selection",
NotificationType.AWARDS: "Awards Posted",
NotificationType.MEDIA_POSTED: "Media Posted",
NotificationType.DISTRICT_POINTS_UPDATED: "District Points Updated",
NotificationType.SCHEDULE_UPDATED: "Event Schedule Updated",
NotificationType.FINAL_RESULTS: "Final Results",
NotificationType.MATCH_VIDEO: "Match Video Added",
NotificationType.EVENT_MATCH_VIDEO: "Match Video Added",
}
TYPES: Dict[str, NotificationType] = {
"upcoming_match": NotificationType.UPCOMING_MATCH,
"match_score": NotificationType.MATCH_SCORE,
"starting_comp_level": NotificationType.LEVEL_STARTING,
"alliance_selection": NotificationType.ALLIANCE_SELECTION,
"awards_posted": NotificationType.AWARDS,
"media_posted": NotificationType.MEDIA_POSTED,
"district_points_updated": NotificationType.DISTRICT_POINTS_UPDATED,
"schedule_updated": NotificationType.SCHEDULE_UPDATED,
"final_results": NotificationType.FINAL_RESULTS,
"match_video": NotificationType.MATCH_VIDEO,
"event_match_video": NotificationType.EVENT_MATCH_VIDEO,
"update_favorites": NotificationType.UPDATE_FAVORITES,
"update_subscriptions": NotificationType.UPDATE_SUBSCRIPTIONS,
"verification": NotificationType.VERIFICATION,
}
ENABLED_NOTIFICATIONS: Dict[NotificationType, str] = {
NotificationType.UPCOMING_MATCH: RENDER_NAMES[NotificationType.UPCOMING_MATCH],
NotificationType.MATCH_SCORE: RENDER_NAMES[NotificationType.MATCH_SCORE],
NotificationType.MATCH_VIDEO: RENDER_NAMES[NotificationType.MATCH_VIDEO],
NotificationType.LEVEL_STARTING: RENDER_NAMES[NotificationType.LEVEL_STARTING],
NotificationType.ALLIANCE_SELECTION: RENDER_NAMES[
NotificationType.ALLIANCE_SELECTION
],
NotificationType.AWARDS: RENDER_NAMES[NotificationType.AWARDS],
NotificationType.SCHEDULE_UPDATED: RENDER_NAMES[NotificationType.SCHEDULE_UPDATED],
}
ENABLED_EVENT_NOTIFICATIONS: Set[NotificationType] = {
NotificationType.UPCOMING_MATCH,
NotificationType.MATCH_SCORE,
NotificationType.LEVEL_STARTING,
NotificationType.ALLIANCE_SELECTION,
NotificationType.AWARDS,
NotificationType.SCHEDULE_UPDATED,
NotificationType.MATCH_VIDEO,
}
ENABLED_TEAM_NOTIFICATIONS: Set[NotificationType] = {
NotificationType.UPCOMING_MATCH,
NotificationType.MATCH_SCORE,
NotificationType.ALLIANCE_SELECTION,
NotificationType.AWARDS,
NotificationType.MATCH_VIDEO,
}
ENABLED_MATCH_NOTIFICATIONS: Set[NotificationType] = {
NotificationType.UPCOMING_MATCH,
NotificationType.MATCH_SCORE,
NotificationType.MATCH_VIDEO,
}
| {
"content_hash": "a35446a39a4e803fbe048d3e77df3d7a",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 103,
"avg_line_length": 38.166666666666664,
"alnum_prop": 0.7540029112081513,
"repo_name": "the-blue-alliance/the-blue-alliance",
"id": "c60049545a54cc28c5ca95e9d1e0c10939446238",
"size": "4809",
"binary": false,
"copies": "1",
"ref": "refs/heads/py3",
"path": "src/backend/common/consts/notification_type.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "359032"
},
{
"name": "Dockerfile",
"bytes": "2503"
},
{
"name": "HTML",
"bytes": "5877313"
},
{
"name": "JavaScript",
"bytes": "755910"
},
{
"name": "Less",
"bytes": "244218"
},
{
"name": "PHP",
"bytes": "10727"
},
{
"name": "Pug",
"bytes": "1857"
},
{
"name": "Python",
"bytes": "4321885"
},
{
"name": "Ruby",
"bytes": "4677"
},
{
"name": "Shell",
"bytes": "27698"
}
],
"symlink_target": ""
} |
<!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_171-google-v7) on Mon Apr 08 11:10:18 PDT 2019 -->
<title>LogQuery.Builder (Google App Engine API for Java)</title>
<meta name="date" content="2019-04-08">
<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="LogQuery.Builder (Google App Engine API for Java)";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":9,"i2":9,"i3":9,"i4":9,"i5":9,"i6":9,"i7":9,"i8":9,"i9":9,"i10":9,"i11":9,"i12":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/google/appengine/api/log/LogQuery.Version.html" title="class in com.google.appengine.api.log"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/appengine/api/log/LogQuery.Builder.html" target="_top">Frames</a></li>
<li><a href="LogQuery.Builder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.google.appengine.api.log</div>
<h2 title="Class LogQuery.Builder" class="title">Class LogQuery.Builder</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.google.appengine.api.log.LogQuery.Builder</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></dd>
</dl>
<hr>
<br>
<pre>public static final class <span class="typeNameLabel">LogQuery.Builder</span>
extends java.lang.Object</pre>
<div class="block">Contains static creation methods for <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a>.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#Builder--">Builder</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withBatchSize-int-">withBatchSize</a></span>(int batchSize)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given batch size.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withDefaults--">withDefaults</a></span>()</code>
<div class="block">Helper method for creating a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> instance with
default values.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withEndTimeMillis-long-">withEndTimeMillis</a></span>(long endTimeMillis)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given end time.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withEndTimeUsec-long-">withEndTimeUsec</a></span>(long endTimeUsec)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given end time.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withIncludeAppLogs-boolean-">withIncludeAppLogs</a></span>(boolean includeAppLogs)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with include application logs set.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withIncludeIncomplete-boolean-">withIncludeIncomplete</a></span>(boolean includeIncomplete)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given include incomplete setting.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withMajorVersionIds-java.util.List-">withMajorVersionIds</a></span>(java.util.List<java.lang.String> versionIds)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given major version IDs.</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withMinLogLevel-com.google.appengine.api.log.LogService.LogLevel-">withMinLogLevel</a></span>(<a href="../../../../../com/google/appengine/api/log/LogService.LogLevel.html" title="enum in com.google.appengine.api.log">LogService.LogLevel</a> minLogLevel)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given minimum log level.</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withOffset-java.lang.String-">withOffset</a></span>(java.lang.String offset)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given offset.</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withRequestIds-java.util.List-">withRequestIds</a></span>(java.util.List<java.lang.String> requestIds)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given request IDs.</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withStartTimeMillis-long-">withStartTimeMillis</a></span>(long startTimeMillis)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given start time.</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withStartTimeUsec-long-">withStartTimeUsec</a></span>(long startTimeUsec)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given start time.</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/log/LogQuery.Builder.html#withVersions-java.util.List-">withVersions</a></span>(java.util.List<<a href="../../../../../com/google/appengine/api/log/LogQuery.Version.html" title="class in com.google.appengine.api.log">LogQuery.Version</a>> versions)</code>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given <a href="../../../../../com/google/appengine/api/log/LogQuery.Version.html" title="class in com.google.appengine.api.log"><code>LogQuery.Version</code></a> values.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Builder--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Builder</h4>
<pre>public Builder()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="withOffset-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withOffset</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withOffset(java.lang.String offset)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given offset.
Shorthand for <code>LogQuery.Builder.withDefaults().offset(offset);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how offsets are used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>offset</code> - the offset to use.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withStartTimeMillis-long-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withStartTimeMillis</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withStartTimeMillis(long startTimeMillis)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given start time.
Shorthand for <code>LogQuery.Builder.withDefaults().startTimeMillis(startTimeMillis);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how start time is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>startTimeMillis</code> - the start time to use, in milliseconds.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withStartTimeUsec-long-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withStartTimeUsec</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withStartTimeUsec(long startTimeUsec)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given start time.
Shorthand for <code>LogQuery.Builder.withDefaults().startTimeUsec(startTimeUsec);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how start time is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>startTimeUsec</code> - the start time to use, in microseconds.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withEndTimeMillis-long-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withEndTimeMillis</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withEndTimeMillis(long endTimeMillis)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given end time.
Shorthand for <code>LogQuery.Builder.withDefaults().endTimeMillis(endTimeMillis);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how end time is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>endTimeMillis</code> - the start time to use, in milliseconds.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withEndTimeUsec-long-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withEndTimeUsec</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withEndTimeUsec(long endTimeUsec)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given end time.
Shorthand for <code>LogQuery.Builder.withDefaults().endTimeUsec(endTimeUsec);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how end time is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>endTimeUsec</code> - the start time to use, in microseconds.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withBatchSize-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withBatchSize</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withBatchSize(int batchSize)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given batch size.
Shorthand for <code>LogQuery.Builder.withDefaults().batchSize(batchSize);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how batch size is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>batchSize</code> - the batch size to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withMinLogLevel-com.google.appengine.api.log.LogService.LogLevel-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withMinLogLevel</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withMinLogLevel(<a href="../../../../../com/google/appengine/api/log/LogService.LogLevel.html" title="enum in com.google.appengine.api.log">LogService.LogLevel</a> minLogLevel)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given minimum log level.
Shorthand for <code>LogQuery.Builder.withDefaults().minLogLevel(minLogLevel);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how minimum log level is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>minLogLevel</code> - the minimum log level to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withIncludeIncomplete-boolean-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withIncludeIncomplete</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withIncludeIncomplete(boolean includeIncomplete)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given include incomplete setting.
Shorthand for
<code>LogQuery.Builder.withDefaults().includeIncomplete(includeIncomplete);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how include incomplete is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>includeIncomplete</code> - the inclusion value to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withIncludeAppLogs-boolean-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withIncludeAppLogs</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withIncludeAppLogs(boolean includeAppLogs)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with include application logs set.
Shorthand for <code>LogQuery.Builder.withDefaults().includeAppLogs(includeAppLogs);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
the include application logs setting.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>includeAppLogs</code> - the inclusion value to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withMajorVersionIds-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withMajorVersionIds</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withMajorVersionIds(java.util.List<java.lang.String> versionIds)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given major version IDs.
Shorthand for <code>LogQuery.Builder.withDefaults().majorVersionIds(versionIds);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how the list of major version ids is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>versionIds</code> - the major version id list to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withVersions-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withVersions</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withVersions(java.util.List<<a href="../../../../../com/google/appengine/api/log/LogQuery.Version.html" title="class in com.google.appengine.api.log">LogQuery.Version</a>> versions)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given <a href="../../../../../com/google/appengine/api/log/LogQuery.Version.html" title="class in com.google.appengine.api.log"><code>LogQuery.Version</code></a> values.
Shorthand for
<code>LogQuery.Builder.withDefaults().versions(versions);</code>.
Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for usage information.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>versions</code> - the list to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
</dl>
</li>
</ul>
<a name="withRequestIds-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withRequestIds</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withRequestIds(java.util.List<java.lang.String> requestIds)</pre>
<div class="block">Create a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> with the given request IDs.
Shorthand for <code>LogQuery.Builder.withDefaults().requestIds(requestIds);</code>.
See the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an explanation of
how the list of request ids is used.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>requestIds</code> - the request id list to set.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The newly created LogQuery instance.</dd>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>App Engine 1.7.4.</dd>
</dl>
</li>
</ul>
<a name="withDefaults--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>withDefaults</h4>
<pre>public static <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log">LogQuery</a> withDefaults()</pre>
<div class="block">Helper method for creating a <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> instance with
default values. Please read the <a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><code>LogQuery</code></a> class javadoc for an
explanation of the defaults.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="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 class="aboutLanguage">Java is a registered trademark of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/google/appengine/api/log/LogQuery.html" title="class in com.google.appengine.api.log"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/google/appengine/api/log/LogQuery.Version.html" title="class in com.google.appengine.api.log"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/appengine/api/log/LogQuery.Builder.html" target="_top">Frames</a></li>
<li><a href="LogQuery.Builder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "2902ef75861cde7b1d95b0db130e731e",
"timestamp": "",
"source": "github",
"line_count": 584,
"max_line_length": 396,
"avg_line_length": 55.73972602739726,
"alnum_prop": 0.6775006144015728,
"repo_name": "googlearchive/caja",
"id": "8ed30f0b02f1e19f4dde31071ef2a38189cf34d4",
"size": "32552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third_party/java/appengine/docs/javadoc/com/google/appengine/api/log/LogQuery.Builder.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "30715"
},
{
"name": "HTML",
"bytes": "1086467"
},
{
"name": "Java",
"bytes": "2541899"
},
{
"name": "JavaScript",
"bytes": "2102219"
},
{
"name": "Perl",
"bytes": "25768"
},
{
"name": "Python",
"bytes": "150158"
},
{
"name": "Shell",
"bytes": "13072"
},
{
"name": "XSLT",
"bytes": "27472"
}
],
"symlink_target": ""
} |
//
// JBaseView.m
// Journey
//
// Created by Wayde Sun on 6/30/13.
// Copyright (c) 2013 iHakula. All rights reserved.
//
#import "BBQBaseView.h"
@implementation BBQBaseView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@end
| {
"content_hash": "207fa82890c061b4dd17b4044d640e67",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 74,
"avg_line_length": 17.096774193548388,
"alnum_prop": 0.6660377358490566,
"repo_name": "wayde191/tulip",
"id": "ef71fa5f6b9ae6d13e91f9025920fc0d7e3003f2",
"size": "530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "appointment/appointment/Common/MVC/BBQBaseView.m",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1347"
},
{
"name": "HTML",
"bytes": "4555"
},
{
"name": "Objective-C",
"bytes": "1102476"
},
{
"name": "Ruby",
"bytes": "465"
},
{
"name": "Shell",
"bytes": "4587"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>infotheo: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.3 / infotheo - 0.1.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
infotheo
<small>
0.1.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-31 04:59:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-31 04:59:10 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.5.3 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "reynald.affeldt@aist.go.jp"
homepage: "https://github.com/affeldt-aist/infotheo"
bug-reports: "https://github.com/affeldt-aist/infotheo/issues"
dev-repo: "git+https://github.com/affeldt-aist/infotheo.git"
license: "GPL-3.0-or-later"
authors: [
"Reynald Affeldt"
"Manabu Hagiwara"
"Jonas Senizergues"
"Jacques Garrigue"
"Kazuhiko Sakaguchi"
"Taku Asai"
"Takafumi Saikawa"
"Naruomi Obata"
"Erik Martin-Dorel"
"Ryosuke Obi"
"Mitsuharu Yamamoto"
]
build: [
[make "-j%{jobs}%"]
[make "-C" "extraction" "tests"] {with-test}
]
install: [
[make "install"]
]
depends: [
"coq" {>= "8.11" & < "8.13~"}
"coq-mathcomp-field" {>= "1.11" & < "1.12~"}
"coq-mathcomp-analysis" {>= "0.3.2" & < "0.3.3~"}
]
synopsis: "Infotheo"
description: """
a Coq formalization of information theory and linear error-correcting codes
"""
tags: [
"category:Computer Science/Data Types and Data Structures"
"keyword: information theory"
"keyword: probability"
"keyword: error-correcting codes"
"logpath:infotheo"
"date:2020-08-11"
]
url {
http: "https://github.com/affeldt-aist/infotheo/archive/0.1.2.tar.gz"
checksum: "sha512=3ae60b960db080bdb176adf7713126d03e1046764da96114ac8bb89de427750819115505844a887b6b82b6250391ff869141f0cb1594c3f87fa1715d45de17ea"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-infotheo.0.1.2 coq.8.5.3</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.3).
The following dependencies couldn't be met:
- coq-infotheo -> coq >= 8.11 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-infotheo.0.1.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "b0576c412b135b6206bd9a4ec0c61a51",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 159,
"avg_line_length": 39.81283422459893,
"alnum_prop": 0.5527199462726662,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "a5e40693cda4bfc908557a679f7ee8b6c5745418",
"size": "7470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.3/infotheo/0.1.2.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0"?>
<layout>
<adminhtml_faq_index>
<reference name="content">
<block type="edgecom_faq/adminhtml_faq" name="faq" />
</reference>
</adminhtml_faq_index>
</layout>
| {
"content_hash": "3613d6bf0623ced0e8649f7949dd1937",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 65,
"avg_line_length": 27,
"alnum_prop": 0.5787037037037037,
"repo_name": "edgecom/faq",
"id": "e6b229cc927f0a43a87bc5f493c7e625d6f0c4e8",
"size": "216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/design/adminhtml/default/default/layout/edgecom/faq.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "3134"
}
],
"symlink_target": ""
} |
package org.pac4j.saml.client;
import org.junit.Test;
import org.pac4j.saml.util.Configuration;
import java.io.File;
import static org.junit.Assert.*;
/**
* Unit tests for the SAML2Client.
*/
public class SAML2ClientTest {
public SAML2ClientTest() {
assertNotNull(Configuration.getParserPool());
assertNotNull(Configuration.getMarshallerFactory());
assertNotNull(Configuration.getUnmarshallerFactory());
assertNotNull(Configuration.getBuilderFactory());
}
@Test
public void testIdpMetadataParsing_fromFile() {
final SAML2Client client = getClient();
client.getConfiguration().setIdentityProviderMetadataPath("resource:testshib-providers.xml");
client.init();
client.getIdentityProviderMetadataResolver().resolve();
final String id = client.getIdentityProviderMetadataResolver().getEntityId();
assertEquals("https://idp.testshib.org/idp/shibboleth", id);
}
@Test
public void testIdpMetadataParsing_fromUrl() {
final SAML2Client client = getClient();
client.getConfiguration().setIdentityProviderMetadataPath("https://idp.testshib.org/idp/profile/Metadata/SAML");
client.init();
client.getIdentityProviderMetadataResolver().resolve();
final String id = client.getIdentityProviderMetadataResolver().getEntityId();
assertEquals("https://idp.testshib.org/idp/shibboleth", id);
}
protected final SAML2Client getClient() {
final SAML2ClientConfiguration cfg =
new SAML2ClientConfiguration("resource:samlKeystore.jks",
"pac4j-demo-passwd",
"pac4j-demo-passwd",
"resource:testshib-providers.xml");
cfg.setMaximumAuthenticationLifetime(3600);
cfg.setServiceProviderEntityId("urn:mace:saml:pac4j.org");
cfg.setServiceProviderMetadataPath(new File("target", "sp-metadata.xml").getAbsolutePath());
final SAML2Client saml2Client = new SAML2Client(cfg);
saml2Client.setCallbackUrl("http://localhost:8080/something");
return saml2Client;
}
}
| {
"content_hash": "c27126133841bbea1f1edd0b1270f71b",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 120,
"avg_line_length": 33.703125,
"alnum_prop": 0.6852109411219286,
"repo_name": "robgratz/pac4j",
"id": "2f263f7ba928e933eb0749b2460e2d391c5902a2",
"size": "2758",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pac4j-saml/src/test/java/org/pac4j/saml/client/SAML2ClientTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1537105"
},
{
"name": "Shell",
"bytes": "335"
}
],
"symlink_target": ""
} |
'use strict';
describe('ReactDOMProduction', () => {
var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
var React;
var ReactDOM;
var oldProcess;
beforeEach(() => {
__DEV__ = false;
// Mutating process.env.NODE_ENV would cause our babel plugins to do the
// wrong thing. If you change this, make sure to test with jest --no-cache.
oldProcess = process;
global.process = {
...process,
env: {...process.env, NODE_ENV: 'production'},
};
jest.resetModules();
React = require('React');
ReactDOM = require('ReactDOM');
});
afterEach(() => {
__DEV__ = true;
global.process = oldProcess;
});
it('should use prod fbjs', () => {
var warning = require('warning');
spyOn(console, 'error');
warning(false, 'Do cows go moo?');
expectDev(console.error.calls.count()).toBe(0);
});
it('should use prod React', () => {
spyOn(console, 'error');
// no key warning
void <div>{[<span />]}</div>;
expectDev(console.error.calls.count()).toBe(0);
});
it('should handle a simple flow', () => {
class Component extends React.Component {
render() {
return <span>{this.props.children}</span>;
}
}
var container = document.createElement('div');
var inst = ReactDOM.render(
<div className="blue">
<Component key={1}>A</Component>
<Component key={2}>B</Component>
<Component key={3}>C</Component>
</div>,
container
);
expect(container.firstChild).toBe(inst);
expect(inst.className).toBe('blue');
expect(inst.textContent).toBe('ABC');
ReactDOM.render(
<div className="red">
<Component key={2}>B</Component>
<Component key={1}>A</Component>
<Component key={3}>C</Component>
</div>,
container
);
expect(inst.className).toBe('red');
expect(inst.textContent).toBe('BAC');
ReactDOM.unmountComponentAtNode(container);
expect(container.childNodes.length).toBe(0);
});
it('should call lifecycle methods', () => {
var log = [];
class Component extends React.Component {
state = {y: 1};
shouldComponentUpdate(nextProps, nextState) {
log.push(['shouldComponentUpdate', nextProps, nextState]);
return nextProps.x !== this.props.x || nextState.y !== this.state.y;
}
componentWillMount() {
log.push(['componentWillMount']);
}
componentDidMount() {
log.push(['componentDidMount']);
}
componentWillReceiveProps(nextProps) {
log.push(['componentWillReceiveProps', nextProps]);
}
componentWillUpdate(nextProps, nextState) {
log.push(['componentWillUpdate', nextProps, nextState]);
}
componentDidUpdate(prevProps, prevState) {
log.push(['componentDidUpdate', prevProps, prevState]);
}
componentWillUnmount() {
log.push(['componentWillUnmount']);
}
render() {
log.push(['render']);
return null;
}
}
var container = document.createElement('div');
var inst = ReactDOM.render(
<Component x={1} />,
container
);
expect(log).toEqual([
['componentWillMount'],
['render'],
['componentDidMount'],
]);
log = [];
inst.setState({y: 2});
expect(log).toEqual([
['shouldComponentUpdate', {x: 1}, {y: 2}],
['componentWillUpdate', {x: 1}, {y: 2}],
['render'],
['componentDidUpdate', {x: 1}, {y: 1}],
]);
log = [];
inst.setState({y: 2});
expect(log).toEqual([
['shouldComponentUpdate', {x: 1}, {y: 2}],
]);
log = [];
ReactDOM.render(
<Component x={2} />,
container
);
expect(log).toEqual([
['componentWillReceiveProps', {x: 2}],
['shouldComponentUpdate', {x: 2}, {y: 2}],
['componentWillUpdate', {x: 2}, {y: 2}],
['render'],
['componentDidUpdate', {x: 1}, {y: 2}],
]);
log = [];
ReactDOM.render(
<Component x={2} />,
container
);
expect(log).toEqual([
['componentWillReceiveProps', {x: 2}],
['shouldComponentUpdate', {x: 2}, {y: 2}],
]);
log = [];
ReactDOM.unmountComponentAtNode(container);
expect(log).toEqual([
['componentWillUnmount'],
]);
});
it('should throw with an error code in production', () => {
expect(function() {
class Component extends React.Component {
render() {
return undefined;
}
}
var container = document.createElement('div');
ReactDOM.render(<Component />, container);
}).toThrowError(
'Minified React error #109; visit ' +
'http://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Component' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.'
);
});
it('should not crash with devtools installed', () => {
try {
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
inject: function() {},
onCommitFiberRoot: function() {},
onCommitFiberUnmount: function() {},
supportsFiber: true,
};
jest.resetModules();
React = require('React');
ReactDOM = require('ReactDOM');
class Component extends React.Component {
render() {
return <div />;
}
}
ReactDOM.render(<Component />, document.createElement('container'));
} finally {
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = undefined;
}
});
if (ReactDOMFeatureFlags.useFiber) {
// This test is originally from ReactDOMFiber-test but we replicate it here
// to avoid production-only regressions because of host context differences
// in dev and prod.
it('should keep track of namespace across portals in production', () => {
var svgEls, htmlEls;
var expectSVG = {ref: el => svgEls.push(el)};
var expectHTML = {ref: el => htmlEls.push(el)};
var usePortal = function(tree) {
return ReactDOM.unstable_createPortal(
tree,
document.createElement('div')
);
};
var assertNamespacesMatch = function(tree) {
var container = document.createElement('div');
svgEls = [];
htmlEls = [];
ReactDOM.render(tree, container);
svgEls.forEach(el => {
expect(el.namespaceURI).toBe('http://www.w3.org/2000/svg');
});
htmlEls.forEach(el => {
expect(el.namespaceURI).toBe('http://www.w3.org/1999/xhtml');
});
ReactDOM.unmountComponentAtNode(container);
expect(container.innerHTML).toBe('');
};
assertNamespacesMatch(
<div {...expectHTML}>
<svg {...expectSVG}>
<foreignObject {...expectSVG}>
<p {...expectHTML} />
{usePortal(
<svg {...expectSVG}>
<image {...expectSVG} />
<svg {...expectSVG}>
<image {...expectSVG} />
<foreignObject {...expectSVG}>
<p {...expectHTML} />
</foreignObject>
{usePortal(<p {...expectHTML} />)}
</svg>
<image {...expectSVG} />
</svg>
)}
<p {...expectHTML} />
</foreignObject>
<image {...expectSVG} />
</svg>
<p {...expectHTML} />
</div>
);
});
}
});
| {
"content_hash": "2a6d21f5c3b748a2cb302cf17942305d",
"timestamp": "",
"source": "github",
"line_count": 271,
"max_line_length": 96,
"avg_line_length": 27.837638376383765,
"alnum_prop": 0.5487804878048781,
"repo_name": "niubaba63/react",
"id": "aba6fc4ff996670026bc44040e268e8cefc576d2",
"size": "7873",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/renderers/dom/__tests__/ReactDOMProduction-test.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5341"
},
{
"name": "C++",
"bytes": "44974"
},
{
"name": "CSS",
"bytes": "1288"
},
{
"name": "CoffeeScript",
"bytes": "12252"
},
{
"name": "HTML",
"bytes": "6222"
},
{
"name": "JavaScript",
"bytes": "3322515"
},
{
"name": "Makefile",
"bytes": "189"
},
{
"name": "Python",
"bytes": "9383"
},
{
"name": "Shell",
"bytes": "5116"
},
{
"name": "TypeScript",
"bytes": "15529"
}
],
"symlink_target": ""
} |
package main
import (
"errors"
"time"
sj "github.com/bitly/go-simplejson"
"github.com/donnie4w/go-logger/logger"
"job"
)
type Workshop struct {
sub string // 业务的名字,打日志时有用
ctx *sj.Json
sleepWhenNeed bool // 当机器不健康时消极怠工
ctrlChan chan int // [0] unis -> channel -> control
reportChan chan int // [0] control -> channel -> unis
processorNum int
collectorNum int
workCtrlChan chan int // [1] control -> channel -> work
workReportChan chan int // [0] work -> channel -> control
msgChan chan string // [n] work -> channel -> processor
itemChans [](chan job.Item) // [n] processor -> channel -> collector
PRCtrlChans [](chan int) // [1] control -> channel(try) -> processor || work -> channel(wait) -> processor
PRReportChan chan int // [0] processor -> channel -> control
CLCtrlChans [](chan int) // [1] control -> channel(try) -> processor || work -> channel(wait) -> processor
CLReportChan chan int // [0] collector -> channel -> control
provider SrcProvider
// memLimit uint64
processedLine int
ticker_ *time.Ticker
}
func (p *Workshop) Init(sub string, ctx *sj.Json, ctrlChan chan int, reportChan chan int) (err error) {
p.sub = sub
// 将pub传下去,供processor和collector用
ctx.Set("runtime", map[string]interface{}{
"sub": sub,
})
p.ctx = ctx
p.ctrlChan = ctrlChan
p.reportChan = reportChan
p.processedLine = 0
if err = p.initSrcProvider(); err != nil {
logger.WarnSubf(p.sub, "Workshop.Init err: %v", err)
return err
}
// p.memLimit = ctx.Get("main").Get("mem_limit").MustUint64()
tickSec := ctx.Get("main").Get("tick_sec").MustInt(5)
p.ticker_ = time.NewTicker(time.Duration(tickSec) * time.Second)
p.sleepWhenNeed = ctx.Get("main").Get("sleep_when_need").MustBool(false)
p.workCtrlChan = make(chan int, 1)
p.workReportChan = make(chan int)
p.PRReportChan = make(chan int)
p.CLReportChan = make(chan int)
if err = p.initChannel(); err != nil {
return err
}
json_str, _ := p.ctx.MarshalJSON()
logger.InfoSubf(p.sub, "Workshop.Init success, ctx: %s", string(json_str))
return nil
}
func (p *Workshop) initChannel() error {
// create channels
p.processorNum = p.ctx.Get("main").Get("processor_num").MustInt()
p.collectorNum = p.ctx.Get("main").Get("collector_num").MustInt()
msgChanSize := p.ctx.Get("main").Get("msg_chan_size").MustInt()
itemChanSize := p.ctx.Get("main").Get("item_chan_size").MustInt()
p.msgChan = make(chan string, msgChanSize)
p.itemChans = make([](chan job.Item), p.collectorNum)
for i := 0; i < p.collectorNum; i++ {
p.itemChans[i] = make(chan job.Item, itemChanSize)
}
p.PRCtrlChans = make([](chan int), p.processorNum)
for i := 0; i < p.processorNum; i++ {
p.PRCtrlChans[i] = make(chan int, 1)
}
p.CLCtrlChans = make([](chan int), p.collectorNum)
for i := 0; i < p.collectorNum; i++ {
p.CLCtrlChans[i] = make(chan int, 1)
}
// start processor goroutines
processorSuccessNum := 0
for i := 0; i < p.processorNum; i++ {
go p.ProcessRoutine(i, p.PRCtrlChans[i])
}
for i := 0; i < p.processorNum; i++ {
isSuccess := <-p.PRReportChan
if isSuccess == RET_INIT_SUCCESS {
processorSuccessNum++
}
}
if processorSuccessNum < p.processorNum {
logger.WarnSubf(p.sub, "Workshop.initChannel failed processor success %d/%d",
processorSuccessNum, p.processorNum)
p.sendCtrlInfo(p.PRCtrlChans, CMD_EXIT)
return errors.New("some processor init fail")
}
logger.InfoSubf(p.sub, "Workshop.initChannel start %d processor, all success", processorSuccessNum)
// start collector goroutines
collectorSuccessNum := 0
for i := 0; i < p.collectorNum; i++ {
go p.CollectRoutine(i, p.CLCtrlChans[i], p.itemChans[i])
}
for i := 0; i < p.collectorNum; i++ {
isSuccess := <-p.CLReportChan
if isSuccess == RET_INIT_SUCCESS {
collectorSuccessNum++
}
}
if collectorSuccessNum < p.collectorNum {
logger.InfoSubf(p.sub, "Workshop.initChannel failed collector success %d/%d",
collectorSuccessNum, p.collectorNum)
p.sendCtrlInfo(p.PRCtrlChans, CMD_EXIT)
p.sendCtrlInfo(p.CLCtrlChans, CMD_EXIT)
return errors.New("some colletor init fail")
}
logger.InfoSubf(p.sub, "Workshop.initChannel start %d colletors", collectorSuccessNum)
return nil
}
func (p *Workshop) ProcessRoutine(id int, ctrlChannel chan int) {
processorFlags := p.ctx.Get("processor").MustMap() // eg: UrlProcessor => true
logger.InfoSubf(p.sub, "Workshop.ProcessRoutine begin id: %d, processor: %v", id, processorFlags)
processorMap := make(map[string]job.Processor)
for name, flag := range processorFlags {
enable, ok := flag.(bool)
if !ok {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine processor name: %s, setting invalid flag: %v", name, flag)
p.PRReportChan <- RET_INIT_FAIL
return
}
if !enable {
continue
}
processorMap[name] = job.NewProcessor(name)
if processorMap[name] == nil {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine processor %s create failed", name)
p.PRReportChan <- RET_INIT_FAIL
return
}
if err := processorMap[name].Init(p.ctx, id, p.itemChans); err != nil {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine processor %s init failed, err: %v", name, err)
delete(processorMap, name)
p.PRReportChan <- RET_INIT_FAIL
return
}
}
if len(processorMap) <= 0 {
logger.ErrorSubf(p.sub, "Workshop.ProcessorRoutine no valid processor")
p.PRReportChan <- RET_INIT_FAIL
return
}
p.PRReportChan <- RET_INIT_SUCCESS
logger.InfoSubf(p.sub, "Workshop.ProcessRoutine success id: %d, count: %d", id, len(processorMap))
exitFlag := false
LOOP:
for {
// 退出条件
if exitFlag && len(p.msgChan) <= 0 {
logger.InfoSubf(p.sub, "Workshop.ProcessRoutine %d th ProcessRoutine is closing", id)
break LOOP
}
select {
case cmd := <-ctrlChannel:
if cmd == CMD_EXIT {
logger.InfoSubf(p.sub, "Workshop.ProcessRoutine %d th ProcessorRoutine receive exit cmd", id)
exitFlag = true
} else if cmd == CMD_TICK {
for _, proc := range processorMap {
proc.Tick()
}
} else {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine %d th ProcessRoutine receive a un-expected cmd: %v",
id, cmd)
}
case msg := <-p.msgChan:
for name, proc := range processorMap {
if err := proc.Process(msg); err != nil {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine %d th ProcessRoutine, %s process fail, err: %v",
id, name, err)
}
}
case <-time.After(time.Second * 1):
// logger.Debug(id, "th ProcessRoutine nothing to do")
} // select
} // for
for _, proc := range processorMap {
proc.Destory()
}
p.PRReportChan <- RET_EXIT_SUCCESS
}
func (p *Workshop) CollectRoutine(id int, ctrlChannel chan int, channel chan job.Item) {
collectorInfos := p.ctx.Get("collector").MustMap()
logger.InfoSubf(p.sub, "Workshop.CollectRoutine begin id: %d, collector: %v", id, collectorInfos)
collectorMap := make(map[string]job.Collector)
for category, name := range collectorInfos {
collectorName, ok := name.(string)
if !ok {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine collector setting invalid: %s => %s", category, name)
p.CLReportChan <- RET_INIT_FAIL
return
}
collectorMap[category] = job.NewCollector(collectorName)
if collectorMap[category] == nil {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine collector %s create failed", collectorName)
p.CLReportChan <- RET_INIT_FAIL
return
}
if err := collectorMap[category].Init(p.ctx, id); err != nil {
logger.ErrorSubf(p.sub, "Workshop.ProcessRoutine collector %s init failed, err: %v", collectorName, err)
delete(collectorMap, category)
p.CLReportChan <- RET_INIT_FAIL
return
}
}
if len(collectorMap) <= 0 {
logger.ErrorSubf(p.sub, "Workshop.CollectRoutine no valid collector")
p.CLReportChan <- RET_INIT_FAIL
return
}
p.CLReportChan <- RET_INIT_SUCCESS
logger.InfoSubf(p.sub, "Workshop.CollectRoutine success id: %d, count: %d", id, len(collectorMap))
exitFlag := false
LOOP:
for {
if exitFlag && len(channel) <= 0 {
logger.InfoSubf(p.sub, "Workshop.CollectRoutine id: %d is closing", id)
break LOOP
}
select {
case cmd := <-ctrlChannel:
if cmd == CMD_EXIT {
logger.InfoSubf(p.sub, "Workshop.CollectRoutine id: %d receive exit cmd", id)
exitFlag = true
} else if cmd == CMD_TICK {
for _, collector := range collectorMap {
collector.Tick()
}
} else {
logger.ErrorSubf(p.sub, "Workshop.CollectRoutine id: %d receive a un-expected cmd: %v",
id, cmd)
}
case processed_item := <-channel:
category := processed_item.Category
if collector, ok := collectorMap[category]; ok {
if err := collector.Collect(processed_item); err != nil {
logger.ErrorSubf(p.sub, "Workshop.CollectRoutine id: %d %s collect fail, err: %v",
id, category, err)
}
} else {
logger.ErrorSubf(p.sub, "Workshop.CollectRoutine id: %d data %s has no proper collector: %v",
id, category, collectorMap)
}
case <-time.After(time.Second * 1):
// logger.Debug(id, "th CollectRoutine nothing to do")
} // select
} // for
for _, collector := range collectorMap {
collector.Destory()
}
p.CLReportChan <- RET_EXIT_SUCCESS
}
func (p *Workshop) worker() {
// 工作goroutine
logger.InfoSubf(p.sub, "WorkShop.worker begin")
exitedProcesser := 0
exitedCollector := 0
for {
select {
// 通过workCtrlChan从控制goroutine获取指令,没有指令的时候就干活
case cmd := <-p.workCtrlChan:
logger.InfoSubf(p.sub, "WorkShop.worker get a cmd: %v", cmd)
if cmd == CMD_EXIT {
logger.InfoSubf(p.sub, "Workshop.worker quit, no msg will push to msgChan, stock will go on")
// 告诉processor关张
// 这一步可能阻塞,所有需要阻塞的工作都交给worker干
// before
// 顺序并阻塞的发送退出信号,太慢了
// after
// 不断try广播,这样可以尽可能使线程早日得到退出信号,加速平滑退出的速度
func() {
p.trySendCtrlInfo(p.PRCtrlChans, cmd)
for {
select {
case <-p.PRReportChan:
exitedProcesser++
logger.InfoSubf(p.sub, "WorkShop.worker receive a exit from processer, total: %d",
exitedProcesser)
if exitedProcesser >= p.processorNum {
return
}
case <-time.After(time.Second * 5):
logger.InfoSubf(p.sub, "WorkShop.worker after some time from close processer, total: %d",
exitedProcesser)
p.trySendCtrlInfo(p.PRCtrlChans, cmd)
}
}
}()
func() {
p.trySendCtrlInfo(p.CLCtrlChans, cmd)
for {
select {
case <-p.CLReportChan:
exitedCollector++
logger.InfoSubf(p.sub, "WorkShop.worker receive a exit from collector, total: %d",
exitedCollector)
if exitedCollector >= p.collectorNum {
p.workReportChan <- RET_EXIT_SUCCESS
return
}
case <-time.After(time.Second * 5):
logger.InfoSubf(p.sub, "WorkShop.worker after some time from close collector, total: %d",
exitedCollector)
p.trySendCtrlInfo(p.CLCtrlChans, cmd)
}
}
}()
return
} else {
logger.WarnSubf(p.sub, "Workshop.worker bad cmd type: %v", cmd)
}
default:
// how many msgs it returns each time depend on max_messsage_fetch_size in etc/qbus-client.conf
messages, err := p.provider.GetNextMsg()
if err != nil {
logger.ErrorSubf(p.sub, "WorkShop.worker GetNextMsg error: %v", err)
// 等一会儿再取消息
time.Sleep(1 * time.Second)
continue
}
if messages == nil || len(messages) <= 0 {
// 如果没有消息需要处理,说明比较闲,就sleep一下
logger.InfoSubf(p.sub, "WorkShop.worker receive nothing from srcProvider")
time.Sleep(5 * time.Second)
continue
}
logger.InfoSubf(p.sub, "WorkShop.worker receive %d msgs from srcProvider", len(messages))
for _, v := range messages {
if len(v) > 0 {
p.msgChan <- string(v)
}
}
logger.InfoSubf(p.sub, "WorkShop.worker send %d msgs successful", len(messages))
p.processedLine += len(messages)
p.provider.Ack()
}
}
}
func (p *Workshop) Run() {
// 分两个goroutine,一个控制,不许阻塞,一个工作可以阻塞
go p.worker()
isWorking := true
// 控制线程是主线程,具有退出的权利
LOOP:
for {
select {
case cmd := <-p.ctrlChan:
if cmd == CMD_EXIT {
if !isWorking {
logger.InfoSubf(p.sub, "Workshop.Run control goroutine is going home, ignore")
continue
}
logger.InfoSubf(p.sub, "Workshop.Run control goroutine tell work goroutine to go home")
isWorking = false
// 由于workCtrlChan有一个空间,所以正常不会堵
// worker接到这个命令后会通知processor关闭,这个动作是可能阻塞的
// 这里要确保所有processor都关闭后,再关闭collector
p.workCtrlChan <- CMD_EXIT
// 从此以后是否不再给processor和collector打tick,抢夺worker向其打exit的机会
// ticker还要,但是不给下游发
// p.ticker_.Stop()
} else {
logger.WarnSubf(p.sub, "Workshop.Run bad cmd type: %v", cmd)
}
case <-p.workReportChan:
logger.InfoSubf(p.sub, "Workshop.Run worker report exit successful, so exit")
break LOOP
case <-p.ticker_.C:
logger.InfoSubf(p.sub, "Workshop.Run tick begin")
// 不许阻塞
if isWorking {
p.trySendCtrlInfo(p.PRCtrlChans, CMD_TICK)
p.trySendCtrlInfo(p.CLCtrlChans, CMD_TICK)
}
p.Tick()
}
}
// all destory
p.provider.Destory()
p.reportChan <- RET_EXIT_SUCCESS
}
var lastProcessedLine = make(map[string]int, 0)
func (p *Workshop) Tick() error {
logger.InfoSubf(p.sub, "Workshop.Tick receive %d(current tick), %d(totally) msgs",
p.processedLine-lastProcessedLine[p.sub], p.processedLine)
lastProcessedLine[p.sub] = p.processedLine
p.ChannelStat()
// p.GC()
return nil
}
func (p *Workshop) ChannelStat() {
logger.InfoSubf(p.sub, "Workshop.ChannelStat len(ctrlChan): %d", len(p.ctrlChan))
logger.InfoSubf(p.sub, "Workshop.ChannelStat len(workCtrlChan): %d", len(p.workCtrlChan))
logger.InfoSubf(p.sub, "Workshop.ChannelStat len(msgChan): %d", len(p.msgChan))
for i, itemChan := range p.itemChans {
logger.InfoSubf(p.sub, "Workshop.ChannelStat index: %d, len(itemChan): %d", i, len(itemChan))
}
}
// func (p *Workshop) GC() {
// runtime.ReadMemStats(&(p.ms))
// alloc := p.ms.Alloc / 1024 / 1024
// logger.Info("memAlloc:", alloc, "M heapAlloc:", p.ms.HeapAlloc/1024/1024, "M, stackAlloc:", p.ms.StackInuse/1024/1024, "M")
// if alloc >= p.memLimit {
// debug.FreeOSMemory()
// runtime.ReadMemStats(&(p.ms))
// alloc = p.ms.Alloc / 1024 / 1024
// logger.Info("after GC memAlloc:", alloc, "M heapAlloc:", p.ms.HeapAlloc/1024/1024, "M, stackAlloc:", p.ms.StackInuse/1024/1024, "M")
// }
// }
func (p *Workshop) initSrcProvider() error {
ctxSrcProvider := p.ctx.Get("src_provider")
if ctxSrcProvider == nil {
return errors.New("no src_provider section")
}
srcType := ctxSrcProvider.Get("src_type").MustString()
p.provider = NewSrcProvider(srcType)
if p.provider == nil {
return errors.New("provider create failed")
}
ctxProviderDetail := ctxSrcProvider.Get(srcType)
if ctxProviderDetail == nil {
return errors.New("no src_provider detail section " + srcType)
}
if err := p.provider.Init(ctxProviderDetail); err != nil {
return err
}
logger.InfoSubf(p.sub, "Workshop.initSrcProvider success, srcType: %s", srcType)
return nil
}
// 会阻塞但保证能发送成功
func (p *Workshop) sendCtrlInfo(channels [](chan int), cmd int) {
logger.InfoSubf(p.sub, "Workshop.sendCtrlInfo begin")
for _, channel := range channels {
channel <- cmd
}
logger.InfoSubf(p.sub, "Workshop.sendCtrlInfo end")
}
// 不会阻塞但不保证能发送成功
func (p *Workshop) trySendCtrlInfo(channels [](chan int), cmd int) {
logger.InfoSubf(p.sub, "Workshop.trySendCtrlInfo begin")
for i, channel := range channels {
select {
case channel <- cmd:
default:
logger.InfoSubf(p.sub, "Workshop.trySendCtrlInfo %d th channel full", i)
}
}
logger.InfoSubf(p.sub, "Workshop.trySendCtrlInfo end")
}
| {
"content_hash": "a2eb0daa38262731b7bc47c5eb4ee995",
"timestamp": "",
"source": "github",
"line_count": 513,
"max_line_length": 137,
"avg_line_length": 30.364522417153996,
"alnum_prop": 0.669833729216152,
"repo_name": "Qihoo360/poseidon",
"id": "31b54f16db7caa6b320885bdb84eff9cbf6a990b",
"size": "16193",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "builder/docformat/src/main/workshop.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "981224"
},
{
"name": "Java",
"bytes": "221754"
},
{
"name": "Makefile",
"bytes": "19153"
},
{
"name": "Protocol Buffer",
"bytes": "53631"
},
{
"name": "Roff",
"bytes": "161725"
},
{
"name": "Shell",
"bytes": "38906"
}
],
"symlink_target": ""
} |
package org.apache.aries.blueprint.plugin.handlers.config;
import org.apache.aries.blueprint.annotation.config.Config;
import org.apache.aries.blueprint.annotation.config.DefaultProperty;
import org.apache.aries.blueprint.plugin.spi.XmlWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
class ConfigWriter implements XmlWriter {
private static final String CONFIG_NS = "http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0";
private Config config;
ConfigWriter(Config config) {
this.config = config;
}
@Override
public void write(XMLStreamWriter writer) throws XMLStreamException {
writer.writeStartElement("property-placeholder");
writer.writeDefaultNamespace(CONFIG_NS);
writer.writeAttribute("persistent-id", config.pid());
if (!"${".equals(config.placeholderPrefix())) {
writer.writeAttribute("placeholder-prefix", config.placeholderPrefix());
}
if (!"}".equals(config.placeholderSuffix())) {
writer.writeAttribute("placeholder-suffix", config.placeholderSuffix());
}
writer.writeAttribute("update-strategy", config.updatePolicy());
DefaultProperty[] defaults = config.defaults();
if (defaults.length > 0) {
writer.writeStartElement("default-properties");
for (DefaultProperty defaultProp : defaults) {
writer.writeEmptyElement("property");
writer.writeAttribute("name", defaultProp.key());
writer.writeAttribute("value", defaultProp.value());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
| {
"content_hash": "53a5301a959996b0dbdbd2570ffe2ba9",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 106,
"avg_line_length": 37.34782608695652,
"alnum_prop": 0.6740395809080326,
"repo_name": "WouterBanckenACA/aries",
"id": "c7ac2e90bf55f5c9ce78cb30689e94784f658999",
"size": "2532",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "blueprint/plugin/blueprint-maven-plugin/src/main/java/org/apache/aries/blueprint/plugin/handlers/config/ConfigWriter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "488"
},
{
"name": "CSS",
"bytes": "32833"
},
{
"name": "Groovy",
"bytes": "4894"
},
{
"name": "HTML",
"bytes": "83923"
},
{
"name": "Java",
"bytes": "10011983"
},
{
"name": "JavaScript",
"bytes": "189672"
},
{
"name": "Roff",
"bytes": "2344"
},
{
"name": "Shell",
"bytes": "4200"
}
],
"symlink_target": ""
} |
use std::result::Result;
use std::error::Error;
use std::io::*;
use std::sync::*;
use serde_json::*;
use gossyp_base::*;
///
/// Tool that prints out text for its parameter to a stream
///
pub struct PrintTool<Stream: Write+Send> {
stream: Mutex<Stream>
}
impl PrintTool<Stdout> {
///
/// Creates a new print tool that writes to stdout
///
pub fn new() -> PrintTool<Stdout> {
PrintTool::<Stdout>::new_with_stream(stdout())
}
}
impl<Stream: Write+Send> PrintTool<Stream> {
///
/// Creates a new print tool that will write to a particular stream
///
pub fn new_with_stream<TStream: Write+Send>(stream: TStream) -> PrintTool<TStream> {
PrintTool { stream: Mutex::new(stream) }
}
}
impl<Stream: Write+Send> Tool for PrintTool<Stream> {
fn invoke_json(&self, input: Value, _environment: &Environment) -> Result<Value, Value> {
// Decide what to print
let print_string = match input {
Value::String(ref s) => {
// If the input is just a string, then we just print that
s.clone()
},
other_value => {
// Other values are formatted as serde_json
to_string_pretty(&other_value).unwrap_or(String::from("<Error>"))
}
};
// Acquire the stream for printing
let mut target = self.stream.lock().unwrap();
// Write out the string as UTF-8
let write_result = target.write(print_string.as_bytes());
if let Err(erm) = write_result {
return Err(json![ {
"error": "Write failed",
"description": erm.description()
} ]);
}
// We flush the stream as we're 'printing' at this point
let flush_result = target.flush();
if let Err(erm) = flush_result {
return Err(json![ {
"error": "Flush failed",
"description": erm.description()
} ]);
}
// We always succeed
Ok(Value::Null)
}
}
| {
"content_hash": "98399d332211b82243750d0ec5d1fb75",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 93,
"avg_line_length": 27.88,
"alnum_prop": 0.5418460066953611,
"repo_name": "Logicalshift/gossyp",
"id": "bc5715e8d180ee4e3daf1a7e46b298efaa297c72",
"size": "2166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gossyp_toolkit/src/io/print.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Rust",
"bytes": "238425"
},
{
"name": "Shell",
"bytes": "103"
}
],
"symlink_target": ""
} |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.callhistory;
import java.util.*;
import net.java.sip.communicator.service.callhistory.*;
import net.java.sip.communicator.service.callhistory.event.*;
import net.java.sip.communicator.service.history.*;
import net.java.sip.communicator.service.history.event.*;
import net.java.sip.communicator.service.history.records.*;
/**
*
* @author Yana Stamcheva
*/
public class CallHistoryQueryImpl
implements CallHistoryQuery
{
private final Collection<CallHistoryQueryListener> queryListeners
= new LinkedList<CallHistoryQueryListener>();
private final Collection<CallRecord> callRecords = new Vector<CallRecord>();
private final HistoryQuery historyQuery;
/**
* Creates an instance of <tt>CallHistoryQueryImpl</tt> by specifying the
* underlying <tt>HistoryQuery</tt>.
* @param query the underlying <tt>HistoryQuery</tt> this query is based on
*/
public CallHistoryQueryImpl(HistoryQuery query)
{
this.historyQuery = query;
historyQuery.addHistoryRecordsListener(new HistoryQueryListener()
{
public void historyRecordReceived(HistoryRecordEvent event)
{
CallRecord callRecord
= CallHistoryServiceImpl.convertHistoryRecordToCallRecord(
event.getHistoryRecord());
callRecords.add(callRecord);
fireQueryEvent(callRecord);
}
public void queryStatusChanged(HistoryQueryStatusEvent event)
{
fireQueryStatusEvent(event.getEventType());
}
});
Iterator<HistoryRecord> historyRecords
= historyQuery.getHistoryRecords().iterator();
while (historyRecords.hasNext())
{
CallRecord callRecord
= CallHistoryServiceImpl.convertHistoryRecordToCallRecord(
historyRecords.next());
callRecords.add(callRecord);
}
}
/**
* Cancels this query.
*/
public void cancel()
{
historyQuery.cancel();
}
/**
* Returns a collection of the results for this query. It's up to
* the implementation to determine how and when to fill this list of
* results.
* <p>
* This method could be used in order to obtain first fast initial
* results and then obtain the additional results through the
* <tt>CallHistoryQueryListener</tt>, which should improve user experience
* when waiting for results.
*
* @return a collection of the initial results for this query
*/
public Collection<CallRecord> getCallRecords()
{
return new Vector<CallRecord>(callRecords);
}
/**
* Adds the given <tt>CallHistoryQueryListener</tt> to the list of
* listeners interested in query result changes.
* @param l the <tt>CallHistoryQueryListener</tt> to add
*/
public void addQueryListener(CallHistoryQueryListener l)
{
synchronized (queryListeners)
{
queryListeners.add(l);
}
}
/**
* Removes the given <tt>CallHistoryQueryListener</tt> from the list of
* listeners interested in query result changes.
* @param l the <tt>CallHistoryQueryListener</tt> to remove
*/
public void removeQueryListener(CallHistoryQueryListener l)
{
synchronized (queryListeners)
{
queryListeners.remove(l);
}
}
/**
* Notifies all registered <tt>HistoryQueryListener</tt>s that a new record
* has been received.
* @param record the <tt>HistoryRecord</tt>
*/
private void fireQueryEvent(CallRecord record)
{
CallRecordEvent event = new CallRecordEvent(this, record);
synchronized (queryListeners)
{
for (CallHistoryQueryListener l : queryListeners)
l.callRecordReceived(event);
}
}
/**
* Notifies all registered <tt>HistoryQueryListener</tt>s that a new record
* has been received.
* @param newStatus the new status
*/
private void fireQueryStatusEvent(int newStatus)
{
CallHistoryQueryStatusEvent event
= new CallHistoryQueryStatusEvent(this, newStatus);
synchronized (queryListeners)
{
for (CallHistoryQueryListener l : queryListeners)
l.queryStatusChanged(event);
}
}
/**
* Returns the query string, this query was created for.
*
* @return the query string, this query was created for
*/
public String getQueryString()
{
return historyQuery.getQueryString();
}
}
| {
"content_hash": "677e26fa2a7093d2411ffe5b81841ab5",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 80,
"avg_line_length": 29.615853658536587,
"alnum_prop": 0.6413423924233066,
"repo_name": "ibauersachs/jitsi",
"id": "0ebeafde335e4c3f62eaff7280b4dd2c18cf5613",
"size": "4857",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/net/java/sip/communicator/impl/callhistory/CallHistoryQueryImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "423671"
},
{
"name": "C++",
"bytes": "464408"
},
{
"name": "CSS",
"bytes": "7555"
},
{
"name": "Groff",
"bytes": "2384"
},
{
"name": "HTML",
"bytes": "5051"
},
{
"name": "Java",
"bytes": "21111446"
},
{
"name": "Makefile",
"bytes": "12348"
},
{
"name": "Mathematica",
"bytes": "21265"
},
{
"name": "Objective-C",
"bytes": "171020"
},
{
"name": "Shell",
"bytes": "13717"
},
{
"name": "Visual Basic",
"bytes": "11032"
},
{
"name": "XSLT",
"bytes": "1814"
}
],
"symlink_target": ""
} |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2012 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
#ifndef OCTREESCENEMANAGER_H
#define OCTREESCENEMANAGER_H
#include "OgreOctreePrerequisites.h"
#include "OgreSceneManager.h"
#include "OgreRenderOperation.h"
#include "OgreSphere.h"
#include <list>
#include <algorithm>
#include "OgreOctree.h"
namespace Ogre
{
class OctreeNode;
class OctreeCamera;
class OctreeIntersectionSceneQuery;
class OctreeRaySceneQuery;
class OctreeSphereSceneQuery;
class OctreeAxisAlignedBoxSceneQuery;
class OctreePlaneBoundedVolumeListSceneQuery;
typedef list< WireBoundingBox * >::type BoxList;
typedef list< unsigned long >::type ColorList;
//typedef list< SceneNode * >::type SceneNodeList;
/** Specialized SceneManager that divides the geometry into an octree in order to facilitate spatial queries.
@remarks
*/
class _OgreOctreePluginExport OctreeSceneManager : public SceneManager
{
friend class OctreeIntersectionSceneQuery;
friend class OctreeRaySceneQuery;
friend class OctreeSphereSceneQuery;
friend class OctreeAxisAlignedBoxSceneQuery;
friend class OctreePlaneBoundedVolumeListSceneQuery;
public:
static int intersect_call;
/** Standard Constructor. Initializes the octree to -10000,-10000,-10000 to 10000,10000,10000 with a depth of 8. */
OctreeSceneManager(const String& name);
/** Standard Constructor */
OctreeSceneManager(const String& name, AxisAlignedBox &box, int max_depth );
/** Standard destructor */
~OctreeSceneManager();
/// @copydoc SceneManager::getTypeName
const String& getTypeName(void) const;
/** Initializes the manager to the given box and depth.
*/
void init( AxisAlignedBox &box, int d );
/** Creates a specialized OctreeNode */
virtual SceneNode * createSceneNodeImpl ( void );
/** Creates a specialized OctreeNode */
virtual SceneNode * createSceneNodeImpl ( const String &name );
/** Creates a specialized OctreeCamera */
virtual Camera * createCamera( const String &name );
/** Deletes a scene node */
virtual void destroySceneNode( const String &name );
/** Does nothing more */
virtual void _updateSceneGraph( Camera * cam );
/** Recurses through the octree determining which nodes are visible. */
virtual void _findVisibleObjects ( Camera * cam,
VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters );
/** Alerts each unculled object, notifying it that it will be drawn.
* Useful for doing calculations only on nodes that will be drawn, prior
* to drawing them...
*/
virtual void _alertVisibleObjects( void );
/** Walks through the octree, adding any visible objects to the render queue.
@remarks
If any octant in the octree if completely within the view frustum,
all subchildren are automatically added with no visibility tests.
*/
void walkOctree( OctreeCamera *, RenderQueue *, Octree *,
VisibleObjectsBoundsInfo* visibleBounds, bool foundvisible,
bool onlyShadowCasters);
/** Checks the given OctreeNode, and determines if it needs to be moved
* to a different octant.
*/
void _updateOctreeNode( OctreeNode * );
/** Removes the given octree node */
void _removeOctreeNode( OctreeNode * );
/** Adds the Octree Node, starting at the given octree, and recursing at max to the specified depth.
*/
void _addOctreeNode( OctreeNode *, Octree *octree, int depth = 0 );
/** Recurses the octree, adding any nodes intersecting with the box into the given list.
It ignores the exclude scene node.
*/
void findNodesIn( const AxisAlignedBox &box, list< SceneNode * >::type &list, SceneNode *exclude = 0 );
/** Recurses the octree, adding any nodes intersecting with the sphere into the given list.
It ignores the exclude scene node.
*/
void findNodesIn( const Sphere &sphere, list< SceneNode * >::type &list, SceneNode *exclude = 0 );
/** Recurses the octree, adding any nodes intersecting with the volume into the given list.
It ignores the exclude scene node.
*/
void findNodesIn( const PlaneBoundedVolume &volume, list< SceneNode * >::type &list, SceneNode *exclude=0 );
/** Recurses the octree, adding any nodes intersecting with the ray into the given list.
It ignores the exclude scene node.
*/
void findNodesIn( const Ray &ray, list< SceneNode * >::type &list, SceneNode *exclude=0 );
/** Sets the box visibility flag */
void setShowBoxes( bool b )
{
mShowBoxes = b;
};
void setLooseOctree( bool b )
{
mLoose = b;
};
/** Resizes the octree to the given size */
void resize( const AxisAlignedBox &box );
/** Sets the given option for the SceneManager
@remarks
Options are:
"Size", AxisAlignedBox *;
"Depth", int *;
"ShowOctree", bool *;
*/
virtual bool setOption( const String &, const void * );
/** Gets the given option for the Scene Manager.
@remarks
See setOption
*/
virtual bool getOption( const String &, void * );
bool getOptionValues( const String & key, StringVector &refValueList );
bool getOptionKeys( StringVector &refKeys );
/** Overridden from SceneManager */
void clearScene(void);
AxisAlignedBoxSceneQuery* createAABBQuery(const AxisAlignedBox& box, unsigned long mask);
SphereSceneQuery* createSphereQuery(const Sphere& sphere, unsigned long mask);
PlaneBoundedVolumeListSceneQuery* createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, unsigned long mask);
RaySceneQuery* createRayQuery(const Ray& ray, unsigned long mask);
IntersectionSceneQuery* createIntersectionQuery(unsigned long mask);
protected:
Octree::NodeList mVisible;
/// The root octree
Octree *mOctree;
/// List of boxes to be rendered
BoxList mBoxes;
/// Number of rendered objs
int mNumObjects;
/// Max depth for the tree
int mMaxDepth;
/// Size of the octree
AxisAlignedBox mBox;
/// Boxes visibility flag
bool mShowBoxes;
bool mLoose;
Real mCorners[ 24 ];
static unsigned long mColors[ 8 ];
static unsigned short mIndexes[ 24 ];
Matrix4 mScaleFactor;
};
/// Factory for OctreeSceneManager
class OctreeSceneManagerFactory : public SceneManagerFactory
{
protected:
void initMetaData(void) const;
public:
OctreeSceneManagerFactory() {}
~OctreeSceneManagerFactory() {}
/// Factory type name
static const String FACTORY_TYPE_NAME;
SceneManager* createInstance(const String& instanceName);
void destroyInstance(SceneManager* instance);
};
}
#endif
| {
"content_hash": "8cd471f3e327d40b20228ab62e811f2c",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 127,
"avg_line_length": 33.24696356275304,
"alnum_prop": 0.6854603019970774,
"repo_name": "Oriense/orsens",
"id": "c24620fb5e9d6da6fd5cecf0e5f061364b9b78ad",
"size": "8559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/OGRE/Plugins/OctreeSceneManager/OgreOctreeSceneManager.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2115739"
},
{
"name": "C++",
"bytes": "29824636"
},
{
"name": "CMake",
"bytes": "4756"
},
{
"name": "Objective-C",
"bytes": "782060"
},
{
"name": "Perl",
"bytes": "2036"
},
{
"name": "TeX",
"bytes": "12428"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CalculateTheSum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CalculateTheSum")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1ab10efb-a9f8-4e70-a2b6-1a0ffdb78dd3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "547269b6d5d3dc3dcf9c81344924fd16",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.97222222222222,
"alnum_prop": 0.7462580185317177,
"repo_name": "Emiliya93/TelerikAcademy",
"id": "b03528e0815a51c91caf59fe4844ca4e1ce47129",
"size": "1406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSharpPart1/Loops/CalculateTheSum/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2183"
},
{
"name": "C",
"bytes": "991"
},
{
"name": "C#",
"bytes": "1313936"
},
{
"name": "CSS",
"bytes": "26060"
},
{
"name": "HTML",
"bytes": "163485"
},
{
"name": "JavaScript",
"bytes": "548828"
},
{
"name": "Python",
"bytes": "168390"
},
{
"name": "Smalltalk",
"bytes": "31868"
},
{
"name": "Visual Basic",
"bytes": "201175"
},
{
"name": "XSLT",
"bytes": "3112"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="https://fonts.googleapis.com/css?family=Orbitron">
<link rel="stylesheet" type="text/css"
href="https://fonts.googleapis.com/css?family=Raleway">
<style>
h1{
font-family: 'Orbitron', serif;
font-size: 30px;
position: auto;
}
body {
font-family: 'Raleway', serif;
font-size: 30px;
position: auto;
}
</style>
<link type="text/css" rel="stylesheet" href="stylesheets/materialize.css" media="screen,projection"/>
<link type="text/css" rel="stylesheet" href="stylesheets/styles.css" media="screen,projection"/>
<title>Pick a Challenge</title>
</head>
<body>
<div class="container">
<h1>Pick a Challenge</h1>
<div class="row">
<form class="col s12">
<div class="row" style="text-align: center">
<a href="gyft-details.html">spelling</a>
</div>
<div class="row" style="text-align: center">
<a href="gyft-details.html">math</a>
</div>
</form>
</div>
</div>
<script src="assets/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="materialize.js"></script>
</body>
</html>
| {
"content_hash": "22dff785c2a2ffc2d62bafacfea4cbe7",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 103,
"avg_line_length": 23.37735849056604,
"alnum_prop": 0.5940274414850686,
"repo_name": "AmandaWouldGo/gamegyft",
"id": "2596d4ba504fa8276cd9a3688ac1c255ea14bd1c",
"size": "1239",
"binary": false,
"copies": "1",
"ref": "refs/heads/design",
"path": "challenge-type.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "156466"
},
{
"name": "HTML",
"bytes": "19775"
},
{
"name": "JavaScript",
"bytes": "299719"
}
],
"symlink_target": ""
} |
EnhancedZipFile
===============
This is a custom zipfile library that supports the zipping of very large files out of memory.
###NB
* I wrote this code specifically to solve [this problem](http://goo.gl/k5ykDP) which I posted on stack-overflow
* The code may not be heavily optimized since I am still a newbie in python. Please help me expand it.
**Thanks**
| {
"content_hash": "f8741b83f141b601f17b9a013e6c0562",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 111,
"avg_line_length": 28,
"alnum_prop": 0.7252747252747253,
"repo_name": "najela/EnhancedZipFile",
"id": "c1406cf1416a78da055953e11df6716f625927d0",
"size": "364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "61403"
}
],
"symlink_target": ""
} |
#ifndef __FSL_MC_CMD_H
#define __FSL_MC_CMD_H
#define MC_CMD_NUM_OF_PARAMS 7
#define MAKE_UMASK64(_width) \
((uint64_t)((_width) < 64 ? ((uint64_t)1 << (_width)) - 1 : -1))
static inline uint64_t mc_enc(int lsoffset, int width, uint64_t val)
{
return (uint64_t)(((uint64_t)val & MAKE_UMASK64(width)) << lsoffset);
}
static inline uint64_t mc_dec(uint64_t val, int lsoffset, int width)
{
return (uint64_t)((val >> lsoffset) & MAKE_UMASK64(width));
}
struct mc_command {
uint64_t header;
uint64_t params[MC_CMD_NUM_OF_PARAMS];
};
struct mc_rsp_create {
__le32 object_id;
};
struct mc_rsp_api_ver {
__le16 major_ver;
__le16 minor_ver;
};
enum mc_cmd_status {
MC_CMD_STATUS_OK = 0x0, /*!< Completed successfully */
MC_CMD_STATUS_READY = 0x1, /*!< Ready to be processed */
MC_CMD_STATUS_AUTH_ERR = 0x3, /*!< Authentication error */
MC_CMD_STATUS_NO_PRIVILEGE = 0x4, /*!< No privilege */
MC_CMD_STATUS_DMA_ERR = 0x5, /*!< DMA or I/O error */
MC_CMD_STATUS_CONFIG_ERR = 0x6, /*!< Configuration error */
MC_CMD_STATUS_TIMEOUT = 0x7, /*!< Operation timed out */
MC_CMD_STATUS_NO_RESOURCE = 0x8, /*!< No resources */
MC_CMD_STATUS_NO_MEMORY = 0x9, /*!< No memory available */
MC_CMD_STATUS_BUSY = 0xA, /*!< Device is busy */
MC_CMD_STATUS_UNSUPPORTED_OP = 0xB, /*!< Unsupported operation */
MC_CMD_STATUS_INVALID_STATE = 0xC /*!< Invalid state */
};
/*
* MC command flags
*/
/* High priority flag */
#define MC_CMD_FLAG_PRI 0x00008000
/* No flags */
#define MC_CMD_NO_FLAGS 0x00000000
/* Command completion flag */
#define MC_CMD_FLAG_INTR_DIS 0x01000000
#define MC_CMD_HDR_CMDID_O 48 /* Command ID field offset */
#define MC_CMD_HDR_CMDID_S 16 /* Command ID field size */
#define MC_CMD_HDR_STATUS_O 16 /* Status field offset */
#define MC_CMD_HDR_TOKEN_O 32 /* Token field offset */
#define MC_CMD_HDR_TOKEN_S 16 /* Token field size */
#define MC_CMD_HDR_STATUS_S 8 /* Status field size*/
#define MC_CMD_HDR_FLAGS_O 0 /* Flags field offset */
#define MC_CMD_HDR_FLAGS_S 32 /* Flags field size*/
#define MC_CMD_HDR_FLAGS_MASK 0x0000FFFF /* Command flags mask */
#define MC_CMD_HDR_READ_STATUS(_hdr) \
((enum mc_cmd_status)mc_dec((_hdr), \
MC_CMD_HDR_STATUS_O, MC_CMD_HDR_STATUS_S))
#define MC_CMD_HDR_READ_TOKEN(_hdr) \
((uint16_t)mc_dec((_hdr), MC_CMD_HDR_TOKEN_O, MC_CMD_HDR_TOKEN_S))
#define MC_PREP_OP(_ext, _param, _offset, _width, _type, _arg) \
((_ext)[_param] |= cpu_to_le64(mc_enc((_offset), (_width), _arg)))
#define MC_EXT_OP(_ext, _param, _offset, _width, _type, _arg) \
(_arg = (_type)mc_dec(cpu_to_le64(_ext[_param]), (_offset), (_width)))
#define MC_CMD_OP(_cmd, _param, _offset, _width, _type, _arg) \
((_cmd).params[_param] |= mc_enc((_offset), (_width), _arg))
#define MC_RSP_OP(_cmd, _param, _offset, _width, _type, _arg) \
(_arg = (_type)mc_dec(_cmd.params[_param], (_offset), (_width)))
/* cmd, param, offset, width, type, arg_name */
#define MC_CMD_READ_OBJ_ID(cmd, obj_id) \
MC_RSP_OP(cmd, 0, 0, 32, uint32_t, obj_id)
/* cmd, param, offset, width, type, arg_name */
#define CMD_DESTROY_SET_OBJ_ID_PARAM0(cmd, object_id) \
MC_CMD_OP(cmd, 0, 0, 32, uint32_t, object_id)
static inline uint64_t mc_encode_cmd_header(uint16_t cmd_id,
uint32_t cmd_flags,
uint16_t token)
{
uint64_t hdr = 0;
hdr = mc_enc(MC_CMD_HDR_CMDID_O, MC_CMD_HDR_CMDID_S, cmd_id);
hdr |= mc_enc(MC_CMD_HDR_FLAGS_O, MC_CMD_HDR_FLAGS_S,
(cmd_flags & MC_CMD_HDR_FLAGS_MASK));
hdr |= mc_enc(MC_CMD_HDR_TOKEN_O, MC_CMD_HDR_TOKEN_S, token);
hdr |= mc_enc(MC_CMD_HDR_STATUS_O, MC_CMD_HDR_STATUS_S,
MC_CMD_STATUS_READY);
return hdr;
}
/**
* mc_write_command - writes a command to a Management Complex (MC) portal
*
* @portal: pointer to an MC portal
* @cmd: pointer to a filled command
*/
static inline void mc_write_command(struct mc_command __iomem *portal,
struct mc_command *cmd)
{
int i;
/* copy command parameters into the portal */
for (i = 0; i < MC_CMD_NUM_OF_PARAMS; i++)
writeq(cmd->params[i], &portal->params[i]);
/* submit the command by writing the header */
writeq(cmd->header, &portal->header);
}
/**
* mc_read_response - reads the response for the last MC command from a
* Management Complex (MC) portal
*
* @portal: pointer to an MC portal
* @resp: pointer to command response buffer
*
* Returns MC_CMD_STATUS_OK on Success; Error code otherwise.
*/
static inline enum mc_cmd_status mc_read_response(
struct mc_command __iomem *portal,
struct mc_command *resp)
{
int i;
enum mc_cmd_status status;
/* Copy command response header from MC portal: */
resp->header = readq(&portal->header);
status = MC_CMD_HDR_READ_STATUS(resp->header);
if (status != MC_CMD_STATUS_OK)
return status;
/* Copy command response data from MC portal: */
for (i = 0; i < MC_CMD_NUM_OF_PARAMS; i++)
resp->params[i] = readq(&portal->params[i]);
return status;
}
/**
* mc_read_version - read version of the given cmd
*
* @cmd: pointer to a filled command
* @major_version: major version value for the given cmd
* @minor_version: minor version value for the given cmd
*/
static inline void mc_cmd_read_api_version(struct mc_command *cmd,
u16 *major_ver,
u16 *minor_ver)
{
struct mc_rsp_api_ver *rsp_params;
rsp_params = (struct mc_rsp_api_ver *)cmd->params;
*major_ver = le16_to_cpu(rsp_params->major_ver);
*minor_ver = le16_to_cpu(rsp_params->minor_ver);
}
#endif /* __FSL_MC_CMD_H */
| {
"content_hash": "ab64e001f40daed8ab5496b5aa2ef700",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 74,
"avg_line_length": 30.48603351955307,
"alnum_prop": 0.6492578339747114,
"repo_name": "guileschool/BEAGLEBONE-tutorials",
"id": "1ec67b549164f4a7a48969d8eb9f004228252891",
"size": "5574",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "BBB-firmware/u-boot-v2018.05-rc2/include/fsl-mc/fsl_mc_cmd.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3031801"
},
{
"name": "Awk",
"bytes": "679"
},
{
"name": "Batchfile",
"bytes": "451009"
},
{
"name": "C",
"bytes": "187049589"
},
{
"name": "C#",
"bytes": "2330"
},
{
"name": "C++",
"bytes": "9495850"
},
{
"name": "CSS",
"bytes": "3499"
},
{
"name": "GDB",
"bytes": "7284"
},
{
"name": "Lex",
"bytes": "27285"
},
{
"name": "Makefile",
"bytes": "1485717"
},
{
"name": "Objective-C",
"bytes": "1073082"
},
{
"name": "Perl",
"bytes": "679475"
},
{
"name": "Prolog",
"bytes": "258849"
},
{
"name": "Python",
"bytes": "1962938"
},
{
"name": "Roff",
"bytes": "24714"
},
{
"name": "Shell",
"bytes": "319726"
},
{
"name": "Tcl",
"bytes": "1934"
},
{
"name": "XSLT",
"bytes": "1335"
},
{
"name": "Yacc",
"bytes": "56953"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="a low-code development platform for creating systems" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>behavior · system </title>
<!-- bootstrap -->
<link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- editor -->
<link href="styles/editor.css" rel="stylesheet" />
<!-- codemirror -->
<link href="lib/codemirror/codemirror.css" rel="stylesheet" />
<link href="lib/codemirror/addon/hint/show-hint.css" rel="stylesheet" />
<link href="lib/codemirror/theme/eclipse.css" rel="stylesheet" />
<!-- cordova -->
<link href="styles/mobile.css" rel="stylesheet" />
</head>
<body>
<!-- menubar -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- menu header -->
<div id="designer-menubar-header" class="navbar-header"></div>
<div>
<!-- menu items -->
<ul id="designer-menubar-items" class="nav navbar-nav"></ul>
<!-- menu actions -->
<ul id="designer-menubar-actions" class="nav navbar-nav navbar-right hidden-xs"></ul>
</div>
</div>
</nav>
<div class="container">
<div class="container-fluid">
<div class="row">
<!-- toolbar -->
<div class="col-sm-3 col-md-2 sidebar">
<!-- toolbar items -->
<ul id="designer-toolbar-items" class="nav nav-sidebar"></ul>
</div>
</div>
</div>
<!-- dialog -->
<div id="designer-dialog"></div>
<!-- message -->
<div id="designer-message"></div>
<!-- editor -->
<div id="designer-editor"></div>
</div>
<!-- cordova -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/mobile.js"></script>
<!-- lib -->
<script src="lib/editor/vendor.js"></script>
<!-- designer -->
<script type="text/javascript" src="scripts/editor-behavior.js"></script>
<script src="//localhost:35729/livereload.js"></script>
</body>
</html> | {
"content_hash": "a7061833ea9c80d98aad1ce9ac8f526a",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 110,
"avg_line_length": 33.53846153846154,
"alnum_prop": 0.6027522935779817,
"repo_name": "system-sdk/system-designer-cordova",
"id": "5f3d8398df9730b750b93a77a0ecd6d57cf9be79",
"size": "2181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/behavior.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "77991"
},
{
"name": "HTML",
"bytes": "21612"
}
],
"symlink_target": ""
} |
layout: model
title: English Bert Embeddings (from smeylan)
author: John Snow Labs
name: bert_embeddings_childes_bert
date: 2022-04-11
tags: [bert, embeddings, en, open_source]
task: Embeddings
language: en
edition: Spark NLP 3.4.2
spark_version: 3.0
supported: true
annotator: BertEmbeddings
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---
## Description
Pretrained Bert Embeddings model, uploaded to Hugging Face, adapted and imported into Spark NLP. `childes-bert` is a English model orginally trained by `smeylan`.
{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/bert_embeddings_childes_bert_en_3.4.2_3.0_1649672895554.zip){:.button.button-orange.button-orange-trans.arr.button-icon}
## How to use
<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = DocumentAssembler() \
.setInputCol("text") \
.setOutputCol("document")
tokenizer = Tokenizer() \
.setInputCols("document") \
.setOutputCol("token")
embeddings = BertEmbeddings.pretrained("bert_embeddings_childes_bert","en") \
.setInputCols(["document", "token"]) \
.setOutputCol("embeddings")
pipeline = Pipeline(stages=[documentAssembler, tokenizer, embeddings])
data = spark.createDataFrame([["I love Spark NLP"]]).toDF("text")
result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new DocumentAssembler()
.setInputCol("text")
.setOutputCol("document")
val tokenizer = new Tokenizer()
.setInputCols(Array("document"))
.setOutputCol("token")
val embeddings = BertEmbeddings.pretrained("bert_embeddings_childes_bert","en")
.setInputCols(Array("document", "token"))
.setOutputCol("embeddings")
val pipeline = new Pipeline().setStages(Array(documentAssembler, tokenizer, embeddings))
val data = Seq("I love Spark NLP").toDF("text")
val result = pipeline.fit(data).transform(data)
```
{:.nlu-block}
```python
import nlu
nlu.load("en.embed.childes_bert").predict("""I love Spark NLP""")
```
</div>
{:.model-param}
## Model Information
{:.table-model}
|---|---|
|Model Name:|bert_embeddings_childes_bert|
|Compatibility:|Spark NLP 3.4.2+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[sentence, token]|
|Output Labels:|[bert]|
|Language:|en|
|Size:|410.0 MB|
|Case sensitive:|true|
## References
- https://huggingface.co/smeylan/childes-bert | {
"content_hash": "c63f1b163994056c8a172f3150e41b1d",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 195,
"avg_line_length": 25.836734693877553,
"alnum_prop": 0.7401263823064771,
"repo_name": "JohnSnowLabs/spark-nlp",
"id": "ad06fc60e33a64f47a1e26f3c5e8768647e07477",
"size": "2536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_posts/luca-martial/2022-04-11-bert_embeddings_childes_bert_en_3_0.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "14452"
},
{
"name": "Java",
"bytes": "223289"
},
{
"name": "Makefile",
"bytes": "819"
},
{
"name": "Python",
"bytes": "1694517"
},
{
"name": "Scala",
"bytes": "4116435"
},
{
"name": "Shell",
"bytes": "5286"
}
],
"symlink_target": ""
} |
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
#include "stm32f1xx.h"
#include "stm32f1xx_it.h"
/* USER CODE BEGIN 0 */
#include "esp8266.h"
#include "control.h"
bool USER_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin);
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;
extern DMA_HandleTypeDef hdma_usart2_rx;
extern DMA_HandleTypeDef hdma_usart2_tx;
extern UART_HandleTypeDef huart2;
/******************************************************************************/
/* Cortex-M3 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN HardFault_IRQn 1 */
/* USER CODE END HardFault_IRQn 1 */
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN MemoryManagement_IRQn 1 */
/* USER CODE END MemoryManagement_IRQn 1 */
}
/**
* @brief This function handles Prefetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN BusFault_IRQn 1 */
/* USER CODE END BusFault_IRQn 1 */
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
}
/* USER CODE BEGIN UsageFault_IRQn 1 */
/* USER CODE END UsageFault_IRQn 1 */
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
HAL_SYSTICK_IRQHandler();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f1xx.s). */
/******************************************************************************/
/**
* @brief This function handles DMA1 channel4 global interrupt.
*/
void DMA1_Channel4_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Channel4_IRQn 0 */
/* USER CODE END DMA1_Channel4_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart1_tx);
/* USER CODE BEGIN DMA1_Channel4_IRQn 1 */
/* USER CODE END DMA1_Channel4_IRQn 1 */
}
/**
* @brief This function handles DMA1 channel5 global interrupt.
*/
void DMA1_Channel5_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Channel5_IRQn 0 */
/* USER CODE END DMA1_Channel5_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart1_rx);
/* USER CODE BEGIN DMA1_Channel5_IRQn 1 */
/* USER CODE END DMA1_Channel5_IRQn 1 */
}
/**
* @brief This function handles DMA1 channel6 global interrupt.
*/
void DMA1_Channel6_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Channel6_IRQn 0 */
/* USER CODE END DMA1_Channel6_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart2_rx);
/* USER CODE BEGIN DMA1_Channel6_IRQn 1 */
/* USER CODE END DMA1_Channel6_IRQn 1 */
}
/**
* @brief This function handles DMA1 channel7 global interrupt.
*/
void DMA1_Channel7_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Channel7_IRQn 0 */
/* USER CODE END DMA1_Channel7_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart2_tx);
/* USER CODE BEGIN DMA1_Channel7_IRQn 1 */
/* USER CODE END DMA1_Channel7_IRQn 1 */
}
/**
* @brief This function handles USART2 global interrupt.
*/
void USART2_IRQHandler(void)
{
/* USER CODE BEGIN USART2_IRQn 0 */
#if 1
if(__HAL_UART_GET_FLAG(&huart2, UART_FLAG_IDLE) && __HAL_UART_GET_IT_SOURCE(&huart2, UART_IT_IDLE))
{
__HAL_UART_CLEAR_IDLEFLAG(&huart2);
ESP8266_RecvCallback(RECV_IDLE);
}
#else
/* USER CODE END USART2_IRQn 0 */
HAL_UART_IRQHandler(&huart2);
/* USER CODE BEGIN USART2_IRQn 1 */
#endif
/* USER CODE END USART2_IRQn 1 */
}
/* USER CODE BEGIN 1 */
void HAL_SYSTICK_Callback(void)
{
static u16 cnt = 0;
static u16 second_cnt = 0;
ESP8266_Task();
INT_Task();
if(++cnt >= 1000/200)
{
cnt = 0;
if(++second_cnt >= 200/2)
{
second_cnt = 0;
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
}
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart == &huart2)
{
ESP8266_RecvCallback(RECV_CPLT);
}
}
void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart)
{
if(huart == &huart2)
{
ESP8266_RecvCallback(RECV_HALF);
}
}
bool USER_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin)
{
/* EXTI line interrupt detected */
if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET)
{
__HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
return true;
}
return false;
}
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"content_hash": "150411556a2805aed496f8dd937c4f37",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 103,
"avg_line_length": 24.027874564459932,
"alnum_prop": 0.5743909512761021,
"repo_name": "JalonWong/Mini-IoT",
"id": "8bc6408f71f6c111b7bad31b300e33903dbf6cdf",
"size": "8837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "HAL/Src/stm32f1xx_it.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "27587"
},
{
"name": "C",
"bytes": "13389936"
},
{
"name": "C++",
"bytes": "3942"
},
{
"name": "HTML",
"bytes": "502"
},
{
"name": "Python",
"bytes": "1908"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d1ab2c3be33a489e76047027e574a5b2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "7359f18b7db7b7f15ec764690d8822a745b024b7",
"size": "205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Serapicamptis/Serapicamptis mutata/ Syn. Paludorchiserapias mutata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Area4\ContableBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Area4\ContableBundle\Entity\EspecificaciondeProducto;
use Area4\ContableBundle\Form\EspecificaciondeProductoType;
/**
* EspecificaciondeProducto controller.
*
* @Route("/especificaciondeproducto")
*/
class EspecificaciondeProductoController extends Controller
{
/**
* Lists all EspecificaciondeProducto entities.
*
* @Route("/", name="especificaciondeproducto")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$entities = $em->getRepository('Area4ContableBundle:EspecificaciondeProducto')->findAll();
return array('entities' => $entities);
}
/**
* Finds and displays a EspecificaciondeProducto entity.
*
* @Route("/{id}/show", name="especificaciondeproducto_show")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('Area4ContableBundle:EspecificaciondeProducto')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EspecificaciondeProducto entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(), );
}
/**
* Displays a form to create a new EspecificaciondeProducto entity.
*
* @Route("/new", name="especificaciondeproducto_new")
* @Template()
*/
public function newAction()
{
$entity = new EspecificaciondeProducto();
$form = $this->createForm(new EspecificaciondeProductoType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
'formName' => $form->getName(),
);
}
/**
* Creates a new EspecificaciondeProducto entity.
*
* @Route("/create", name="especificaciondeproducto_create")
* @Method("post")
* @Template("Area4ContableBundle:EspecificaciondeProducto:new.html.twig")
*/
public function createAction()
{
$entity = new EspecificaciondeProducto();
$request = $this->getRequest();
$form = $this->createForm(new EspecificaciondeProductoType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('especificaciondeproducto'));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Displays a form to edit an existing EspecificaciondeProducto entity.
*
* @Route("/{id}/edit", name="especificaciondeproducto_edit")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('Area4ContableBundle:EspecificaciondeProducto')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EspecificaciondeProducto entity.');
}
$editForm = $this->createForm(new EspecificaciondeProductoType(), $entity);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'formName' => $editForm->getName(),
);
}
/**
* Edits an existing EspecificaciondeProducto entity.
*
* @Route("/{id}/update", name="especificaciondeproducto_update")
* @Method("post")
* @Template("Area4ContableBundle:EspecificaciondeProducto:edit.html.twig")
*/
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('Area4ContableBundle:EspecificaciondeProducto')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EspecificaciondeProducto entity.');
}
$editForm = $this->createForm(new EspecificaciondeProductoType(), $entity);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('especificaciondeproducto'));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a EspecificaciondeProducto entity.
*
* @Route("/{id}/delete", name="especificaciondeproducto_delete")
* @Method("post")
*/
public function deleteAction($id)
{
$form = $this->createDeleteForm($id);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('Area4ContableBundle:EspecificaciondeProducto')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EspecificaciondeProducto entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('especificaciondeproducto'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
| {
"content_hash": "e73b5fe2e6581b4f70a9d00a1231edf1",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 104,
"avg_line_length": 29.846534653465348,
"alnum_prop": 0.5913086747387627,
"repo_name": "ezekielriva/CampeonatoFutbol-Area4",
"id": "33af2c0ab9e272e02bfc106cac328d8092082891",
"size": "6029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Area4/ContableBundle/Controller/EspecificaciondeProductoController.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "859372"
},
{
"name": "PHP",
"bytes": "462819"
},
{
"name": "Perl",
"bytes": "7841"
},
{
"name": "Racket",
"bytes": "2327"
},
{
"name": "Shell",
"bytes": "2036"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<head>
<title>circlepacking</title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<script src='../deps/lib.js'></script>
<script src="../deps/pvisual.v1.min.js"></script>
<style>
.chart, svg{
float: left;
}
</style>
</head>
<body>
<div id="Chart"></div>
<script>
var circlepacking = pvisual.model.circlepacking();
circlepacking.size(800, 800).sizeAvail(750, 750);
circlepacking.json('circlepacking.json', function(d) {
circlepacking.data(d).render('div#Chart');
});
</script>
</body>
</html> | {
"content_hash": "d43d94aeee166f2c0fc9e81b99490372",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 71,
"avg_line_length": 26.304347826086957,
"alnum_prop": 0.6066115702479339,
"repo_name": "linan142857/pvisual",
"id": "4aa0fb7ce3842f98d821c097661a818ad4084786",
"size": "605",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/circlepacking/circlepacking.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2569524"
}
],
"symlink_target": ""
} |
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { jqxNavigationBarComponent } from '../../../../../jqwidgets-ts/angular_jqxnavigationbar';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {
@ViewChild('jqxNavigationBar') jqxNavigationBar: jqxNavigationBarComponent;
ngAfterViewInit() {
this.jqxNavigationBar.focus();
}
} | {
"content_hash": "b09b3a2973a60924a26e40b9777a8e85",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 97,
"avg_line_length": 28.5625,
"alnum_prop": 0.7089715536105032,
"repo_name": "juannelisalde/holter",
"id": "292c9e21c59d78f9dc11d5527e1ddba581a11c1b",
"size": "459",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "assets/jqwidgets/demos/angular/app/navigationbar/keyboardnavigation/app.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1327"
},
{
"name": "Batchfile",
"bytes": "802"
},
{
"name": "C#",
"bytes": "374733"
},
{
"name": "CSS",
"bytes": "882785"
},
{
"name": "HTML",
"bytes": "18898187"
},
{
"name": "Java",
"bytes": "12788"
},
{
"name": "JavaScript",
"bytes": "9712220"
},
{
"name": "PHP",
"bytes": "2051144"
},
{
"name": "TypeScript",
"bytes": "3437214"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mem. New York Bot. Gard. 65:300. 1991
#### Original name
Schrankia floridana Chapman
### Remarks
null | {
"content_hash": "d2e2ab5626ec866b6eecf3e564d7ea59",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 14.615384615384615,
"alnum_prop": 0.7157894736842105,
"repo_name": "mdoering/backbone",
"id": "eabef0dbe4948f26796d9a1b7cea1530b7fe1049",
"size": "266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Mimosa/Mimosa quadrivalvis/Mimosa quadrivalvis floridana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace ncore
{
Semaphore::Semaphore()
: handle_(0)
{
}
Semaphore::~Semaphore()
{
fini();
}
bool Semaphore::init(uint32_t initial, uint32_t max)
{
if(handle_)
return true;
handle_ = CreateSemaphore(0, initial, max, 0);
return handle_ != 0;
}
void Semaphore::fini()
{
if(handle_)
{
::CloseHandle(handle_);
handle_ = 0;
}
}
//'Increase' in Dutch
bool Semaphore::Verhogen(uint32_t release, uint32_t & previous)
{
if(!handle_)
return false;
LPLONG prev = reinterpret_cast<LPLONG>(&previous);
return ::ReleaseSemaphore(handle_, release, prev) != FALSE;
}
//alias for Verhogen
bool Semaphore::Increase(uint32_t release)
{
uint32_t dontcare;
return Verhogen(release, dontcare);
}
bool Semaphore::Wait(uint32_t timeout)
{
return WaitEx(timeout, false);
}
bool Semaphore::WaitEx(uint32_t timeout, bool alertable)
{
return Wait::WaitOne(*this, timeout, alertable);
}
void * Semaphore::WaitableHandle() const
{
return handle_;
}
} | {
"content_hash": "097f18bc8c8ffa48cacfed839d4eaa5a",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 63,
"avg_line_length": 16.83076923076923,
"alnum_prop": 0.6023765996343693,
"repo_name": "shileiyu/ncore",
"id": "a559f9448a1af8f432f4061fba2f8527d916c9d2",
"size": "1137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ncore/sys/semaphore_windows_imp.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1643382"
}
],
"symlink_target": ""
} |
import functools
import json
from contextlib import contextmanager
import pytest
import launch
import launch.cli
import launch.config
import pkgpanda
import ssh
import test_util
from launch.util import get_temp_config_path, stub
from test_util.helpers import Host
@contextmanager
def mocked_context(*args, **kwargs):
""" To be directly patched into an ssh.tunnel invocation to prevent
any real SSH attempt
"""
yield type('Tunnelled', (object,), {})
@pytest.fixture
def mocked_test_runner(monkeypatch):
monkeypatch.setattr(launch.util, 'try_to_output_unbuffered', stub(0))
@pytest.fixture
def mock_ssher(monkeypatch):
monkeypatch.setattr(ssh.ssher, 'open_tunnel', mocked_context)
monkeypatch.setattr(ssh.ssher.Ssher, 'command', stub(b''))
monkeypatch.setattr(ssh.ssher.Ssher, 'get_home_dir', stub(b''))
@pytest.fixture
def ssh_key_path(tmpdir):
ssh_key_path = tmpdir.join('ssh_key')
ssh_key_path.write(launch.util.MOCK_SSH_KEY_DATA)
return str(ssh_key_path)
class MockStack:
def __init__(self):
self.stack_id = launch.util.MOCK_STACK_ID
mock_pub_priv_host = Host('127.0.0.1', '12.34.56')
mock_priv_host = Host('127.0.0.1', None)
@pytest.fixture
def mocked_aws_cf(monkeypatch, mocked_test_runner):
"""Does not include SSH key mocking
"""
monkeypatch.setattr(test_util.aws.DcosCfStack, '__init__', stub(None))
monkeypatch.setattr(
test_util.aws, 'fetch_stack', lambda stack_name, bw: test_util.aws.DcosCfStack(stack_name, bw))
# mock create
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_stack', stub(MockStack()))
# mock wait
monkeypatch.setattr(test_util.aws.CfStack, 'wait_for_complete', stub(None))
# mock describe
monkeypatch.setattr(test_util.aws.DcosCfStack, 'get_master_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.aws.DcosCfStack, 'get_private_agent_ips',
stub([mock_priv_host]))
monkeypatch.setattr(test_util.aws.DcosCfStack, 'get_public_agent_ips',
stub([mock_pub_priv_host]))
# mock delete
monkeypatch.setattr(test_util.aws.DcosCfStack, 'delete', stub(None))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_key_pair', stub(None))
# mock config
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_key_pair', stub(launch.util.MOCK_SSH_KEY_DATA))
@pytest.fixture
def mocked_aws_zen_cf(monkeypatch, mocked_aws_cf):
monkeypatch.setattr(test_util.aws.DcosZenCfStack, '__init__', stub(None))
monkeypatch.setattr(
test_util.aws, 'fetch_stack', lambda stack_name, bw: test_util.aws.DcosZenCfStack(stack_name, bw))
# mock create
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_vpc_tagged', stub(launch.util.MOCK_VPC_ID))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_internet_gateway_tagged', stub(launch.util.MOCK_GATEWAY_ID))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'create_subnet_tagged', stub(launch.util.MOCK_SUBNET_ID))
# mock delete
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_subnet', stub(None))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_vpc', stub(None))
monkeypatch.setattr(test_util.aws.BotoWrapper, 'delete_internet_gateway', stub(None))
# mock describe
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'get_master_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'get_private_agent_ips',
stub([mock_priv_host]))
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'get_public_agent_ips',
stub([mock_pub_priv_host]))
# mock delete
monkeypatch.setattr(test_util.aws.DcosZenCfStack, 'delete', stub(None))
@pytest.fixture
def mocked_azure(monkeypatch, mocked_test_runner):
monkeypatch.setattr(test_util.azure.ServicePrincipalCredentials, '__init__', stub(None))
monkeypatch.setattr(test_util.azure.ResourceManagementClient, '__init__', stub(None))
monkeypatch.setattr(test_util.azure.NetworkManagementClient, '__init__', stub(None))
monkeypatch.setattr(test_util.azure.AzureWrapper, 'deploy_template_to_new_resource_group', stub(None))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'wait_for_deployment', stub(None))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'delete', stub(None))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'get_master_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'get_private_agent_ips',
stub([mock_priv_host]))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'get_public_agent_ips',
stub([mock_pub_priv_host]))
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'public_agent_lb_fqdn', 'abc-foo-bar')
monkeypatch.setattr(test_util.azure.DcosAzureResourceGroup, 'public_master_lb_fqdn', 'dead-beef')
class MockInstaller(test_util.onprem.DcosInstallerApiSession):
"""Simple object to make sure the installer API is invoked
in the correct order
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.genconf_called = False
self.preflight_called = False
self.deploy_called = False
def genconf(self, config):
self.genconf_called = True
def preflight(self):
assert self.genconf_called is True
self.preflight_called = True
def deploy(self):
assert self.genconf_called is True
assert self.preflight_called is True
self.deploy_called = True
def postflight(self):
assert self.genconf_called is True
assert self.preflight_called is True
assert self.deploy_called is True
@pytest.fixture
def mock_bare_cluster_hosts(monkeypatch, mocked_aws_cf, mock_ssher):
monkeypatch.setattr(test_util.aws.BareClusterCfStack, '__init__', stub(None))
monkeypatch.setattr(test_util.aws.BareClusterCfStack, 'delete', stub(None))
monkeypatch.setattr(test_util.aws.BareClusterCfStack, 'get_host_ips', stub([mock_pub_priv_host] * 4))
monkeypatch.setattr(
test_util.aws, 'fetch_stack', lambda stack_name, bw: test_util.aws.BareClusterCfStack(stack_name, bw))
monkeypatch.setattr(test_util.onprem.OnpremCluster, 'setup_installer_server', stub(None))
monkeypatch.setattr(test_util.onprem.OnpremCluster, 'start_bootstrap_zk', stub(None))
monkeypatch.setattr(test_util.onprem, 'DcosInstallerApiSession', MockInstaller)
monkeypatch.setattr(launch.onprem.OnpremLauncher, 'get_last_state', stub(None))
@pytest.fixture
def aws_cf_config_path(tmpdir, ssh_key_path, mocked_aws_cf):
return get_temp_config_path(tmpdir, 'aws-cf.yaml', update={'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def aws_cf_with_helper_config_path(tmpdir, mocked_aws_cf):
return get_temp_config_path(tmpdir, 'aws-cf-with-helper.yaml')
@pytest.fixture
def aws_zen_cf_config_path(tmpdir, ssh_key_path, mocked_aws_zen_cf):
return get_temp_config_path(tmpdir, 'aws-zen-cf.yaml')
@pytest.fixture
def aws_cf_no_pytest_config_path(tmpdir, mocked_aws_cf):
return get_temp_config_path(tmpdir, 'aws-cf-no-pytest.yaml')
@pytest.fixture
def azure_config_path(tmpdir, mocked_azure, ssh_key_path):
return get_temp_config_path(tmpdir, 'azure.yaml', update={'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def azure_with_helper_config_path(tmpdir, mocked_azure):
return get_temp_config_path(tmpdir, 'azure-with-helper.yaml')
@pytest.fixture
def aws_onprem_config_path(tmpdir, ssh_key_path, mock_bare_cluster_hosts):
return get_temp_config_path(tmpdir, 'aws-onprem.yaml', update={
'ssh_private_key_filename': ssh_key_path})
@pytest.fixture
def aws_onprem_with_helper_config_path(tmpdir, mock_bare_cluster_hosts):
return get_temp_config_path(tmpdir, 'aws-onprem-with-helper.yaml')
def check_cli(cmd):
assert launch.cli.main(cmd) == 0, 'Command failed! {}'.format(' '.join(cmd))
def check_success(capsys, tmpdir, config_path):
"""
Runs through the required functions of a launcher and then
runs through the default usage of the script for a
given config path and info path, ensuring each step passes
if all steps finished successfully, this parses and returns the generated
info JSON and stdout description JSON for more specific checks
"""
# Test launcher directly first
config = launch.config.get_validated_config(config_path)
launcher = launch.get_launcher(config)
info = launcher.create()
# Grab the launcher again with the output from create
launcher = launch.get_launcher(info)
launcher.wait()
launcher.describe()
launcher.test([], {})
launcher.delete()
info_path = str(tmpdir.join('my_specific_info.json')) # test non-default name
# Now check launcher via CLI
check_cli(['create', '--config-path={}'.format(config_path), '--info-path={}'.format(info_path)])
# use the info written to disk to ensure JSON parsable
info = pkgpanda.util.load_json(info_path)
check_cli(['wait', '--info-path={}'.format(info_path)])
# clear stdout capture
capsys.readouterr()
check_cli(['describe', '--info-path={}'.format(info_path)])
# capture stdout from describe and ensure JSON parse-able
description = json.loads(capsys.readouterr()[0])
# general assertions about description
assert 'masters' in description
assert 'private_agents' in description
assert 'public_agents' in description
check_cli(['pytest', '--info-path={}'.format(info_path)])
check_cli(['delete', '--info-path={}'.format(info_path)])
return info, description
@pytest.fixture
def check_cli_success(capsys, tmpdir):
return functools.partial(check_success, capsys, tmpdir)
| {
"content_hash": "a298e7e87f02cbce2129a8bbf851e314",
"timestamp": "",
"source": "github",
"line_count": 255,
"max_line_length": 119,
"avg_line_length": 38.984313725490196,
"alnum_prop": 0.7017402675787144,
"repo_name": "jeid64/dcos",
"id": "4e3dc9b9f2159cfb0f898fae16939b9e32b4fbf5",
"size": "9941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/dcos-launch/extra/conftest.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2529"
},
{
"name": "Groovy",
"bytes": "528"
},
{
"name": "HTML",
"bytes": "77042"
},
{
"name": "Lua",
"bytes": "137993"
},
{
"name": "Makefile",
"bytes": "179"
},
{
"name": "Python",
"bytes": "1302387"
},
{
"name": "Shell",
"bytes": "67998"
}
],
"symlink_target": ""
} |
// Copyright (c) kuicker.org. All rights reserved.
// Modified By YYYY-MM-DD
// kevinjong 2016-02-11 - Creation
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace IsTo.Tests
{
public class ToOfTypeToArray
{
[Fact]
public void BySelf()
{
var value = new Int32[] { 1, 2 };
var result = (Int32[])value.To(typeof(Int32[]));
Assert.True(result.SequenceEqual(value));
}
[Theory]
[InlineData("abc def 1234")]
[InlineData(true)]
[InlineData(false)]
[InlineData('A')]
[InlineData(123)]
[InlineData(123U)]
[InlineData(123L)]
[InlineData(123UL)]
[InlineData(123F)]
[InlineData(123D)]
[InlineData(Animal.Cat)]
public void ByPrimative<T>(T value)
{
var values = new T[] { value };
var expect = (T[])value.To(typeof(T[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByStream()
{
var value = "123123";
var value1 = new MemoryStream(
Encoding.UTF8.GetBytes(value)
);
var value2 = new MemoryStream(
Encoding.UTF8.GetBytes(value)
);
var values = new MemoryStream[] { value1 };
var expect = (MemoryStream[])value2.To(typeof(MemoryStream[]));
TestHelper.StreamComparison(values[0], expect[0]);
}
[Fact]
public void ByColor()
{
var value = Color.Beige;
var values = new Color[] { value };
var expect = (Color[])value.To(typeof(Color[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByDateTime()
{
var value = DateTime.Now;
var values = new DateTime[] { value };
var expect = (DateTime[])value.To(typeof(DateTime[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByDecimal()
{
var value = (Decimal)123.456;
var values = new Decimal[] { value };
var expect = (Decimal[])value.To(typeof(Decimal[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByByte()
{
var value = (Byte)123;
var values = new Byte[] { value };
var expect = (Byte[])value.To(typeof(Byte[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void BySByte()
{
var value = (SByte)123;
var values = new SByte[] { value };
var expect = (SByte[])value.To(typeof(SByte[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByInt16()
{
var value = (Int16)123;
var values = new Int16[] { value };
var expect = (Int16[])value.To(typeof(Int16[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByUInt16()
{
var value = (UInt16)123;
var values = new UInt16[] { value };
var expect = (UInt16[])value.To(typeof(UInt16[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByTest11()
{
var value = new Test11();
var values = new Test11[] { value };
var expect = (Test11[])value.To(typeof(Test11[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByTest12()
{
var value = new Test12();
var values = new Test12[] { value };
var expect = (Test12[])value.To(typeof(Test12[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByTest13()
{
var value = new Test13();
var values = new Test13[] { value };
var expect = (Test13[])value.To(typeof(Test13[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByTest21()
{
var value = new Test21<string>();
var values = new Test21<string>[] { value };
var expect = (Test21<string>[])value.To(typeof(Test21<string>[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByTest22()
{
var value = new Test22<string, int>();
var values = new Test22<string, int>[] { value };
var expect = (Test22<string, int>[])value.To(typeof(Test22<string, int>[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByTest23()
{
var value = new Test23<string, int>();
var values = new Test23<string, int>[] { value };
var expect = (Test23<string, int>[])value.To(typeof(Test23<string, int>[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByEnumToArrayOfInteger()
{
var value = Animal.Dog;
var values = new int[] { (int)value };
var expect = (int[])value.To(typeof(int[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByEnumToArrayOfString()
{
var value = Animal.Dog;
var values = new string[] { value.ToString() };
var expect = (string[])value.To(typeof(string[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByIntegerToArrayOfByte()
{
byte value = 111;
var values = new byte[] { value };
var expect = (Byte[])value.To(typeof(Byte[]));
Assert.True(values.SequenceEqual(expect));
}
[Fact]
public void ByArrayOfEnumToArrayOfString()
{
var result = (string[])new[] { Animal.Bird, Animal.Cat }
.To(typeof(string[]));
var expect = new string[] {
Animal.Bird.ToString(),
Animal.Cat.ToString()
};
Assert.True(result.SequenceEqual(expect));
}
[Fact]
public void ByArrayOfEnumToArrayOfInteger()
{
var result = (int[])new[] { Animal.Bird, Animal.Cat }
.To(typeof(int[]));
var expect = new int[] {
(int)Animal.Bird,
(int)Animal.Cat
};
Assert.True(result.SequenceEqual(expect));
}
[Fact]
public void ByArrayOfEnumToArrayOfEnum()
{
var result = (Animal[])new[] {
Animal.Bird,
Animal.Cat
}.To(typeof(Animal[]));
var expect = new Animal[] {
Animal.Bird,
Animal.Cat
};
Assert.True(result.SequenceEqual(expect));
}
[Fact]
public void ByArrayOfStringToArrayOfEnum()
{
var result = (Animal[])new[] { "Bird", "Cat" }
.To(typeof(Animal[]));
var expect = new Animal[] {
Animal.Bird,
Animal.Cat
};
Assert.True(result.SequenceEqual(expect));
}
[Fact]
public void ByArrayOfIntegerToArrayOfEnum()
{
var result = (Animal[])new[] { 0, 1 }
.To(typeof(Animal[]));
var expect = new Animal[] {
Animal.Bird,
Animal.Cat
};
Assert.True(result.SequenceEqual(expect));
}
//[Theory]
//[InlineData(true, false, true)]
//[InlineData(100, 101, true)]
//[InlineData(100.1, 101.1, false)]
//[InlineData(100, 300, false)]
//[InlineData(100, 300.1, false)]
//[InlineData("100", "101", true)]
//[InlineData("1001.", "101.1", false)]
//[InlineData("100", "300", false)]
//[InlineData("100.1", "300.1", false)]
//[InlineData("A", "B", false)]
//[InlineData('A', 'B', true)]
//[InlineData('1', '2', true)]
//[InlineData(100U, 101U, true)]
//[InlineData(100U, 300U, false)]
//[InlineData(100L, 101L, true)]
//[InlineData(100UL, 300UL, false)]
//[InlineData(100F, 101F, true)]
//[InlineData(100D, 300D, false)]
//public void ByArrayToArrayOfByte<T>(
// T value1,
// T value2,
// bool expect)
//{
// byte[] result;
// Assert.True(
// new[] { value1, value2 }.TryTo(out result)
// ==
// expect
// );
//}
[Fact]
public void ByArrayToArrayOfClass()
{
var classA = new Test22<string, int>() {
Property11 = 1,
Property21 = 3,
Property12 = 5,
Property22 = 7
};
var classB = new Test22<string, int>() {
Property11 = 2,
Property21 = 4,
Property12 = 6,
Property22 = 8
};
var result = (Test11[])new[] { classA, classB }.To(typeof(Test11[]));
var expect = new[] {
new Test11(){Property11 = 1},
new Test11(){Property11 = 2}
};
Assert.True(expect.SequenceEqual(result));
}
[Fact]
public void ByDictionary()
{
// Not support yet!
//var value = new Dictionary<string, Animal>();
//value.Add("Bird", Animal.Bird);
//value.Add("Cat", Animal.Cat);
//var result = value.To<Dictionary<Animal, string>>();
//var expect = new Dictionary<Animal, string>();
//expect.Add(Animal.Bird, "Bird");
//expect.Add(Animal.Cat, "Cat");
//Assert.True(result.SequenceEqual(expect));
}
}
}
| {
"content_hash": "7175d5487aa3edf11444762d31a76a77",
"timestamp": "",
"source": "github",
"line_count": 352,
"max_line_length": 79,
"avg_line_length": 23.74715909090909,
"alnum_prop": 0.590261993061371,
"repo_name": "Kuick/IsTo",
"id": "c104a37957cef87c73a63c5a74890044e2eefe4c",
"size": "8361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IsTo.Tests/To/ToOfTypeToArray.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "336982"
}
],
"symlink_target": ""
} |
import BaseHTTPServer
import json
import service_func
class service_handler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def do_GET(self):
data = None
uri_splitted = self.path.split('?')
path = uri_splitted[0]
args = {}
print "Serving request : %s:%d, URI : %s" % (self.client_address[0], self.client_address[1], self.path)
if len(uri_splitted) > 1:
url_args = uri_splitted[1].split('&')
for a in url_args:
a_data = a.split('=')
a_name = a_data[0]
a_value = None
if len(a_data) > 1:
a_value = a_data[1]
args[a_name] = a_value
for f in self.server.functions:
if path == f.func_path:
try:
f.init()
f.execute(args, self.server)
data = f.answer()
except KeyError:
data = {"error": "Missing argument"}
except service_func.func_error as f_e:
data = {"func_error": str(f_e)}
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
if data is not None:
self.wfile.write(json.dumps(data))
else:
data = {"error": "Unknown function"}
self.wfile.write(json.dumps(data)) | {
"content_hash": "f8728579aca1c68ca8565214873f9f3f",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 111,
"avg_line_length": 32.54,
"alnum_prop": 0.51259987707437,
"repo_name": "jordsti/hacker-jeopardy",
"id": "0b39b0210cf5007a3d0276b5b06c50a1ce786430",
"size": "1627",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webservice/handler.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49"
},
{
"name": "HTML",
"bytes": "2441"
},
{
"name": "JavaScript",
"bytes": "7658"
},
{
"name": "Python",
"bytes": "29104"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Craterostigma latibracteatum Skan
### Remarks
null | {
"content_hash": "e83125d13f83a319e143292fa035b4f5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 33,
"avg_line_length": 11.923076923076923,
"alnum_prop": 0.7483870967741936,
"repo_name": "mdoering/backbone",
"id": "48b685d5099d71a29cd2c926a82101e15e3d040a",
"size": "226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Crepidorhopalon/Crepidorhopalon latibracteatus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (1.8.0_45) on Thu Nov 12 15:33:43 BRST 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ET</title>
<meta name="date" content="2015-11-12">
<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="ET";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ET.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-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 Class</li>
<li><a href="../../../../br/ufscar/cgm/preenchimento/No.html" title="class in br.ufscar.cgm.preenchimento"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?br/ufscar/cgm/preenchimento/ET.html" target="_top">Frames</a></li>
<li><a href="ET.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">br.ufscar.cgm.preenchimento</div>
<h2 title="Class ET" class="title">Class ET</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>br.ufscar.cgm.preenchimento.ET</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">ET</span>
extends java.lang.Object</pre>
<div class="block">Classe que representa a estrutura da tabela de arestas e que também possui a
lógica para adicionar e exibir nós. <br><br></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../br/ufscar/cgm/preenchimento/ET.html#ET-int-">ET</a></span>(int alturaTela)</code>
<div class="block">Inicializa uma estrutura de nós com no máximo de entradas igual à altura
da tela</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/ufscar/cgm/preenchimento/ET.html#adicionaNo-br.ufscar.cgm.preenchimento.No-int-">adicionaNo</a></span>(<a href="../../../../br/ufscar/cgm/preenchimento/No.html" title="class in br.ufscar.cgm.preenchimento">No</a> nocriado,
int posicao)</code>
<div class="block">Adiciona um novo nó na linha especificada.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/ufscar/cgm/preenchimento/ET.html#exibe--">exibe</a></span>()</code>
<div class="block">Rotina responsável por mostrar uma visualização da ET no output para Debug.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../br/ufscar/cgm/preenchimento/No.html" title="class in br.ufscar.cgm.preenchimento">No</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/ufscar/cgm/preenchimento/ET.html#getNivel-int-">getNivel</a></span>(int i)</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/ufscar/cgm/preenchimento/ET.html#getTamanho--">getTamanho</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/ufscar/cgm/preenchimento/ET.html#isNivelVazio-int-">isNivelVazio</a></span>(int i)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ET-int-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ET</h4>
<pre>public ET(int alturaTela)</pre>
<div class="block">Inicializa uma estrutura de nós com no máximo de entradas igual à altura
da tela</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>alturaTela</code> - altura da tela.</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="adicionaNo-br.ufscar.cgm.preenchimento.No-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>adicionaNo</h4>
<pre>public void adicionaNo(<a href="../../../../br/ufscar/cgm/preenchimento/No.html" title="class in br.ufscar.cgm.preenchimento">No</a> nocriado,
int posicao)</pre>
<div class="block">Adiciona um novo nó na linha especificada.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>nocriado</code> - Novo nó.</dd>
<dd><code>posicao</code> - linha.</dd>
</dl>
</li>
</ul>
<a name="getNivel-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getNivel</h4>
<pre>public <a href="../../../../br/ufscar/cgm/preenchimento/No.html" title="class in br.ufscar.cgm.preenchimento">No</a> getNivel(int i)</pre>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>i</code> - linha.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Primeiro nó da linha.</dd>
</dl>
</li>
</ul>
<a name="isNivelVazio-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isNivelVazio</h4>
<pre>public boolean isNivelVazio(int i)</pre>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>i</code> - linha a ser verificada.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Se linha não contém entradas na tabela.</dd>
</dl>
</li>
</ul>
<a name="getTamanho--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTamanho</h4>
<pre>public int getTamanho()</pre>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>A quantidade de posições em ET.</dd>
</dl>
</li>
</ul>
<a name="exibe--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>exibe</h4>
<pre>public void exibe()</pre>
<div class="block">Rotina responsável por mostrar uma visualização da ET no output para Debug.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ET.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-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 Class</li>
<li><a href="../../../../br/ufscar/cgm/preenchimento/No.html" title="class in br.ufscar.cgm.preenchimento"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?br/ufscar/cgm/preenchimento/ET.html" target="_top">Frames</a></li>
<li><a href="ET.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "32506c00226912ab4495e0052d139511",
"timestamp": "",
"source": "github",
"line_count": 364,
"max_line_length": 391,
"avg_line_length": 35.41208791208791,
"alnum_prop": 0.617377812257564,
"repo_name": "lucasdavid/CG-Assignment-1",
"id": "c11912e2c2470f519177c2fdab17af2d0b7b33eb",
"size": "12936",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "projects/cgm-2015-2-camilo-breno-jp/javadoc/br/ufscar/cgm/preenchimento/ET.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "294753"
}
],
"symlink_target": ""
} |
A simple combat manager for the Supers! rpg written for the Commodore 64 using CC65
| {
"content_hash": "80b48875e0e9a0b11c2d9ca2ee4667b6",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 83,
"avg_line_length": 84,
"alnum_prop": 0.8095238095238095,
"repo_name": "hculpan/supers-combat-manager",
"id": "2461702a67e4383885a840200b747d910deeb55b",
"size": "108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "55"
},
{
"name": "C",
"bytes": "710"
},
{
"name": "Shell",
"bytes": "832"
}
],
"symlink_target": ""
} |
import {OnlinePlayerMetadata} from "../../io/OnlinePlayerMetadata";
import {ResourcePath, ResourcePathUtil} from "../../io/ResourcePath";
import {ResourceSubscriberTabModel} from "../ResourceSubscriberTabModel";
import {TabController} from "../TabController";
import {UserManagementTabController} from "./UserManagementTabController";
import {UserManagementTabState} from "./UserManagementTabState";
export class UserManagementTabModel extends ResourceSubscriberTabModel<UserManagementTabState> {
public getName(): string {
return "Users";
}
public getSubscribedResourcePaths(): ResourcePath[] {
return [
["onlinePlayers"],
["blacklist"],
["whitelist"],
];
}
public getDefaultState(): UserManagementTabState {
return {onlinePlayers: [], blacklist: [], whitelist: [], dialogUpdater: () => null};
}
public initController(): TabController<UserManagementTabState> {
return new UserManagementTabController();
}
public onResourceUpdated(resourcePath: ResourcePath, data: any): void {
if (ResourcePathUtil.equals(resourcePath, ["onlinePlayers"])) {
this.update({onlinePlayers: data as OnlinePlayerMetadata[]});
} else if (ResourcePathUtil.equals(resourcePath, ["blacklist"])) {
this.update({blacklist: data as string[]});
} else if (ResourcePathUtil.equals(resourcePath, ["whitelist"])) {
this.update({whitelist: data as string[]});
}
this.getState().dialogUpdater(this.getState().whitelist, this.getState().blacklist);
}
}
| {
"content_hash": "098cdb7ccf57a153f96fb7c159597dc8",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 96,
"avg_line_length": 37.073170731707314,
"alnum_prop": 0.7171052631578947,
"repo_name": "gianluca-nitti/FacadeServer-frontend",
"id": "b3d8c8dca1201560e188fcd8e1884e8c179e1d81",
"size": "1520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/tabs/userManagement/UserManagementTabModel.tsx",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "469"
},
{
"name": "Java",
"bytes": "1487"
},
{
"name": "JavaScript",
"bytes": "9483"
},
{
"name": "Objective-C",
"bytes": "4429"
},
{
"name": "Python",
"bytes": "1746"
},
{
"name": "TypeScript",
"bytes": "93980"
}
],
"symlink_target": ""
} |
Official releases are built in Docker containers. Details are [here](../../build/README.md). You can do simple builds and development with just a local Docker installation. If want to build go locally outside of docker, please continue below.
## Go development environment
Kubernetes is written in [Go](http://golang.org) programming language. If you haven't set up Go development environment, please follow [this instruction](http://golang.org/doc/code.html) to install go tool and set up GOPATH. Ensure your version of Go is at least 1.3.
## Clone kubernetes into GOPATH
We highly recommend to put kubernetes' code into your GOPATH. For example, the following commands will download kubernetes' code under the current user's GOPATH (Assuming there's only one directory in GOPATH.):
```
$ echo $GOPATH
/home/user/goproj
$ mkdir -p $GOPATH/src/github.com/GoogleCloudPlatform/
$ cd $GOPATH/src/github.com/GoogleCloudPlatform/
$ git clone https://github.com/GoogleCloudPlatform/kubernetes.git
```
The commands above will not work if there are more than one directory in ``$GOPATH``.
If you plan to do development, read about the
[Kubernetes Github Flow](https://docs.google.com/presentation/d/1HVxKSnvlc2WJJq8b9KCYtact5ZRrzDzkWgKEfm0QO_o/pub?start=false&loop=false&delayms=3000),
and then clone your own fork of Kubernetes as described there.
## godep and dependency management
Kubernetes uses [godep](https://github.com/tools/godep) to manage dependencies. It is not strictly required for building Kubernetes but it is required when managing dependencies under the Godeps/ tree, and is required by a number of the build and test scripts. Please make sure that ``godep`` is installed and in your ``$PATH``.
### Installing godep
There are many ways to build and host go binaries. Here is an easy way to get utilities like ```godep``` installed:
1) Ensure that [mercurial](http://mercurial.selenic.com/wiki/Download) is installed on your system. (some of godep's dependencies use the mercurial
source control system). Use ```apt-get install mercurial``` or ```yum install mercurial``` on Linux, or [brew.sh](http://brew.sh) on OS X, or download
directly from mercurial.
2) Create a new GOPATH for your tools and install godep:
```
export GOPATH=$HOME/go-tools
mkdir -p $GOPATH
go get github.com/tools/godep
```
3) Add $GOPATH/bin to your path. Typically you'd add this to your ~/.profile:
```
export GOPATH=$HOME/go-tools
export PATH=$PATH:$GOPATH/bin
```
### Using godep
Here's a quick walkthrough of one way to use godeps to add or update a Kubernetes dependency into Godeps/_workspace. For more details, please see the instructions in [godep's documentation](https://github.com/tools/godep).
1) Devote a directory to this endeavor:
```
export KPATH=$HOME/code/kubernetes
mkdir -p $KPATH/src/github.com/GoogleCloudPlatform/kubernetes
cd $KPATH/src/github.com/GoogleCloudPlatform/kubernetes
git clone https://path/to/your/fork .
# Or copy your existing local repo here. IMPORTANT: making a symlink doesn't work.
```
2) Set up your GOPATH.
```
# Option A: this will let your builds see packages that exist elsewhere on your system.
export GOPATH=$KPATH:$GOPATH
# Option B: This will *not* let your local builds see packages that exist elsewhere on your system.
export GOPATH=$KPATH
# Option B is recommended if you're going to mess with the dependencies.
```
3) Populate your new GOPATH.
```
cd $KPATH/src/github.com/GoogleCloudPlatform/kubernetes
godep restore
```
4) Next, you can either add a new dependency or update an existing one.
```
# To add a new dependency, do:
cd $KPATH/src/github.com/GoogleCloudPlatform/kubernetes
go get path/to/dependency
# Change code in Kubernetes to use the dependency.
godep save ./...
# To update an existing dependency, do:
cd $KPATH/src/github.com/GoogleCloudPlatform/kubernetes
go get -u path/to/dependency
# Change code in Kubernetes accordingly if necessary.
godep update path/to/dependency
```
5) Before sending your PR, it's a good idea to sanity check that your Godeps.json file is ok by re-restoring: ```godep restore```
It is sometimes expedient to manually fix the /Godeps/godeps.json file to minimize the changes.
Please send dependency updates in separate commits within your PR, for easier reviewing.
## Hooks
Before committing any changes, please link/copy these hooks into your .git
directory. This will keep you from accidentally committing non-gofmt'd go code.
```
cd kubernetes/.git/hooks/
ln -s ../../hooks/pre-commit .
```
## Unit tests
```
cd kubernetes
hack/test-go.sh
```
Alternatively, you could also run:
```
cd kubernetes
godep go test ./...
```
If you only want to run unit tests in one package, you could run ``godep go test`` under the package directory. For example, the following commands will run all unit tests in package kubelet:
```
$ cd kubernetes # step into kubernetes' directory.
$ cd pkg/kubelet
$ godep go test
# some output from unit tests
PASS
ok github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet 0.317s
```
## Coverage
Currently, collecting coverage is only supported for the Go unit tests.
To run all unit tests and generate an HTML coverage report, run the following:
```
cd kubernetes
KUBE_COVER=y hack/test-go.sh
```
At the end of the run, an the HTML report will be generated with the path printed to stdout.
To run tests and collect coverage in only one package, pass its relative path under the `kubernetes` directory as an argument, for example:
```
cd kubernetes
KUBE_COVER=y hack/test-go.sh pkg/kubectl
```
Multiple arguments can be passed, in which case the coverage results will be combined for all tests run.
Coverage results for the project can also be viewed on [Coveralls](https://coveralls.io/r/GoogleCloudPlatform/kubernetes), and are continuously updated as commits are merged. Additionally, all pull requests which spawn a Travis build will report unit test coverage results to Coveralls.
## Integration tests
You need an [etcd](https://github.com/coreos/etcd/releases/tag/v2.0.0) in your path, please make sure it is installed and in your ``$PATH``.
```
cd kubernetes
hack/test-integration.sh
```
## End-to-End tests
You can run an end-to-end test which will bring up a master and two minions, perform some tests, and then tear everything down. Make sure you have followed the getting started steps for your chosen cloud platform (which might involve changing the `KUBERNETES_PROVIDER` environment variable to something other than "gce".
```
cd kubernetes
hack/e2e-test.sh
```
Pressing control-C should result in an orderly shutdown but if something goes wrong and you still have some VMs running you can force a cleanup with this command:
```
go run hack/e2e.go --down
```
### Flag options
See the flag definitions in `hack/e2e.go` for more options, such as reusing an existing cluster, here is an overview:
```sh
# Build binaries for testing
go run hack/e2e.go --build
# Create a fresh cluster. Deletes a cluster first, if it exists
go run hack/e2e.go --up
# Create a fresh cluster at a specific release version.
go run hack/e2e.go --up --version=0.7.0
# Test if a cluster is up.
go run hack/e2e.go --isup
# Push code to an existing cluster
go run hack/e2e.go --push
# Push to an existing cluster, or bring up a cluster if it's down.
go run hack/e2e.go --pushup
# Run all tests
go run hack/e2e.go --test
# Run tests matching the regex "Pods.*env"
go run hack/e2e.go -v -test --test_args="--ginkgo.focus=Pods.*env"
# Alternately, if you have the e2e cluster up and no desire to see the event stream, you can run ginkgo-e2e.sh directly:
hack/ginkgo-e2e.sh --ginkgo.focus=Pods.*env
```
### Combining flags
```sh
# Flags can be combined, and their actions will take place in this order:
# -build, -push|-up|-pushup, -test|-tests=..., -down
# e.g.:
go run hack/e2e.go -build -pushup -test -down
# -v (verbose) can be added if you want streaming output instead of only
# seeing the output of failed commands.
# -ctl can be used to quickly call kubectl against your e2e cluster. Useful for
# cleaning up after a failed test or viewing logs. Use -v to avoid suppressing
# kubectl output.
go run hack/e2e.go -v -ctl='get events'
go run hack/e2e.go -v -ctl='delete pod foobar'
```
## Conformance testing
End-to-end testing, as described above, is for [development
distributions](../../docs/devel/writing-a-getting-started-guide.md). A conformance test is used on
a [versioned distro](../../docs/devel/writing-a-getting-started-guide.md).
The conformance test runs a subset of the e2e-tests against a manually-created cluster. It does not
require support for up/push/down and other operations. To run a conformance test, you need to know the
IP of the master for your cluster and the authorization arguments to use. The conformance test is
intended to run against a cluster at a specific binary release of Kubernetes.
See [conformance-test.sh](../../hack/conformance-test.sh).
## Testing out flaky tests
[Instructions here](flaky-tests.md)
## Keeping your development fork in sync
One time after cloning your forked repo:
```
git remote add upstream https://github.com/GoogleCloudPlatform/kubernetes.git
```
Then each time you want to sync to upstream:
```
git fetch upstream
git rebase upstream/master
```
If you have write access to the main repository, you should modify your git configuration so that
you can't accidentally push to upstream:
```
git remote set-url --push upstream no_push
```
## Regenerating the CLI documentation
```
hack/run-gendocs.sh
```
| {
"content_hash": "668ec0326f2848f445bbd2f15093cc8a",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 328,
"avg_line_length": 36.011320754716984,
"alnum_prop": 0.7557371895630305,
"repo_name": "whitmo/kubernetes",
"id": "6d6bdb8611890f7cb409e038a206dcd2bd42ce0e",
"size": "9596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/devel/development.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "60606"
},
{
"name": "Go",
"bytes": "9939981"
},
{
"name": "HTML",
"bytes": "51569"
},
{
"name": "Java",
"bytes": "3851"
},
{
"name": "JavaScript",
"bytes": "177629"
},
{
"name": "Makefile",
"bytes": "11115"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "PHP",
"bytes": "736"
},
{
"name": "Perl",
"bytes": "329"
},
{
"name": "Python",
"bytes": "60519"
},
{
"name": "Ruby",
"bytes": "2778"
},
{
"name": "Scheme",
"bytes": "1112"
},
{
"name": "Shell",
"bytes": "633411"
}
],
"symlink_target": ""
} |
<?php
/**
* Defines the securable object role assignments for a user or group on the Web site, list, or list item.
*/
namespace SharePoint\PHP\Client;
class RoleAssignment extends ClientObject
{
} | {
"content_hash": "9d6562f4d002d94b70f142c3534e7402",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 105,
"avg_line_length": 16.833333333333332,
"alnum_prop": 0.7425742574257426,
"repo_name": "ctcudd/phpSPO",
"id": "58e25e90a89c8485eb240e41a869b4a14da6d527",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RoleAssignment.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "101270"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Sistema de Aprendizado de Lógica</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<!-- <link rel="apple-touch-icon" sizes="76x76" href="assets/mBranca.png" /> -->
<link rel="icon" type="image/png" href="assets/mBranca.png" />
<!-- Fonts and icons -->
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<!-- CSS Files -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet" />
<link href="assets/css/material-bootstrap-wizard.css" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="assets/css/demo.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.w3schools.com/lib/w3.js"></script>
<script src="funcoes_gerais.js" type="text/javascript"></script>
<script src="teste.js" type="text/javascript"></script>
<script src="funcoes_resolucao.js" type="text/javascript"></script>
<script src="funcoes_tableaux.js" type="text/javascript"></script>
<!-- <script src="funcoes_deducao.js" type="text/javascript"></script> -->
<style>
.popover-content {
background-color: PaleGoldenRod ;
color: #000000;
padding: 15px;
}
.popover-title {
background-color: GoldenRod ;
color: #000000;
font-size: 14px;
text-align:center;
}
.popover {
border: 2 px solid #C0C0C0;
}
</style>
</head>
<body onload="load()">
<a target="_blank" href="https://ufrj.br/">
<div class="logo-container">
<div class="logo">
<img src="assets/mBranca.png">
</div>
<div class="brand">
Universidade Federal do Rio de Janeiro
</div>
</div>
</a>
<div class="image-container set-full-height" style="background-image: url('assets/img/wall.jpg')">
<!-- Big container -->
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<!-- Wizard container -->
<div class="wizard-container">
<div class="card wizard-card" data-color="red" id="wizard">
<form action="" method="">
<!-- You can switch " data-color="blue" " with one of the next bright colors: "green", "orange", "red", "purple" -->
<div class="wizard-header">
<h3 class="wizard-title">
Sistema de Aprendizado de Lógica
</h3>
<h5>Ambiente para prática de exercícios de lógica.</h5>
</div>
<div class="wizard-navigation">
<ul>
<!-- style="display:none" -->
<li><a href="#tipo" data-toggle="tab">Tipo de Exercício</a></li>
<li><a href="#exercicio" id='tabExercicio' data-toggle="tab">Seleção do Exercício</a></li>
<li><a href="#execucao" id='tabExecucao' data-toggle="tab">Solução</a></li>
</ul>
</div>
<div class="tab-content">
<!---------------------------------------------------------------------------------------------------------------------------------->
<!------------------ TAB DOS TIPOS DE EXERCICIOS --------------------------------------------------------------------------------->
<div class="tab-pane" id="tipo">
<h4 class="info-text">Qual tipo de exercício deseja praticar? </h4>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Árvore de Tableaux">
<input type="radio" name="escolha" value="tableaux">
<div class="icon" id="botaoTableaux">
<i class="material-icons">call_split</i>
</div>
<h6>Tableaux</h6>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Método de Resolução">
<input type="radio" name="escolha" value="resolucao">
<div class="icon" id="botaoResolucao">
<i class="material-icons">live_tv</i>
</div>
<h6>Resolução</h6>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Método de Dedução Natural">
<input type="radio" name="escolha" value="deducao">
<div class="icon" id="botaoDeducao">
<i class="material-icons">search</i>
</div>
<h6>Deducao Natural</h6>
</div>
</div>
</div>
</div>
</div>
<!---------------------------------------------------------------------------------------------------------------------------------->
<!----------------- TAB DE SELECAO DE EXERCICIOS / ADD REGRAS --------------------------------------------------------------------->
<div class="tab-pane" id="exercicio" style="display: none">
<div class="row">
<div class="col-sm-8 col-sm-offset-3">
<article>✦ Selecione um exercício ou crie o seu próprio</article>
<article>✦ Exemplo de adição de fórmula:</article>
<article> ¬A∨((B^C)➝ D) deve ser escrita como (notA)ou((BeC)implica(D))</article>
</div>
<div class="col-sm-4 col-sm-offset-1">
<!-- <div class="dropdown"> -->
<!-- <button class="btn btn-info btn-sm dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> -->
<!-- Listas de Exercícíos -->
<!-- </button> -->
<!-- <div class="dropdown-menu" aria-labelledby="dropdownMenu2"> -->
<!-- <h6 class="dropdown-header">Lista 1</h6> -->
<!-- <button class="dropdown-item" type="button">Ex.1</button> -->
<!-- <button class="dropdown-item" type="button">Ex.2</button> -->
<!-- <h6 class="dropdown-header">Lista 2</h6> -->
<!-- <button class="dropdown-item" type="button">Ex.1</button> -->
<!-- <button class="dropdown-item" type="button">Ex.2</button> -->
<!-- <button class="dropdown-item" type="button">Ex.3</button> -->
<!-- <h6 class="dropdown-header">Lista 3</h6> -->
<!-- <button class="dropdown-item" type="button">Ex.1</button> -->
<!-- <button class="dropdown-item" type="button">Ex.2</button> -->
<!-- </div> -->
<!-- </div> -->
<div class="input-group">
<div class="form-group label-floating">
<label class="control-label">Número do Exercício</label>
<input name="numExercicio" id="numExercicio" type="text" class="form-control">
<button class='btn btn-info btn-xs' type="button" id="buttonBuscaExercicio" onclick="f_buscaExercicio()">Buscar exercício</button>
</div>
</div>
<div class="input-group">
<div class="form-group label-floating">
<label class="control-label">Regra</label>
<input name="regra" id="regra" type="text" class="form-control">
<button class='btn btn-info btn-xs' type="button" id="buttonRegra" onClick="f_AddRegra()"> Adicionar regra </button>
</div>
</div>
<div class="input-group">
<div class="form-group label-floating">
<label class="control-label">Pergunta</label>
<input name="pergunta" id="pergunta" type="text" class="form-control">
<button class='btn btn-info btn-xs' type="button" id="buttonPergunta" onclick="f_AddPergunta()"> Adicionar pergunta </button>
</div>
</div>
</div>
<div class="col-sm-6 col-sm-offset-1">
<div class="form-group label-floating">
<strong>> Regras adicionadas:</strong>
<article id="regrasAdicionadas" ></article>
</div>
<div class="form-group label-floating">
<strong>> Pergunta:</strong>
<article id="perguntaAdicionada" ></article>
</div>
</div>
</div>
</div>
<!--------------------------------------------------------------------------------------------------------------------->
<!----------------- TAB DE SOLUCAO DO EXERCICIO --------------------------------------------------------------------------------->
<div class="tab-pane" id="execucao" >
<div class="row">
<!-- DIV PARA TABLEAUX #############################################################################-->
<div class="col-sm-8 col-sm-offset-2">
<div class="regrasTableaux" id='divTableaux' style="display: none">
<!-- <div class="alert alert-info alert-dismissible" id='alertResolucao' > -->
<!-- <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> -->
<!-- <strong>Atenção!</strong> Todas as fórmulas devem passar uma vez pelo passo de transformação para FNC, mesmo que já estejam inicialmente em FNC. -->
<!-- </div> -->
<div class="passos" id="t_passos">
<h4 class="control-label"><strong> > Passo-a-passo Para Tableaux:</strong></h4>
<article id='t_passo1'>- Negar a Pergunta</article> </br>
<!-- <article id='t_passo2'> </article> </br> -->
<article id='t_passo3'>- Desenvolver o exercício até fechar todos os ramos da árvore </article> </br>
<button type="button" class="btn btn-success btn-sm" data-trigger="focus" data-toggle="popover" data-placement="left" data-content="<ol><li>Negar a pergunta</li><li>Passar todas as fórmulas e a pergunta para FNC</li><li>Separar todos os 'e', ou seja, cada 'e' vira uma fórmula (ou linha) independente.</li><li>Verificar se há 'átomos', havendo, confrontar átomos para ver se a resolução fecha, por exemplo A e ¬A são átomos que se contradizem e portanto fecharia a resolução.</li><li>Se não fechar, vá para a próxima etapa. Fazer as simplificações do 'ou', se possível. Se Av¬B e AvB então A. Se Av¬B e B então A</li><li>Verificar se há átomos, havendo, confrontar átomos para ver se a resolução fecha.</li><li>Se não fechar após este último passo, o problema não é possível de resolver.</li></ol>" data-html="true" title="Algoritmo Base" >Algoritmo completo aqui</button>
</div>
<!-- ############################################################################################### -->
<div class="t_inicioEx">
<h4><strong>> Início do Exercício</strong> </h4>
<div class="col-sm-8 col-sm-offset-0">
<div id="t_divFormulas">
</style>
</div>
<!-- ############################################################################################### -->
<div class="form-check" id="t_divNovasFormulas">
</div>
</br>
<!-- <button type="button" id="btn_ConfrontarRegra" class="btn btn-info btn-sm" onclick='f_Confrontar()' >Confrontar fórmulas</button> -->
<!-- <button type="button" id="btn_TransformarRegra" class="btn btn-info btn-sm" onclick="f_Transformar()" >Transformar fórmula</button> -->
<!-- <button type="button" id="btn_ProximoPasso" class="btn btn-danger btn-sm" onclick='f_Next()' >Próximo passo </button> -->
</div>
</div>
</div>
</div> <!--FIM TABLEAUX -->
<!-- DIV PARA RESOLUCAO -->
<div class="col-sm-8 col-sm-offset-2">
<div class="regrasResolucao" id='divResolucao' style="display: none">
<div class="alert alert-info alert-dismissible" id='alertResolucao' >
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Atenção!</strong> Todas as fórmulas devem passar uma vez pelo passo de transformação para FNC, mesmo que já estejam inicialmente em FNC.
</div>
<div class="passos" id="r_passos">
<h4 class="control-label"><strong> > Passo-a-passo Para Resolução:</strong></h4>
<span id='r_passo1'>- Negar a Pergunta</span> </br>
<span id='r_passo2'>- Passar todas as fórmulas e a pergunta negada para FNC</span> </br>
<article id='r_passo3'>- Desenvolver o exercício até encontrar o absurdo ❒ </article> </br>
<button type="button" class="btn btn-success btn-sm" data-trigger="focus" data-toggle="popover" data-placement="left" data-content="<ol><li>Negar a pergunta</li><li>Passar todas as fórmulas e a pergunta para FNC</li><li>Separar todos os 'e', ou seja, cada 'e' vira uma fórmula (ou linha) independente.</li><li>Verificar se há 'átomos', havendo, confrontar átomos para ver se a resolução fecha, por exemplo A e ¬A são átomos que se contradizem e portanto fecharia a resolução.</li><li>Se não fechar, vá para a próxima etapa. Fazer as simplificações do 'ou', se possível. Se Av¬B e AvB então A. Se Av¬B e B então A</li><li>Verificar se há átomos, havendo, confrontar átomos para ver se a resolução fecha.</li><li>Se não fechar após este último passo, o problema não é possível de resolver.</li></ol>" data-html="true" title="Algoritmo Base" >Algoritmo completo aqui</button>
</div>
<!-- ############################################################################################### -->
<div class="r_inicioEx">
<h4><strong>> Início do Exercício</strong> </h4>
<div class="col-sm-8 col-sm-offset-0">
<div class='formulas' id="r_divFormulas">
</style>
</div>
<!-- ############################################################################################### -->
<div class="form-check" id="r_divNovasFormulas">
</div>
</br>
<button type="button" id="btn_ConfrontarRegra" class="btn btn-info btn-sm" onclick='f_Confrontar()' >Confrontar fórmulas</button>
<button type="button" id="btn_TransformarRegra" class="btn btn-info btn-sm" onclick="f_Transformar()" >Transformar fórmula</button>
<button type="button" id="btn_ProximoPasso" class="btn btn-danger btn-sm" onclick='f_Next()' >Próximo passo </button>
</div>
</div>
</div> <!--FIM RESOLUCAO -->
<!-- DIV PARA DEDUCAO NATURAL-->
<div class="col-sm-8 col-sm-offset-2">
<div class="regrasDeducao" id='divDeducao' style="display: none">
<h4 class="info-text"> Execução da Dedução Natural...</h4>
</div>
</div> <!--FIM DEDUCAO -->
</div> <!-- FIM ROW -->
</div> <!-- FIM TAB EXERCICIO -->
<!-- fechando div do tabpane -->
</div>
<!--------------------------------------------------------------------------------------------------------------------->
<!----------------- NEXT/PREVIOUS/RODAPE --------------------------------------------------------------------------------->
<div class="wizard-footer">
</br>
<div class="pull-right">
<input disabled type='button' class='btn btn-next btn-fill btn-danger btn-wd' id="proximo" name='proximo' value='Próximo' />
<input type='button' class='btn btn-finish btn-fill btn-warning btn-wd' id="btn_gabarito" name='gabarito' value='Gabarito' onclick='f_Gabarito()' />
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-fill btn-default btn-wd' id="anterior" name='anterior' value='Anterior' />
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</div> <!-- wizard container -->
</div>
</div> <!-- row -->
</div> <!-- big container -->
<div class="footer">
<div class="container text-center">
<b>Desenvolvedores: Herbert Salazar, Marco Rodrigues e Yuri Santana.</b> <br/>
<b>Orientador: Mário Benevides.</b>
</div>
</div>
</div>
</body>
<!-- Core JS Files -->
<script src="assets/js/jquery-2.2.4.min.js" type="text/javascript"></script>
<script src="assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.bootstrap.js" type="text/javascript"></script>
<!-- Plugin for the Wizard -->
<script src="assets/js/material-bootstrap-wizard.js"></script>
<!-- More information about jquery.validate here: http://jqueryvalidation.org/ -->
<script src="assets/js/jquery.validate.min.js"></script>
</html>
| {
"content_hash": "7e0100ab3be80e8c33bc18d32b6a8fca",
"timestamp": "",
"source": "github",
"line_count": 360,
"max_line_length": 889,
"avg_line_length": 58.12222222222222,
"alnum_prop": 0.43576753966736764,
"repo_name": "herbertsds/projetoFinal",
"id": "3275a0cdb709935dab9e2acc8494ea75471a63e1",
"size": "21060",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Projeto Final/WebContent/pagina/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "128174"
},
{
"name": "HTML",
"bytes": "24579"
},
{
"name": "JavaScript",
"bytes": "43233"
},
{
"name": "PHP",
"bytes": "375738"
},
{
"name": "Vue",
"bytes": "563"
}
],
"symlink_target": ""
} |
//
// QtThread.cpp - C++ Thread class built on top of Qt threads.
// ~~~~~~~~~~~
#include "QtThreadPrivateData.h"
#include <QtCore/QCoreApplication>
#include <iostream>
using namespace OpenThreads;
//-----------------------------------------------------------------------------
// Initialize thread master priority level
//
Thread::ThreadPriority Thread::s_masterThreadPriority = Thread::THREAD_PRIORITY_DEFAULT;
bool Thread::s_isInitialized = false;
//----------------------------------------------------------------------------
//
// Description: Set the concurrency level (no-op)
//
// Use static public
//
int Thread::SetConcurrency(int concurrencyLevel)
{ return -1; }
//----------------------------------------------------------------------------
//
// Description: Get the concurrency level
//
// Use static public
//
int Thread::GetConcurrency()
{ return -1; }
//----------------------------------------------------------------------------
//
// Decription: Constructor
//
// Use: public.
//
Thread::Thread()
{
if (!s_isInitialized) Init();
QtThreadPrivateData* pd = new QtThreadPrivateData(this);
pd->isRunning = false;
pd->detached = false;
pd->cancelled = false;
pd->cancelMode = 0;
pd->uniqueId = QtThreadPrivateData::createUniqueID();
pd->cpunum = -1;
pd->stackSize = 0;
pd->threadPolicy = Thread::THREAD_SCHEDULE_DEFAULT;
pd->threadPriority = Thread::THREAD_PRIORITY_DEFAULT;
_prvData = static_cast<void*>(pd);
}
//----------------------------------------------------------------------------
//
// Description: Destructor
//
// Use: public.
//
Thread::~Thread()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
if (pd->isRunning)
{
std::cout<<"Error: Thread "<< this <<" still running in destructor"<<std::endl;
cancel();
}
delete pd;
_prvData = 0;
}
Thread* Thread::CurrentThread()
{
if (!s_isInitialized) Thread::Init();
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(QThread::currentThread());
return (pd ? pd->getMasterThread() : 0);
}
//-----------------------------------------------------------------------------
//
// Description: Initialize Threading
//
// Use: public.
//
void Thread::Init()
{
s_isInitialized = true;
}
//-----------------------------------------------------------------------------
//
// Description: Get a unique identifier for this thread.
//
// Use: public
//
int Thread::getThreadId()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
return pd->uniqueId;
}
//-----------------------------------------------------------------------------
//
// Description: Get the thread's process id
//
// Use: public
//
size_t Thread::getProcessId()
{
return (size_t)QCoreApplication::applicationPid();
}
//-----------------------------------------------------------------------------
//
// Description: Determine if the thread is running
//
// Use: public
//
bool Thread::isRunning()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
return pd->isRunning;
}
//-----------------------------------------------------------------------------
//
// Description: Start the thread.
//
// Use: public
//
int Thread::start()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->threadStartedBlock.reset();
pd->setStackSize( pd->stackSize );
pd->start();
// wait till the thread has actually started.
pd->threadStartedBlock.block();
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Alternate thread start routine.
//
// Use: public
//
int Thread::startThread()
{
if (_prvData) return start();
else return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Join the thread.
//
// Use: public
//
int Thread::detach()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->detached = true;
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Join the thread.
//
// Use: public
//
int Thread::join()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
if (pd->detached) return -1;
return pd->wait() ? 0 : -1;
}
//-----------------------------------------------------------------------------
//
// Description: test the cancel state of the thread.
//
// Use: public
//
int Thread::testCancel()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
if (!pd->cancelled)
return 0;
if (pd->cancelMode == 2)
return -1;
if (pd!=QThread::currentThread())
return -1;
throw QtThreadCanceled();
}
//-----------------------------------------------------------------------------
//
// Description: Cancel the thread.
//
// Use: public
//
int Thread::cancel()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
if (pd->isRunning)
{
if (pd->cancelMode == 2)
return -1;
pd->cancelled = true;
if (pd->cancelMode == 1)
{
pd->isRunning = false;
pd->terminate();
}
}
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: set the thread to cancel at the next convenient point.
//
// Use: public
//
int Thread::setCancelModeDeferred()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->cancelMode = 0;
pd->setAsynchronousTermination(false);
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: set the thread to cancel immediately
//
// Use: public
//
int Thread::setCancelModeAsynchronous()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->cancelMode = 1;
pd->setAsynchronousTermination(true);
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Disable cancelibility
//
// Use: public
//
int Thread::setCancelModeDisable()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->cancelMode = 2;
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Set the thread's schedule priority (if able)
//
// Use: public
//
int Thread::setSchedulePriority(ThreadPriority priority)
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->threadPriority = priority;
if (pd->isRunning)
pd->applyPriority();
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Get the thread's schedule priority (if able)
//
// Use: public
//
int Thread::getSchedulePriority()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
return pd->threadPriority;
}
//-----------------------------------------------------------------------------
//
// Description: Set the thread's scheduling policy (if able)
//
// Use: public
//
int Thread::setSchedulePolicy(ThreadPolicy policy)
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->threadPolicy = policy;
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Set the thread's scheduling policy (if able)
//
// Use: public
//
int Thread::getSchedulePolicy()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
return pd->threadPolicy;
}
//-----------------------------------------------------------------------------
//
// Description: Set the thread's desired stack size
//
// Use: public
//
int Thread::setStackSize(size_t stackSize)
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
if (pd->isRunning) return 13; // return EACESS
else pd->stackSize = stackSize;
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Get the thread's stack size.
//
// Use: public
//
size_t Thread::getStackSize()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
return pd->stackSize;
}
//-----------------------------------------------------------------------------
//
// Description: set processor affinity for the thread
//
// Use: public
//
int Thread::setProcessorAffinity(unsigned int cpunum)
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
pd->cpunum = cpunum;
if (!pd->isRunning) return 0;
// FIXME:
// Qt doesn't have a platform-independent thread affinity method at present.
// Does it automatically configure threads on different processors, or we have to do it ourselves?
return -1;
}
//-----------------------------------------------------------------------------
//
// Description: Print the thread's scheduling information to stdout.
//
// Use: public
//
void Thread::printSchedulingInfo()
{
QtThreadPrivateData* pd = static_cast<QtThreadPrivateData*>(_prvData);
std::cout << "Thread "<< pd->getMasterThread() <<" priority: ";
switch (pd->threadPriority)
{
case Thread::THREAD_PRIORITY_MAX:
std::cout << "MAXIMAL" << std::endl;
break;
case Thread::THREAD_PRIORITY_HIGH:
std::cout << "HIGH" << std::endl;
break;
case Thread::THREAD_PRIORITY_DEFAULT:
case Thread::THREAD_PRIORITY_NOMINAL:
std::cout << "NORMAL" << std::endl;
break;
case Thread::THREAD_PRIORITY_LOW:
std::cout << "LOW" << std::endl;
break;
case Thread::THREAD_PRIORITY_MIN:
std::cout << "MINIMAL" << std::endl;
break;
}
}
//-----------------------------------------------------------------------------
//
// Description: Yield the processor
//
// Use: protected
//
int Thread::YieldCurrentThread()
{
QThread::yieldCurrentThread();
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: sleep
//
// Use: public
//
int Thread::microSleep(unsigned int microsec)
{
QtThreadPrivateData::microSleep(microsec);
return 0;
}
//-----------------------------------------------------------------------------
//
// Description: Get the number of processors
//
int OpenThreads::GetNumberOfProcessors()
{
return QThread::idealThreadCount();
}
//-----------------------------------------------------------------------------
//
// Description: set processor affinity for current thread
//
int OpenThreads::SetProcessorAffinityOfCurrentThread(unsigned int cpunum)
{
if (cpunum<0) return -1;
Thread::Init();
Thread* thread = Thread::CurrentThread();
if (thread)
return thread->setProcessorAffinity(cpunum);
else
return -1;
}
| {
"content_hash": "5672113a0d1deeeb62000c0d949ef2a2",
"timestamp": "",
"source": "github",
"line_count": 452,
"max_line_length": 102,
"avg_line_length": 24.347345132743364,
"alnum_prop": 0.5086778736937756,
"repo_name": "mattjr/seafloorexplore",
"id": "803da0cd39974fd829b450af3ea3d84b0108f8b5",
"size": "11652",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "OpenThreads/qt/QtThread.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1348006"
},
{
"name": "C++",
"bytes": "10602121"
},
{
"name": "CMake",
"bytes": "14594"
},
{
"name": "GLSL",
"bytes": "38682"
},
{
"name": "Objective-C",
"bytes": "1053643"
},
{
"name": "Objective-C++",
"bytes": "312055"
},
{
"name": "Shell",
"bytes": "1959"
}
],
"symlink_target": ""
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdPlaylistAdd = function MdPlaylistAdd(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm3.4 26.6v-3.2h13.2v3.2h-13.2z m26.6-3.2h6.6v3.2h-6.6v6.8h-3.4v-6.8h-6.6v-3.2h6.6v-6.8h3.4v6.8z m-6.6-13.4v3.4h-20v-3.4h20z m0 6.6v3.4h-20v-3.4h20z' })
)
);
};
exports.default = MdPlaylistAdd;
module.exports = exports['default']; | {
"content_hash": "ec15b4d555edb67adca0fc6c9fc1ce54",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 257,
"avg_line_length": 36.90625,
"alnum_prop": 0.6494496189669772,
"repo_name": "bairrada97/festival",
"id": "78b1c2e1975e09165f51cfbe4cf2ccbee087194c",
"size": "1181",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/react-icons/lib/md/playlist-add.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39693"
},
{
"name": "CSS",
"bytes": "17977"
},
{
"name": "HTML",
"bytes": "727641"
},
{
"name": "JavaScript",
"bytes": "3264"
}
],
"symlink_target": ""
} |
import contextlib
import os
import sys
import tempfile
import uuid
import datetime
import shlex
import pyclbr
import random
import inspect
import socket
import re
import types
import time
import calendar
import netaddr
import shutil
import json
import itertools
from collections import OrderedDict
from xml.sax import saxutils
from eventlet import greenthread
from eventlet.green import subprocess
from synaps import flags
from synaps import exception
from synaps import log as logging
from synaps.openstack.common import cfg
from novaclient.v1_1 import client
LOG = logging.getLogger(__name__)
ISO_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
PERFECT_TIME_FORMAT_Z = "%Y-%m-%dT%H:%M:%S.%fZ"
NO_MS_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
FLAGS = flags.FLAGS
FLAGS.register_opt(
cfg.BoolOpt('disable_process_locking', default=False,
help='Whether to disable inter-process locks'))
RE_INTERNATIONAL_PHONENUMBER = re.compile("^\+[0-9]{7,17}$")
RE_EMAIL = re.compile('^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$')
RE_UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
RE_INSTANCE_ACTION = re.compile('^InstanceAction:(Reboot|Migrate)\((%s)\)' %
RE_UUID)
RE_GROUPNOTIFICATION_ACTION = re.compile('^NotifyTo\((.{3,60})\)')
UNIT_CONV_MAP = {
'None': 1.0,
'Seconds': 1.0,
'Bytes':1.0,
'Bytes/Second':1.0, # std: Bytes/Second
'Percent': 1.0,
'Count': 1.0,
'Count/Second': 1.0,
'Microseconds': 10.0 ** (-6), # std: Seconds
'Milliseconds': 10.0 ** (-3), # std: Seconds
'Kilobytes':2.0 ** 10, # std: Bytes
'Megabytes':2.0 ** 20, # std: Bytes
'Gigabytes':2.0 ** 30, # std: Bytes
'Terabytes':2.0 ** 40, # std: Bytes
'Bits':2.0 ** (-3), # std: Bytes
'Kilobits':2.0 ** 7, # std: Bytes
'Megabits':2.0 ** 17, # std: Bytes
'Gigabits':2.0 ** 27, # std: Bytes
'Terabits':2.0 ** 37, # std: Bytes
'Kilobytes/Second':10.0 ** 3, # std: Bytes/Second
'Megabytes/Second':10.0 ** 6, # std: Bytes/Second
'Gigabytes/Second':10.0 ** 9, # std: Bytes/Second
'Terabytes/Second':10.0 ** 12, # std: Bytes/Second
'Bits/Second':2.0 ** (-3), # std: Bytes/Second
'Kilobits/Second':2.0 ** 7, # std: Bytes/Second
'Megabits/Second':2.0 ** 17, # std: Bytes/Second
'Gigabits/Second':2.0 ** 27, # std: Bytes/Second
'Terabits/Second':2.0 ** 37, # std: Bytes/Second
}
UNITS = UNIT_CONV_MAP.keys()
def validate_email(email):
try:
ret = RE_EMAIL.match(email) is not None
except TypeError:
ret = False
return ret
def validate_instance_action(instance_action):
try:
ret = RE_INSTANCE_ACTION.match(instance_action) is not None
except TypeError:
ret = False
return ret
def validate_groupnotification_action(action):
try:
ret = RE_GROUPNOTIFICATION_ACTION.match(action) is not None
except TypeError:
ret = False
return ret
def parse_instance_action(instance_action):
mobj = RE_INSTANCE_ACTION.match(instance_action)
return mobj.groups() if mobj else None
def parse_groupnotification_action(action):
mobj = RE_GROUPNOTIFICATION_ACTION.match(action)
return mobj.groups()[-1] if mobj else None
def validate_international_phonenumber(number):
"""
International Telecommunication Union ITU-T Rec. E.123 (02/2001)
Notation for national and international telephone numbers, e-mail addresses
and web addresses
"""
try:
head, tail = number.split(' ', 1)
except ValueError:
return False
number = head + tail.replace(' ', '')
return RE_INTERNATIONAL_PHONENUMBER.match(number) is not None
def to_unit(value, unit):
if not unit:
unit = "None"
return value / UNIT_CONV_MAP[unit]
def to_default_unit(value, unit):
if not unit:
unit = "None"
return value * UNIT_CONV_MAP[unit]
def to_primitive(value, convert_instances=False, level=0):
"""Convert a complex object into primitives.
Handy for JSON serialization. We can optionally handle instances,
but since this is a recursive function, we could have cyclical
data structures.
To handle cyclical data structures we could track the actual objects
visited in a set, but not all objects are hashable. Instead we just
track the depth of the object inspections and don't go too deep.
Therefore, convert_instances=True is lossy ... be aware.
"""
nasty = [inspect.ismodule, inspect.isclass, inspect.ismethod,
inspect.isfunction, inspect.isgeneratorfunction,
inspect.isgenerator, inspect.istraceback, inspect.isframe,
inspect.iscode, inspect.isbuiltin, inspect.isroutine,
inspect.isabstract]
for test in nasty:
if test(value):
return unicode(value)
# value of itertools.count doesn't get caught by inspects
# above and results in infinite loop when list(value) is called.
if type(value) == itertools.count:
return unicode(value)
# FIXME(vish): Workaround for LP bug 852095. Without this workaround,
# tests that raise an exception in a mocked method that
# has a @wrap_exception with a notifier will fail. If
# we up the dependency to 0.5.4 (when it is released) we
# can remove this workaround.
if getattr(value, '__module__', None) == 'mox':
return 'mock'
if level > 3:
return '?'
# The try block may not be necessary after the class check above,
# but just in case ...
try:
if isinstance(value, (list, tuple)):
o = []
for v in value:
o.append(to_primitive(v, convert_instances=convert_instances,
level=level))
return o
elif isinstance(value, dict):
o = {}
for k, v in value.iteritems():
o[k] = to_primitive(v, convert_instances=convert_instances,
level=level)
return o
elif isinstance(value, datetime.datetime):
return str(value)
elif hasattr(value, 'iteritems'):
return to_primitive(dict(value.iteritems()),
convert_instances=convert_instances,
level=level)
elif hasattr(value, '__iter__'):
return to_primitive(list(value), level)
elif convert_instances and hasattr(value, '__dict__'):
# Likely an instance of something. Watch for cycles.
# Ignore class member vars.
return to_primitive(value.__dict__,
convert_instances=convert_instances,
level=level + 1)
else:
return value
except TypeError, e:
# Class objects are tricky since they may define something like
# __iter__ defined but it isn't callable as list().
return unicode(value)
def dumps(value):
try:
return json.dumps(value)
except TypeError:
pass
return json.dumps(to_primitive(value))
def gen_uuid():
return uuid.uuid4()
def utcnow():
"""Overridable version of utils.utcnow."""
if utcnow.override_time:
return utcnow.override_time
return datetime.datetime.utcnow()
utcnow.override_time = None
def align_metrictime(timestamp, resolution=60):
"""
Align timestamp of metric for statistics
>>> align_metrictime(35.0, 60.0)
60.0
>>> align_metrictime(60.0, 60.0)
120.0
>>> align_metrictime(150.0, 60.0)
180.0
>>> align_metrictime(150.1, 60.0)
180.0
"""
mod = int(datetime_to_timestamp(timestamp)) / resolution
return datetime.datetime.utcfromtimestamp((mod + 1) * resolution)
def str_to_timestamp(timestr, fmt=PERFECT_TIME_FORMAT):
if isinstance(timestr, str):
at = parse_strtime(timestr, fmt)
return time.mktime(at.timetuple())
else:
return time.time()
def parse_strtime(timestr, fmt=PERFECT_TIME_FORMAT):
"""Turn a formatted time back into a datetime."""
if timestr.endswith('Z'):
timestr = timestr[:-1]
try:
ret = datetime.datetime.strptime(timestr, fmt)
except ValueError:
ret = datetime.datetime.strptime(timestr, NO_MS_TIME_FORMAT)
return ret
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
"""Returns formatted utcnow."""
if not at:
at = utcnow()
return at.strftime(fmt)
def strtime_trunk(at=None):
"""Returns formatted utcnow."""
strt = strtime(at, PERFECT_TIME_FORMAT_Z)
return strt[:-5] + "Z"
def to_ascii(utf8):
if isinstance(utf8, unicode):
return utf8.encode('ascii')
assert isinstance(utf8, str)
return utf8
def utf8(value):
"""Try to turn a string into utf-8 if possible.
Code is directly from the utf8 function in
http://github.com/facebook/tornado/blob/master/tornado/escape.py
"""
if isinstance(value, unicode):
return value.encode('utf-8')
assert isinstance(value, str)
return value
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ImportError, ValueError, AttributeError), exc:
LOG.debug(_('Inner Exception: %s'), exc)
raise exception.ClassNotFound(class_name=class_str, exception=exc)
def monkey_patch():
""" If the Flags.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using FLAGS.monkey_patch_modules.
The format is "Module path:Decorator function".
Example: 'nova.api.ec2.cloud:nova.notifier.api.notify_decorator'
Parameters of the decorator is as follows.
(See nova.notifier.api.notify_decorator)
name - name of the function
function - object of the function
"""
# If FLAGS.monkey_patch is not True, this function do nothing.
if not FLAGS.monkey_patch:
return
# Get list of modules and decorators
for module_and_decorator in FLAGS.monkey_patch_modules:
module, decorator_name = module_and_decorator.split(':')
# import decorator function
decorator = import_class(decorator_name)
__import__(module)
# Retrieve module information using pyclbr
module_data = pyclbr.readmodule_ex(module)
for key in module_data.keys():
# set the decorator for the class methods
if isinstance(module_data[key], pyclbr.Class):
clz = import_class("%s.%s" % (module, key))
for method, func in inspect.getmembers(clz, inspect.ismethod):
setattr(clz, method,
decorator("%s.%s.%s" % (module, key, method), func))
# set the decorator for the function
if isinstance(module_data[key], pyclbr.Function):
func = import_class("%s.%s" % (module, key))
setattr(sys.modules[module], key,
decorator("%s.%s" % (module, key), func))
def default_flagfile(filename='synaps.conf', args=None):
if args is None:
args = sys.argv
for arg in args:
if arg.find('flagfile') != -1:
return arg[arg.index('flagfile') + len('flagfile') + 1:]
else:
if not os.path.isabs(filename):
# turn relative filename into an absolute path
script_dir = os.path.dirname(inspect.stack()[-1][1])
filename = os.path.abspath(os.path.join(script_dir, filename))
if not os.path.exists(filename):
filename = "./synaps.conf"
if not os.path.exists(filename):
filename = '/etc/synaps/synaps.conf'
if os.path.exists(filename):
flagfile = '--flagfile=%s' % filename
args.insert(1, flagfile)
return filename
def find_config(config_path):
"""Find a configuration file using the given hint.
:param config_path: Full or relative path to the config.
:returns: Full path of the config, if it exists.
:raises: `synaps.exception.ConfigNotFound`
"""
possible_locations = [
config_path,
os.path.join(FLAGS.state_path, "etc", "synaps", config_path),
os.path.join(FLAGS.state_path, "etc", config_path),
os.path.join(FLAGS.state_path, config_path),
"/etc/synaps/%s" % config_path,
]
for path in possible_locations:
if os.path.exists(path):
return os.path.abspath(path)
raise exception.ConfigNotFound(path=os.path.abspath(config_path))
def cleanup_file_locks():
"""clean up stale locks left behind by process failures
The lockfile module, used by @synchronized, can leave stale lockfiles
behind after process failure. These locks can cause process hangs
at startup, when a process deadlocks on a lock which will never
be unlocked.
Intended to be called at service startup.
"""
# NOTE(mikeyp) this routine incorporates some internal knowledge
# from the lockfile module, and this logic really
# should be part of that module.
#
# cleanup logic:
# 1) look for the lockfile modules's 'sentinel' files, of the form
# hostname.[thread-.*]-pid, extract the pid.
# if pid doesn't match a running process, delete the file since
# it's from a dead process.
# 2) check for the actual lockfiles. if lockfile exists with linkcount
# of 1, it's bogus, so delete it. A link count >= 2 indicates that
# there are probably sentinels still linked to it from active
# processes. This check isn't perfect, but there is no way to
# reliably tell which sentinels refer to which lock in the
# lockfile implementation.
if FLAGS.disable_process_locking:
return
hostname = socket.gethostname()
sentinel_re = hostname + r'\..*-(\d+$)'
lockfile_re = r'synaps-.*\.lock'
files = os.listdir(FLAGS.lock_path)
# cleanup sentinels
for filename in files:
match = re.match(sentinel_re, filename)
if match is None:
continue
pid = match.group(1)
LOG.debug(_('Found sentinel %(filename)s for pid %(pid)s' %
{'filename': filename, 'pid': pid}))
if not os.path.exists(os.path.join('/proc', pid)):
delete_if_exists(os.path.join(FLAGS.lock_path, filename))
LOG.debug(_('Cleaned sentinel %(filename)s for pid %(pid)s' %
{'filename': filename, 'pid': pid}))
# cleanup lock files
for filename in files:
match = re.match(lockfile_re, filename)
if match is None:
continue
try:
stat_info = os.stat(os.path.join(FLAGS.lock_path, filename))
except OSError as (errno, strerror):
if errno == 2: # doesn't exist
continue
else:
raise
msg = _('Found lockfile %(file)s with link count %(count)d' %
{'file': filename, 'count': stat_info.st_nlink})
LOG.debug(msg)
if stat_info.st_nlink == 1:
delete_if_exists(os.path.join(FLAGS.lock_path, filename))
msg = _('Cleaned lockfile %(file)s with link count %(count)d' %
{'file': filename, 'count': stat_info.st_nlink})
LOG.debug(msg)
def delete_if_exists(pathname):
"""delete a file, but ignore file not found error"""
try:
os.unlink(pathname)
except OSError as (errno, strerror):
if errno == 2: # doesn't exist
return
else:
raise
def execute(*cmd, **kwargs):
"""
Helper method to execute command with optional retry.
:cmd Passed to subprocess.Popen.
:process_input Send to opened process.
:check_exit_code Defaults to 0. Raise exception.ProcessExecutionError
unless program exits with this code.
:delay_on_retry True | False. Defaults to True. If set to True, wait a
short amount of time before retrying.
:attempts How many times to retry cmd.
:run_as_root True | False. Defaults to False. If set to True,
the command is prefixed by the command specified
in the root_helper FLAG.
:raises exception.Error on receiving unknown arguments
:raises exception.ProcessExecutionError
"""
process_input = kwargs.pop('process_input', None)
check_exit_code = kwargs.pop('check_exit_code', 0)
delay_on_retry = kwargs.pop('delay_on_retry', True)
attempts = kwargs.pop('attempts', 1)
run_as_root = kwargs.pop('run_as_root', False)
if len(kwargs):
raise exception.Error(_('Got unknown keyword args '
'to utils.execute: %r') % kwargs)
if run_as_root:
cmd = shlex.split(FLAGS.root_helper) + list(cmd)
cmd = map(str, cmd)
while attempts > 0:
attempts -= 1
try:
LOG.debug(_('Running cmd (subprocess): %s'), ' '.join(cmd))
_PIPE = -1 # (subprocess.PIPE) # pylint: disable=E1101
obj = subprocess.Popen(cmd,
stdin=_PIPE,
stdout=_PIPE,
stderr=_PIPE,
close_fds=True)
result = None
if process_input is not None:
result = obj.communicate(process_input)
else:
result = obj.communicate()
obj.stdin.close() # pylint: disable=E1101
_returncode = obj.returncode # pylint: disable=E1101
if _returncode:
LOG.debug(_('Result was %s') % _returncode)
if type(check_exit_code) == types.IntType \
and _returncode != check_exit_code:
(stdout, stderr) = result
raise exception.ProcessExecutionError(
exit_code=_returncode,
stdout=stdout,
stderr=stderr,
cmd=' '.join(cmd))
return result
except exception.ProcessExecutionError:
if not attempts:
raise
else:
LOG.debug(_('%r failed. Retrying.'), cmd)
if delay_on_retry:
greenthread.sleep(random.randint(20, 200) / 100.0)
finally:
# NOTE(termie): this appears to be necessary to let the subprocess
# call clean something up in between calls, without
# it two execute calls in a row hangs the second one
greenthread.sleep(0)
def extract_member_list(aws_list, key='member'):
"""
ex) if key is 'member', it will convert from
{'member': {'1': 'something1',
'2': 'something2',
'3': 'something3'}}
to
['something1', 'something2', 'something3']
"""
if not aws_list:
return []
return OrderedDict(aws_list[key]).values()
def extract_member_dict(aws_dict, key='member'):
"""
it will convert from
{'member': {'1': {'name': u'member1', 'value': u'value1'}},
{'2': {'name': u'member2', 'value': u'value2'}}}
to
{u'member1': u'value1', u'member2': u'value2'}
this is useful for processing dimension.
"""
if not aws_dict:
return {}
members = extract_member_list(aws_dict, key)
member_list = [(member['name'], member['value']) for member in members]
return dict(member_list)
def dict_to_aws(pydict):
return [{'name':k, 'value':v} for k, v in pydict.iteritems()]
def datetime_to_timestamp(dt):
if isinstance(dt, datetime.datetime):
return calendar.timegm(dt.utctimetuple())
return dt
def abspath(s):
return os.path.join(os.path.dirname(__file__), s)
def parse_server_string(server_str):
"""
Parses the given server_string and returns a list of host and port.
If it's not a combination of host part and port, the port element
is a null string. If the input is invalid expression, return a null
list.
"""
try:
# First of all, exclude pure IPv6 address (w/o port).
if netaddr.valid_ipv6(server_str):
return (server_str, '')
# Next, check if this is IPv6 address with a port number combination.
if server_str.find("]:") != -1:
(address, port) = server_str.replace('[', '', 1).split(']:')
return (address, port)
# Third, check if this is a combination of an address and a port
if server_str.find(':') == -1:
return (server_str, '')
# This must be a combination of an address and a port
(address, port) = server_str.split(':')
return (address, port)
except Exception:
LOG.debug(_('Invalid server_string: %s' % server_str))
return ('', '')
def import_object(import_str):
"""Returns an object including a module or module and class."""
try:
__import__(import_str)
return sys.modules[import_str]
except ImportError:
cls = import_class(import_str)
return cls()
def utcnow_ts():
"""Timestamp version of our utcnow function."""
return time.mktime(utcnow().timetuple())
def isotime(at=None):
"""Returns iso formatted utcnow."""
return strtime(at, ISO_TIME_FORMAT)
@contextlib.contextmanager
def tempdir(**kwargs):
tmpdir = tempfile.mkdtemp(**kwargs)
try:
yield tmpdir
finally:
try:
shutil.rmtree(tmpdir)
except OSError, e:
LOG.debug(_('Could not remove tmpdir: %s'), str(e))
def strcmp_const_time(s1, s2):
"""Constant-time string comparison.
:params s1: the first string
:params s2: the second string
:return: True if the strings are equal.
This function takes two strings and compares them. It is intended to be
used when doing a comparison for authentication purposes to help guard
against timing attacks.
"""
if len(s1) != len(s2):
return False
result = 0
for (a, b) in zip(s1, s2):
result |= ord(a) ^ ord(b)
return result == 0
def prefix_end(buf):
lastord = ord(buf[-1])
return buf[:-1] + unichr(lastord + 1)
def xhtml_escape(value):
"""Escapes a string so it is valid within XML or XHTML.
"""
return saxutils.escape(value, {'"': '"', "'": '''})
def get_python_novaclient():
nc = client.Client(FLAGS.get('admin_user'),
FLAGS.get('admin_password'),
FLAGS.get('admin_tenant_name'),
auth_url=FLAGS.get('nova_auth_url'),
endpoint_type='internalURL', no_cache=True)
return nc
def generate_metric_key(project_id, namespace, metric_name, dimensions):
if type(dimensions) is not str:
dimensions = pack_dimensions(dimensions)
elements = map(repr, [project_id, namespace, metric_name, dimensions])
metric_str = " /SEP/ ".join(elements)
return uuid.uuid5(uuid.NAMESPACE_OID, metric_str)
def pack_dimensions(dimensions):
return json.dumps(OrderedDict(sorted(dimensions.items())))
| {
"content_hash": "7279b947dc8d90301a096a09b505281e",
"timestamp": "",
"source": "github",
"line_count": 699,
"max_line_length": 80,
"avg_line_length": 34.06008583690987,
"alnum_prop": 0.5933299731182796,
"repo_name": "spcs/synaps",
"id": "7eeeee8f4ed109737d7edf38d6b3810a3d6e913e",
"size": "24666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "synaps/utils.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "16047"
},
{
"name": "Java",
"bytes": "4969"
},
{
"name": "JavaScript",
"bytes": "7403"
},
{
"name": "Python",
"bytes": "521894"
},
{
"name": "Shell",
"bytes": "29603"
}
],
"symlink_target": ""
} |
using EDDiscovery.Controls;
using EliteDangerousCore;
using EliteDangerousCore.EDSM;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace EDDiscovery.UserControls
{
public partial class UserControlJournalGrid : UserControlCommonBase, IHistoryCursor
{
private JournalFilterSelector cfs;
private BaseUtils.ConditionLists fieldfilter = new BaseUtils.ConditionLists();
private Dictionary<long, DataGridViewRow> rowsbyjournalid = new Dictionary<long, DataGridViewRow>();
private string dbFilter = "EventFilter2";
private string dbHistorySave = "EDUIHistory";
private string dbFieldFilter = "ControlFieldFilter";
public delegate void PopOut();
public PopOut OnPopOut;
private HistoryList current_historylist; // the last one set, for internal refresh purposes on sort
private string searchterms = "system:body:station:stationfaction";
public event ChangedSelectionHEHandler OnTravelSelectionChanged; // as above, different format, for certain older controls
public HistoryEntry GetCurrentHistoryEntry { get { return dataGridViewJournal.CurrentCell != null ? dataGridViewJournal.Rows[dataGridViewJournal.CurrentCell.RowIndex].Tag as HistoryEntry : null; } }
#region Init
private class Columns
{
public const int Time = 0;
public const int Event = 1;
public const int Type = 2;
public const int Text = 3;
}
private Timer searchtimer;
private Timer todotimer;
private Queue<Action> todo = new Queue<Action>();
private Queue<HistoryEntry> queuedadds = new Queue<HistoryEntry>();
private int fdropdown; // filter totals
public UserControlJournalGrid()
{
InitializeComponent();
}
public override void Init()
{
DBBaseName = "JournalGrid";
dataGridViewJournal.MakeDoubleBuffered();
dataGridViewJournal.RowTemplate.MinimumHeight = 26; // enough for the icon
dataGridViewJournal.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridViewJournal.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells; // NEW! appears to work https://msdn.microsoft.com/en-us/library/74b2wakt(v=vs.110).aspx
cfs = new JournalFilterSelector();
cfs.AddAllNone();
cfs.AddJournalExtraOptions();
cfs.AddJournalEntries();
cfs.SaveSettings += EventFilterChanged;
checkBoxCursorToTop.Checked = true;
string filter = GetSetting(dbFieldFilter, "");
if (filter.Length > 0)
fieldfilter.FromJSON(filter); // load filter
searchtimer = new Timer() { Interval = 500 };
searchtimer.Tick += Searchtimer_Tick;
todotimer = new Timer() { Interval = 10 };
todotimer.Tick += Todotimer_Tick;
discoveryform.OnHistoryChange += HistoryChanged;
discoveryform.OnNewEntry += AddNewEntry;
var enumlist = new Enum[] { EDTx.UserControlJournalGrid_ColumnTime, EDTx.UserControlJournalGrid_Event, EDTx.UserControlJournalGrid_ColumnType, EDTx.UserControlJournalGrid_ColumnText, EDTx.UserControlJournalGrid_labelTime, EDTx.UserControlJournalGrid_labelSearch };
var enumlistcms = new Enum[] { EDTx.UserControlJournalGrid_removeSortingOfColumnsToolStripMenuItem, EDTx.UserControlJournalGrid_jumpToEntryToolStripMenuItem, EDTx.UserControlJournalGrid_mapGotoStartoolStripMenuItem, EDTx.UserControlJournalGrid_viewOnEDSMToolStripMenuItem, EDTx.UserControlJournalGrid_toolStripMenuItemStartStop, EDTx.UserControlJournalGrid_runActionsOnThisEntryToolStripMenuItem, EDTx.UserControlJournalGrid_copyJournalEntryToClipboardToolStripMenuItem };
var enumlisttt = new Enum[] { EDTx.UserControlJournalGrid_comboBoxTime_ToolTip, EDTx.UserControlJournalGrid_textBoxSearch_ToolTip, EDTx.UserControlJournalGrid_buttonFilter_ToolTip, EDTx.UserControlJournalGrid_buttonExtExcel_ToolTip, EDTx.UserControlJournalGrid_checkBoxCursorToTop_ToolTip };
BaseUtils.Translator.Instance.TranslateControls(this, enumlist);
BaseUtils.Translator.Instance.TranslateToolstrip(historyContextMenu, enumlistcms, this);
BaseUtils.Translator.Instance.TranslateTooltip(toolTip, enumlisttt, this);
TravelHistoryFilter.InitaliseComboBox(comboBoxTime, GetSetting(dbHistorySave, ""));
if (TranslatorExtensions.TxDefined(EDTx.UserControlTravelGrid_SearchTerms)) // if translator has it defined, use it (share with travel grid)
searchterms = searchterms.TxID(EDTx.UserControlTravelGrid_SearchTerms);
}
public override void LoadLayout()
{
dataGridViewJournal.RowTemplate.MinimumHeight = Math.Max(28, Font.ScalePixels(28));
DGVLoadColumnLayout(dataGridViewJournal);
}
public override void Closing()
{
todo.Clear();
todotimer.Stop();
searchtimer.Stop();
DGVSaveColumnLayout(dataGridViewJournal);
discoveryform.OnHistoryChange -= HistoryChanged;
discoveryform.OnNewEntry -= AddNewEntry;
searchtimer.Dispose();
}
#endregion
#region Display
public override void InitialDisplay()
{
HistoryChanged(discoveryform.history);
}
private void HistoryChanged(HistoryList hl)
{
Display(hl, false);
}
private void Display(HistoryList hl, bool disablesorting )
{
todo.Clear(); // ensure in a quiet state
queuedadds.Clear();
todotimer.Stop();
if (hl == null) // just for safety
return;
this.dataGridViewJournal.Cursor = Cursors.WaitCursor;
buttonExtExcel.Enabled = buttonFilter.Enabled = buttonField.Enabled = false;
current_historylist = hl;
Tuple<long, int> pos = CurrentGridPosByJID();
SortOrder sortorder = dataGridViewJournal.SortOrder;
int sortcol = dataGridViewJournal.SortedColumn?.Index ?? -1;
if (sortcol >= 0 && disablesorting)
{
dataGridViewJournal.Columns[sortcol].HeaderCell.SortGlyphDirection = SortOrder.None;
sortcol = -1;
}
var filter = (TravelHistoryFilter)comboBoxTime.SelectedItem ?? TravelHistoryFilter.NoFilter;
List<HistoryEntry> result = filter.Filter(hl.EntryOrder());
fdropdown = hl.Count - result.Count();
dataGridViewJournal.Rows.Clear();
rowsbyjournalid.Clear();
dataGridViewJournal.Columns[0].HeaderText = EDDConfig.Instance.GetTimeTitle();
List<HistoryEntry[]> chunks = new List<HistoryEntry[]>();
int chunksize = 500;
for (int i = 0; i < result.Count; i += chunksize, chunksize = 2000)
{
HistoryEntry[] chunk = new HistoryEntry[i + chunksize > result.Count ? result.Count - i : chunksize];
result.CopyTo(i, chunk, 0, chunk.Length);
chunks.Add(chunk);
}
var sst = new BaseUtils.StringSearchTerms(textBoxSearch.Text, searchterms);
HistoryEventFilter hef = new HistoryEventFilter(GetSetting(dbFilter, "All"), fieldfilter, discoveryform.Globals);
System.Diagnostics.Stopwatch swtotal = new System.Diagnostics.Stopwatch(); swtotal.Start();
//int lrowno = 0;
foreach (var chunk in chunks)
{
todo.Enqueue(() =>
{
//System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start();
List<DataGridViewRow> rowstoadd = new List<DataGridViewRow>();
foreach (var item in chunk)
{
var row = CreateHistoryRow(item, sst, hef);
if (row != null)
{
//row.Cells[2].Value = (lrowno++).ToString() + " " + item.Journalid + " " + (string)row.Cells[2].Value;
rowstoadd.Add(row);
}
}
dataGridViewJournal.Rows.AddRange(rowstoadd.ToArray()); // much faster to send in one chunk
// System.Diagnostics.Debug.WriteLine("J Chunk Load in " + sw.ElapsedMilliseconds);
if (dataGridViewJournal.MoveToSelection(rowsbyjournalid, ref pos, false))
FireChangeSelection();
});
}
todo.Enqueue(() =>
{
System.Diagnostics.Debug.WriteLine(BaseUtils.AppTicks.TickCount + " JG TOTAL TIME " + swtotal.ElapsedMilliseconds);
UpdateToolTipsForFilter();
if (dataGridViewJournal.MoveToSelection(rowsbyjournalid, ref pos, true))
FireChangeSelection();
if (sortcol >= 0)
{
dataGridViewJournal.Sort(dataGridViewJournal.Columns[sortcol], (sortorder == SortOrder.Descending) ? ListSortDirection.Descending : ListSortDirection.Ascending);
dataGridViewJournal.Columns[sortcol].HeaderCell.SortGlyphDirection = sortorder;
}
this.dataGridViewJournal.Cursor = Cursors.Default;
buttonExtExcel.Enabled = buttonFilter.Enabled = buttonField.Enabled = true;
while (queuedadds.Count > 0) // finally, dequeue any adds added
{
System.Diagnostics.Debug.WriteLine("JG Dequeue paused adds");
AddEntry(queuedadds.Dequeue());
}
});
todotimer.Start();
}
private void Todotimer_Tick(object sender, EventArgs e)
{
if (todo.Count != 0)
{
var act = todo.Dequeue();
act();
}
else
{
todotimer.Stop();
}
}
private void AddNewEntry(HistoryEntry he, HistoryList hl) // on new entry from discovery system
{
if (todotimer.Enabled) // if we have the todotimer running.. we add to the queue. better than the old loadcomplete, no race conditions
{
queuedadds.Enqueue(he);
}
else
{
AddEntry(he);
}
}
private void AddEntry(HistoryEntry he)
{
var sst = new BaseUtils.StringSearchTerms(textBoxSearch.Text, searchterms);
HistoryEventFilter hef = new HistoryEventFilter(GetSetting(dbFilter, "All"), fieldfilter, discoveryform.Globals);
var row = CreateHistoryRow(he, sst, hef); // we might be filtered out by search
if (row != null)
{
dataGridViewJournal.Rows.Insert(0, row);
var filter = (TravelHistoryFilter)comboBoxTime.SelectedItem ?? TravelHistoryFilter.NoFilter;
if (filter.MaximumNumberOfItems != null) // this one won't remove the latest one
{
for (int r = dataGridViewJournal.Rows.Count - 1; r >= filter.MaximumNumberOfItems; r--)
{
dataGridViewJournal.Rows.RemoveAt(r);
}
}
if (checkBoxCursorToTop.Checked) // Move focus to first row
{
dataGridViewJournal.ClearSelection();
dataGridViewJournal.SetCurrentAndSelectAllCellsOnRow(0); // its the current cell which needs to be set, moves the row marker as well
FireChangeSelection();
}
}
}
private DataGridViewRow CreateHistoryRow(HistoryEntry he, BaseUtils.StringSearchTerms search, HistoryEventFilter hef)
{
if (!hef.IsIncluded(he))
return null;
DateTime time = EDDConfig.Instance.ConvertTimeToSelectedFromUTC(he.EventTimeUTC);
he.FillInformation(out string EventDescription, out string EventDetailedInfo);
string detail = EventDescription;
detail = detail.AppendPrePad(EventDetailedInfo.LineLimit(15,Environment.NewLine + "..."), Environment.NewLine);
if (search.Enabled)
{
bool matched = false;
if (search.Terms[0] != null)
{
string timestr = time.ToString();
int rown = EDDConfig.Instance.OrderRowsInverted ? he.EntryNumber : (discoveryform.history.Count - he.EntryNumber + 1);
string entryrow = rown.ToStringInvariant();
matched = timestr.IndexOf(search.Terms[0], StringComparison.InvariantCultureIgnoreCase) >= 0 ||
he.EventSummary.IndexOf(search.Terms[0], StringComparison.InvariantCultureIgnoreCase) >= 0 ||
detail.IndexOf(search.Terms[0], StringComparison.InvariantCultureIgnoreCase) >= 0 ||
entryrow.IndexOf(search.Terms[0], StringComparison.InvariantCultureIgnoreCase) >= 0;
}
if (!matched && search.Terms[1] != null) // system
matched = he.System.Name.WildCardMatch(search.Terms[1], true);
if (!matched && search.Terms[2] != null) // body
matched = he.Status.BodyName?.WildCardMatch(search.Terms[2], true) ?? false;
if (!matched && search.Terms[3] != null) // station
matched = he.Status.StationName?.WildCardMatch(search.Terms[3], true) ?? false;
if (!matched && search.Terms[4] != null) // stationfaction
matched = he.Status.StationFaction?.WildCardMatch(search.Terms[4], true) ?? false;
if (!matched)
return null;
}
var rw = dataGridViewJournal.RowTemplate.Clone() as DataGridViewRow;
rw.CreateCells(dataGridViewJournal, time, "", he.EventSummary, detail);
rw.Tag = he;
rowsbyjournalid[he.Journalid] = rw;
return rw;
}
private void UpdateToolTipsForFilter()
{
string ms = string.Format(" showing {0} original {1}".T(EDTx.UserControlJournalGrid_TT1), dataGridViewJournal.Rows.Count, current_historylist?.Count ?? 0);
comboBoxTime.SetTipDynamically(toolTip, fdropdown > 0 ? string.Format("Filtered {0}".T(EDTx.UserControlJournalGrid_TTFilt1), fdropdown + ms) : "Select the entries by age, ".T(EDTx.UserControlJournalGrid_TTSelAge) + ms);
}
#endregion
#region Buttons
private void buttonFilter_Click(object sender, EventArgs e)
{
Button b = sender as Button;
cfs.Open(GetSetting(dbFilter,"All"), b, this.FindForm());
}
private void EventFilterChanged(string newset, Object e)
{
string filters = GetSetting(dbFilter, "All");
if (filters != newset)
{
PutSetting(dbFilter, newset);
HistoryChanged(current_historylist);
}
}
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
searchtimer.Stop();
searchtimer.Start();
}
private void Searchtimer_Tick(object sender, EventArgs e)
{
searchtimer.Stop();
Display(current_historylist, false);
}
private void comboBoxJournalWindow_SelectedIndexChanged(object sender, EventArgs e)
{
PutSetting(dbHistorySave, comboBoxTime.Text);
HistoryChanged(current_historylist);
}
private void buttonField_Click(object sender, EventArgs e)
{
BaseUtils.ConditionLists res = HistoryFilterHelpers.ShowDialog(FindForm(), fieldfilter, discoveryform, "Journal: Filter out fields".T(EDTx.UserControlJournalGrid_JHF));
if ( res != null )
{
fieldfilter = res;
PutSetting(dbFieldFilter, fieldfilter.GetJSON());
HistoryChanged(current_historylist);
}
}
#endregion
private void dataGridViewJournal_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataGridView grid = sender as DataGridView;
PaintHelpers.PaintEventColumn(sender as DataGridView, e,
discoveryform.history.Count, (HistoryEntry)dataGridViewJournal.Rows[e.RowIndex].Tag,
Columns.Event, false);
}
#region Mouse Clicks
private void historyContextMenu_Opening(object sender, CancelEventArgs e)
{
mapGotoStartoolStripMenuItem.Enabled = (rightclicksystem != null && rightclicksystem.System.HasCoordinate);
viewOnEDSMToolStripMenuItem.Enabled = (rightclicksystem != null);
removeSortingOfColumnsToolStripMenuItem.Enabled = dataGridViewJournal.SortedColumn != null;
jumpToEntryToolStripMenuItem.Enabled = dataGridViewJournal.Rows.Count > 0;
}
HistoryEntry rightclicksystem = null;
HistoryEntry leftclicksystem = null;
private void dataGridViewJournal_MouseDown(object sender, MouseEventArgs e)
{
rightclicksystem = dataGridViewJournal.RightClickRowValid ? (HistoryEntry)dataGridViewJournal.Rows[dataGridViewJournal.RightClickRow].Tag : null;
leftclicksystem = dataGridViewJournal.LeftClickRowValid ? (HistoryEntry)dataGridViewJournal.Rows[dataGridViewJournal.LeftClickRow].Tag : null;
}
private void dataGridViewJournal_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridViewJournal.LeftClickRowValid) // Click expands it..
{
ExtendedControls.InfoForm info = new ExtendedControls.InfoForm();
leftclicksystem.FillInformation(out string EventDescription, out string EventDetailedInfo);
string infodetailed = EventDescription.AppendPrePad(EventDetailedInfo, Environment.NewLine);
info.Info( (EDDConfig.Instance.ConvertTimeToSelectedFromUTC(leftclicksystem.EventTimeUTC)) + ": " + leftclicksystem.EventSummary,
FindForm().Icon, infodetailed);
info.Size = new Size(1200, 800);
info.Show(FindForm());
}
}
private void dataGridViewJournal_CellClick(object sender, DataGridViewCellEventArgs e)
{
FireChangeSelection();
}
private void mapGotoStartoolStripMenuItem_Click(object sender, EventArgs e)
{
discoveryform.Open3DMap(rightclicksystem?.System);
}
private void viewOnEDSMToolStripMenuItem_Click(object sender, EventArgs e)
{
EDSMClass edsm = new EDSMClass();
if (!edsm.ShowSystemInEDSM(rightclicksystem.System.Name))
ExtendedControls.MessageBoxTheme.Show(this.FindForm(), "System could not be found - has not been synched or EDSM is unavailable".T(EDTx.UserControlJournalGrid_NotSynced));
}
private void toolStripMenuItemStartStop_Click(object sender, EventArgs e)
{
if (rightclicksystem != null)
{
discoveryform.history.SetStartStop(rightclicksystem);
discoveryform.RefreshHistoryAsync();
}
}
private void runActionsOnThisEntryToolStripMenuItem_Click(object sender, EventArgs e)
{
if (rightclicksystem != null)
discoveryform.ActionRunOnEntry(rightclicksystem, Actions.ActionEventEDList.UserRightClick(rightclicksystem));
}
private void copyJournalEntryToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
if (rightclicksystem != null && rightclicksystem.journalEntry != null)
{
string json = rightclicksystem.journalEntry.GetJsonString();
if (json != null)
{
SetClipboardText(json);
}
}
}
private void removeSortingOfColumnsToolStripMenuItem_Click(object sender, EventArgs e)
{
Display(current_historylist, true);
}
#endregion
Tuple<long, int> CurrentGridPosByJID() // Returns JID, column index. JID = -1 if cell is not defined
{
long jid = (dataGridViewJournal.CurrentCell != null) ? ((HistoryEntry)(dataGridViewJournal.Rows[dataGridViewJournal.CurrentCell.RowIndex].Tag)).Journalid : -1;
int cellno = (dataGridViewJournal.CurrentCell != null) ? dataGridViewJournal.CurrentCell.ColumnIndex : 0;
return new Tuple<long, int>(jid, cellno);
}
public void GotoPosByJID(long jid)
{
int rowno = DataGridViewControlHelpersStaticFunc.FindGridPosByID(rowsbyjournalid, jid, true);
if (rowno >= 0)
{
dataGridViewJournal.SetCurrentAndSelectAllCellsOnRow(rowno);
dataGridViewJournal.Rows[rowno].Selected = true;
FireChangeSelection();
}
}
public void FireChangeSelection()
{
System.Diagnostics.Debug.WriteLine("JG Fire Change Sel");
if (dataGridViewJournal.CurrentCell != null)
{
int row = dataGridViewJournal.CurrentCell.RowIndex;
OnTravelSelectionChanged?.Invoke(dataGridViewJournal.Rows[row].Tag as HistoryEntry, current_historylist, true);
}
}
private void jumpToEntryToolStripMenuItem_Click(object sender, EventArgs e)
{
int curi = rightclicksystem != null ? (EDDConfig.Instance.OrderRowsInverted ? rightclicksystem.EntryNumber : (discoveryform.history.Count - rightclicksystem.EntryNumber + 1)) : 0;
int selrow = dataGridViewJournal.JumpToDialog(this.FindForm(), curi, r =>
{
HistoryEntry he = r.Tag as HistoryEntry;
return EDDConfig.Instance.OrderRowsInverted ? he.EntryNumber : (discoveryform.history.Count - he.EntryNumber + 1);
});
if (selrow >= 0)
{
dataGridViewJournal.ClearSelection();
dataGridViewJournal.SetCurrentAndSelectAllCellsOnRow(selrow);
FireChangeSelection();
}
}
private void dataGridViewJournal_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
if (e.Column.Index == 0)
{
e.SortDataGridViewColumnDate();
}
}
#region Excel
private void buttonExtExcel_Click(object sender, EventArgs e)
{
Forms.ExportForm frm = new Forms.ExportForm();
frm.Init(false, new string[] { "Export Current View", "Export as Journals" },
new string[] { "CSV export| *.csv", "Journal Export|*.log" },
new Forms.ExportForm.ShowFlags[] { Forms.ExportForm.ShowFlags.None, Forms.ExportForm.ShowFlags.DisableCVS });
if (frm.ShowDialog(this.FindForm()) == DialogResult.OK)
{
if (frm.SelectedIndex == 1)
{
try
{
using (StreamWriter writer = new StreamWriter(frm.Path))
{
foreach(DataGridViewRow dgvr in dataGridViewJournal.Rows)
{
HistoryEntry he = dgvr.Tag as HistoryEntry;
if (dgvr.Visible && he.EventTimeUTC.CompareTo(frm.StartTimeUTC) >= 0 && he.EventTimeUTC.CompareTo(frm.EndTimeUTC) <= 0)
{
string forExport = he.journalEntry.GetJsonString().Replace("\r\n", "");
if (forExport != null)
{
forExport = System.Text.RegularExpressions.Regex.Replace(forExport, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1");
writer.Write(forExport);
writer.WriteLine();
}
}
}
}
if (frm.AutoOpen)
{
try
{
System.Diagnostics.Process.Start(frm.Path);
}
catch
{
ExtendedControls.MessageBoxTheme.Show(FindForm(), "Failed to open " + frm.Path, "Warning".TxID(EDTx.Warning), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
catch
{
ExtendedControls.MessageBoxTheme.Show(this.FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
BaseUtils.CSVWriteGrid grd = new BaseUtils.CSVWriteGrid();
grd.SetCSVDelimiter(frm.Comma);
grd.GetLineStatus += delegate (int r)
{
if (r < dataGridViewJournal.Rows.Count)
{
HistoryEntry he = dataGridViewJournal.Rows[r].Tag as HistoryEntry;
return (dataGridViewJournal.Rows[r].Visible &&
he.EventTimeUTC.CompareTo(frm.StartTimeUTC) >= 0 &&
he.EventTimeUTC.CompareTo(frm.EndTimeUTC) <= 0) ? BaseUtils.CSVWriteGrid.LineStatus.OK : BaseUtils.CSVWriteGrid.LineStatus.Skip;
}
else
return BaseUtils.CSVWriteGrid.LineStatus.EOF;
};
grd.GetLine += delegate (int r)
{
DataGridViewRow rw = dataGridViewJournal.Rows[r];
return new Object[] { rw.Cells[0].Value, rw.Cells[2].Value, rw.Cells[3].Value };
};
grd.GetHeader += delegate (int c)
{
return (c < 3 && frm.IncludeHeader) ? dataGridViewJournal.Columns[c + ((c > 0) ? 1 : 0)].HeaderText : null;
};
grd.WriteGrid(frm.Path, frm.AutoOpen, FindForm());
}
}
}
#endregion
}
}
| {
"content_hash": "fb3339d9b98fa725e15e61fac70f3515",
"timestamp": "",
"source": "github",
"line_count": 636,
"max_line_length": 484,
"avg_line_length": 43.20754716981132,
"alnum_prop": 0.5791848617176129,
"repo_name": "EDDiscovery/EDDiscovery",
"id": "e0cc9a3dd2114563acde976b6d64ed1a64451d62",
"size": "28164",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EDDiscovery/UserControls/History/UserControlJournalGrid.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2624"
},
{
"name": "C#",
"bytes": "2820878"
},
{
"name": "CSS",
"bytes": "20655"
},
{
"name": "HTML",
"bytes": "10288"
},
{
"name": "Inno Setup",
"bytes": "11026"
},
{
"name": "JavaScript",
"bytes": "105342"
},
{
"name": "Rich Text Format",
"bytes": "65100"
}
],
"symlink_target": ""
} |
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Configuration;
using Akka.Actor;
using Akka.Configuration;
using Akka.Configuration.Hocon;
namespace Samples.Cluster.Simple
{
class Program
{
private static void Main(string[] args)
{
StartUp(args.Length == 0 ? new String[] { "2551", "2552", "0" } : args);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
public static void StartUp(string[] ports)
{
var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");
foreach (var port in ports)
{
//Override the configuration of the port
var config =
ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port)
.WithFallback(section.AkkaConfig);
//create an Akka system
var system = ActorSystem.Create("ClusterSystem", config);
//create an actor that handles cluster domain events
system.ActorOf(Props.Create(typeof(SimpleClusterListener)), "clusterListener");
}
}
}
}
| {
"content_hash": "8a6c853c52df8a0daba69779572bb8cb",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 95,
"avg_line_length": 35.54545454545455,
"alnum_prop": 0.539002557544757,
"repo_name": "eloraiby/akka.net",
"id": "6145e7f60de53778f515e7b138e70c4f5da2848c",
"size": "1566",
"binary": false,
"copies": "4",
"ref": "refs/heads/dev",
"path": "src/examples/Cluster/Samples.Cluster.Simple/Program.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1387"
},
{
"name": "C#",
"bytes": "7405797"
},
{
"name": "F#",
"bytes": "120261"
},
{
"name": "Protocol Buffer",
"bytes": "37516"
},
{
"name": "Shell",
"bytes": "1740"
}
],
"symlink_target": ""
} |
package java.awt.dnd;
import gnu.classpath.NotImplementedException;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.peer.DragSourceContextPeer;
import java.io.Serializable;
import java.util.TooManyListenersException;
/**
* @since 1.2
*/
public class DragSourceContext
implements DragSourceListener, DragSourceMotionListener, Serializable
{
/**
* Compatible with JDK 1.2+
*/
static final long serialVersionUID = -115407898692194719L;
protected static final int DEFAULT = 0;
protected static final int ENTER = 1;
protected static final int OVER = 2;
protected static final int CHANGED = 3;
private DragSourceContextPeer peer;
private Cursor cursor;
private Transferable transferable;
private DragGestureEvent trigger;
private DragSourceListener dragSourceListener;
private boolean useCustomCursor;
private int sourceActions;
private Image image;
private Point offset;
/**
* Initializes a drag source context.
*
* @exception IllegalArgumentException If Component or DragSource of trigger
* are null, the drag action for the trigger event is DnDConstants.ACTION_NONE
* or if the source actions for the DragGestureRecognizer associated with the
* trigger event are equal to DnDConstants.ACTION_NONE.
* @exception NullPointerException If peer, trans or trigger is null or if the
* image is not null but the offset is.
*/
public DragSourceContext (DragSourceContextPeer peer,
DragGestureEvent trigger, Cursor cursor,
Image image, Point offset, Transferable trans,
DragSourceListener dsl)
{
if (peer == null
|| trigger == null || trans == null
|| (image != null && offset == null))
throw new NullPointerException ();
if (trigger.getComponent () == null
|| trigger.getDragSource () == null
|| trigger.getDragAction () == DnDConstants.ACTION_NONE
|| trigger.getSourceAsDragGestureRecognizer ()
.getSourceActions () == DnDConstants.ACTION_NONE)
throw new IllegalArgumentException ();
this.peer = peer;
this.trigger = trigger;
this.cursor = cursor;
this.image = image;
this.offset = offset;
this.transferable = trans;
this.dragSourceListener = dsl;
this.sourceActions = trigger.getSourceAsDragGestureRecognizer().getSourceActions();
setCursor(cursor);
updateCurrentCursor(trigger.getDragAction(), sourceActions, DEFAULT);
}
/**
* Returns the DragSource object associated with the
* DragGestureEvent.
*
* @return the DragSource associated with the trigger.
*/
public DragSource getDragSource()
{
return trigger.getDragSource ();
}
/**
* Returns the component associated with this.
*
* @return the component associated with the trigger.
*/
public Component getComponent()
{
return trigger.getComponent ();
}
/**
* Gets the trigger associated with this.
*
* @return the trigger.
*/
public DragGestureEvent getTrigger()
{
return trigger;
}
/**
* Returns the source actions for the DragGestureRecognizer.
*
* @return the source actions for DragGestureRecognizer.
*/
public int getSourceActions()
{
if (sourceActions == 0)
sourceActions = trigger.getSourceAsDragGestureRecognizer().getSourceActions();
return sourceActions;
}
/**
* Sets the cursor for this drag operation to the specified cursor.
*
* @param cursor c - the Cursor to use, or null to use the default drag
* cursor.
*/
public void setCursor(Cursor cursor)
{
if (cursor == null)
useCustomCursor = false;
else
useCustomCursor = true;
this.cursor = cursor;
peer.setCursor(cursor);
}
/**
* Returns the current cursor or null if the default
* drag cursor is used.
*
* @return the current cursor or null.
*/
public Cursor getCursor()
{
return cursor;
}
/**
* Adds a <code>DragSourceListener</code>.
*
* @exception TooManyListenersException If a <code>DragSourceListener</code>
* has already been added.
*/
public void addDragSourceListener (DragSourceListener dsl)
throws TooManyListenersException
{
if (dragSourceListener != null)
throw new TooManyListenersException ();
dragSourceListener = dsl;
}
public void removeDragSourceListener (DragSourceListener dsl)
{
if (dragSourceListener == dsl)
dragSourceListener = null;
}
/**
* This function tells the peer that the DataFlavors have been modified.
*/
public void transferablesFlavorsChanged()
{
peer.transferablesFlavorsChanged();
}
/**
* Calls dragEnter on the listeners registered with this
* and with the DragSource.
*
* @param e - the DragSourceDragEvent
*/
public void dragEnter(DragSourceDragEvent e)
{
if (dragSourceListener != null)
dragSourceListener.dragEnter(e);
DragSource ds = getDragSource();
DragSourceListener[] dsl = ds.getDragSourceListeners();
for (int i = 0; i < dsl.length; i++)
dsl[i].dragEnter(e);
updateCurrentCursor(e.getDropAction(), e.getTargetActions(), ENTER);
}
/**
* Calls dragOver on the listeners registered with this
* and with the DragSource.
*
* @param e - the DragSourceDragEvent
*/
public void dragOver(DragSourceDragEvent e)
{
if (dragSourceListener != null)
dragSourceListener.dragOver(e);
DragSource ds = getDragSource();
DragSourceListener[] dsl = ds.getDragSourceListeners();
for (int i = 0; i < dsl.length; i++)
dsl[i].dragOver(e);
updateCurrentCursor(e.getDropAction(), e.getTargetActions(), OVER);
}
/**
* Calls dragExit on the listeners registered with this
* and with the DragSource.
*
* @param e - the DragSourceEvent
*/
public void dragExit(DragSourceEvent e)
{
if (dragSourceListener != null)
dragSourceListener.dragExit(e);
DragSource ds = getDragSource();
DragSourceListener[] dsl = ds.getDragSourceListeners();
for (int i = 0; i < dsl.length; i++)
dsl[i].dragExit(e);
updateCurrentCursor(0, 0, DEFAULT);
}
/**
* Calls dropActionChanged on the listeners registered with this
* and with the DragSource.
*
* @param e - the DragSourceDragEvent
*/
public void dropActionChanged(DragSourceDragEvent e)
{
if (dragSourceListener != null)
dragSourceListener.dropActionChanged(e);
DragSource ds = getDragSource();
DragSourceListener[] dsl = ds.getDragSourceListeners();
for (int i = 0; i < dsl.length; i++)
dsl[i].dropActionChanged(e);
updateCurrentCursor(e.getDropAction(), e.getTargetActions(), CHANGED);
}
/**
* Calls dragDropEnd on the listeners registered with this
* and with the DragSource.
*
* @param e - the DragSourceDropEvent
*/
public void dragDropEnd(DragSourceDropEvent e)
{
if (dragSourceListener != null)
dragSourceListener.dragDropEnd(e);
DragSource ds = getDragSource();
DragSourceListener[] dsl = ds.getDragSourceListeners();
for (int i = 0; i < dsl.length; i++)
dsl[i].dragDropEnd(e);
}
/**
* Calls dragMouseMoved on the listeners registered with the DragSource.
*
* @param e - the DragSourceDragEvent
*/
public void dragMouseMoved(DragSourceDragEvent e)
{
DragSource ds = getDragSource();
DragSourceMotionListener[] dsml = ds.getDragSourceMotionListeners();
for (int i = 0; i < dsml.length; i++)
dsml[i].dragMouseMoved(e);
}
/**
* Returns the Transferable set with this object.
*
* @return the transferable.
*/
public Transferable getTransferable()
{
return transferable;
}
/**
* This function sets the drag cursor for the specified operation, actions and
* status if the default drag cursor is active. Otherwise, the cursor is not
* updated in any way.
*
* @param dropOp - the current operation.
* @param targetAct - the supported actions.
* @param status - the status of the cursor (constant).
*/
protected void updateCurrentCursor(int dropOp, int targetAct, int status)
throws NotImplementedException
{
// FIXME: Not implemented fully
if (!useCustomCursor)
{
Cursor cursor = null;
switch (status)
{
case ENTER:
break;
case CHANGED:
break;
case OVER:
break;
default:
break;
}
this.cursor = cursor;
peer.setCursor(cursor);
}
}
} // class DragSourceContext
| {
"content_hash": "536ca8eb5cd6f06f0ebcd6d09279f926",
"timestamp": "",
"source": "github",
"line_count": 330,
"max_line_length": 87,
"avg_line_length": 26.696969696969695,
"alnum_prop": 0.6623155505107832,
"repo_name": "shaotuanchen/sunflower_exp",
"id": "1fee5c0c3043faacbc821f83010fad1f9bb73b09",
"size": "10541",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "tools/source/gcc-4.2.4/libjava/classpath/java/awt/dnd/DragSourceContext.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "459993"
},
{
"name": "Awk",
"bytes": "6562"
},
{
"name": "Batchfile",
"bytes": "9028"
},
{
"name": "C",
"bytes": "50326113"
},
{
"name": "C++",
"bytes": "2040239"
},
{
"name": "CSS",
"bytes": "2355"
},
{
"name": "Clarion",
"bytes": "2484"
},
{
"name": "Coq",
"bytes": "61440"
},
{
"name": "DIGITAL Command Language",
"bytes": "69150"
},
{
"name": "Emacs Lisp",
"bytes": "186910"
},
{
"name": "Fortran",
"bytes": "5364"
},
{
"name": "HTML",
"bytes": "2171356"
},
{
"name": "JavaScript",
"bytes": "27164"
},
{
"name": "Logos",
"bytes": "159114"
},
{
"name": "M",
"bytes": "109006"
},
{
"name": "M4",
"bytes": "100614"
},
{
"name": "Makefile",
"bytes": "5409865"
},
{
"name": "Mercury",
"bytes": "702"
},
{
"name": "Module Management System",
"bytes": "56956"
},
{
"name": "OCaml",
"bytes": "253115"
},
{
"name": "Objective-C",
"bytes": "57800"
},
{
"name": "Papyrus",
"bytes": "3298"
},
{
"name": "Perl",
"bytes": "70992"
},
{
"name": "Perl 6",
"bytes": "693"
},
{
"name": "PostScript",
"bytes": "3440120"
},
{
"name": "Python",
"bytes": "40729"
},
{
"name": "Redcode",
"bytes": "1140"
},
{
"name": "Roff",
"bytes": "3794721"
},
{
"name": "SAS",
"bytes": "56770"
},
{
"name": "SRecode Template",
"bytes": "540157"
},
{
"name": "Shell",
"bytes": "1560436"
},
{
"name": "Smalltalk",
"bytes": "10124"
},
{
"name": "Standard ML",
"bytes": "1212"
},
{
"name": "TeX",
"bytes": "385584"
},
{
"name": "WebAssembly",
"bytes": "52904"
},
{
"name": "Yacc",
"bytes": "510934"
}
],
"symlink_target": ""
} |
require "inspec"
require "kitchen/terraform/system_bastion_host_resolver"
require "kitchen/terraform/system_inspec_map"
require "rubygems"
module Kitchen
module Terraform
# InSpecOptionsMapper is the class of objects which build Inspec options.
class InSpecOptionsFactory
class << self
# #inputs_key provides a key for InSpec profile inputs which depends on the version of InSpec.
#
# @return [Symbol] if the version is less than 4.3.2, :attributes; else, :inputs.
def inputs_key
if ::Gem::Requirement.new("< 4.3.2").satisfied_by? ::Gem::Version.new ::Inspec::VERSION
:attributes
else
:inputs
end
end
end
# #build creates a mapping of InSpec options. Most key-value pairs are derived from the configuration attributes
# of a system; some key-value pairs are hard-coded.
#
# @param attributes [Hash] the attributes to be added to the InSpec options.
# @param system_configuration_attributes [Hash] the configuration attributes of a system.
# @raise [Kitchen::ClientError] if the system bastion host fails to be resolved.
# @return [Hash] a mapping of InSpec options.
def build(attributes:, system_configuration_attributes:)
map_system_to_inspec system_configuration_attributes: system_configuration_attributes
options.store self.class.inputs_key, attributes
resolve_bastion_host system_configuration_attributes: system_configuration_attributes
options
end
# #initialize prepares a new instance of the class.
#
# @param outputs [Hash] the Terraform output variables.
# @return [Kitchen::Terraform::InSpecOptionsFactory]
def initialize(outputs:)
self.options = { "distinct_exit" => false }
self.system_bastion_host_resolver = ::Kitchen::Terraform::SystemBastionHostResolver.new outputs: outputs
self.system_inspec_map = ::Kitchen::Terraform::SYSTEM_INSPEC_MAP.dup
end
private
attr_accessor :options, :system_bastion_host_resolver, :system_inspec_map
def map_system_to_inspec(system_configuration_attributes:)
system_configuration_attributes.lazy.select do |attribute_name, _|
system_inspec_map.key?(attribute_name)
end.each do |attribute_name, attribute_value|
options.store system_inspec_map.fetch(attribute_name), attribute_value
end
end
def resolve_bastion_host(system_configuration_attributes:)
system_bastion_host_resolver.resolve(
bastion_host: system_configuration_attributes.fetch(:bastion_host, ""),
bastion_host_output: system_configuration_attributes.fetch(:bastion_host_output, ""),
) do |bastion_host:|
options.store :bastion_host, bastion_host
end
end
end
end
end
| {
"content_hash": "756e52df83f78618c687383381cd4d2b",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 118,
"avg_line_length": 41.214285714285715,
"alnum_prop": 0.6790294627383016,
"repo_name": "newcontext-oss/kitchen-terraform",
"id": "19211560787adb4664417b425a46cf13cef36c8f",
"size": "3500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/kitchen/terraform/inspec_options_factory.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3162"
},
{
"name": "HCL",
"bytes": "14785"
},
{
"name": "HTML",
"bytes": "92815"
},
{
"name": "JavaScript",
"bytes": "32"
},
{
"name": "Ruby",
"bytes": "441107"
},
{
"name": "SCSS",
"bytes": "147919"
},
{
"name": "Shell",
"bytes": "364"
}
],
"symlink_target": ""
} |
FROM balenalib/solidrun-imx6-ubuntu:focal-build
ENV GO_VERSION 1.17.7
RUN mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-armv7hf.tar.gz" \
&& echo "e4f33e7e78f96024d30ff6bf8d2b86329fc04df1b411a8bd30a82dbe60f408ba go$GO_VERSION.linux-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-armv7hf.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/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
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 v7 \nOS: Ubuntu focal \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.17.7 \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 | {
"content_hash": "5af3ac72a2f4378d9d145395c007bad9",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 673,
"avg_line_length": 64.7741935483871,
"alnum_prop": 0.727589641434263,
"repo_name": "resin-io-library/base-images",
"id": "181258de6d53347a4ce56bd45cf72870961994f9",
"size": "2029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/golang/solidrun-imx6/ubuntu/focal/1.17.7/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
<!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_112) on Wed May 31 18:08:09 EDT 2017 -->
<title>Uses of Class brown.tracingplane.baggageprotocol.BagKey.Keyed</title>
<meta name="date" content="2017-05-31">
<link rel="stylesheet" type="text/css" href="../../../../javadoc-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 brown.tracingplane.baggageprotocol.BagKey.Keyed";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-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?brown/tracingplane/baggageprotocol/class-use/BagKey.Keyed.html" target="_top">Frames</a></li>
<li><a href="BagKey.Keyed.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 brown.tracingplane.baggageprotocol.BagKey.Keyed" class="title">Uses of Class<br>brown.tracingplane.baggageprotocol.BagKey.Keyed</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#brown.tracingplane.baggageprotocol">brown.tracingplane.baggageprotocol</a></td>
<td class="colLast">
<div class="block">
Defines an encoding scheme for nested data structures using atoms.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="brown.tracingplane.baggageprotocol">
<!-- -->
</a>
<h3>Uses of <a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> in <a href="../../../../brown/tracingplane/baggageprotocol/package-summary.html">brown.tracingplane.baggageprotocol</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../brown/tracingplane/baggageprotocol/package-summary.html">brown.tracingplane.baggageprotocol</a> with parameters of type <a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static java.nio.ByteBuffer</code></td>
<td class="colLast"><span class="typeNameLabel">HeaderSerialization.</span><code><span class="memberNameLink"><a href="../../../../brown/tracingplane/baggageprotocol/HeaderSerialization.html#serialize-brown.tracingplane.baggageprotocol.BagKey.Keyed-int-">serialize</a></span>(<a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> bagKey,
int level)</code>
<div class="block">Serialize the header atom, including prefix byte, for the provided bagKey and level</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><span class="typeNameLabel">HeaderSerialization.</span><code><span class="memberNameLink"><a href="../../../../brown/tracingplane/baggageprotocol/HeaderSerialization.html#serializedSize-brown.tracingplane.baggageprotocol.BagKey.Keyed-">serializedSize</a></span>(<a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> bagKey)</code>
<div class="block">Calculates the serialized size of a Keyed header atom including its prefix</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.nio.ByteBuffer</code></td>
<td class="colLast"><span class="typeNameLabel">HeaderSerialization.</span><code><span class="memberNameLink"><a href="../../../../brown/tracingplane/baggageprotocol/HeaderSerialization.html#serializePayload-brown.tracingplane.baggageprotocol.BagKey.Keyed-">serializePayload</a></span>(<a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> bagKey)</code>
<div class="block">Serialize the atom payload for the provided bagkey, excluding atom prefix.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="typeNameLabel">HeaderSerialization.</span><code><span class="memberNameLink"><a href="../../../../brown/tracingplane/baggageprotocol/HeaderSerialization.html#writeAtom-java.nio.ByteBuffer-brown.tracingplane.baggageprotocol.BagKey.Keyed-int-">writeAtom</a></span>(java.nio.ByteBuffer buf,
<a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> bagKey,
int level)</code>
<div class="block">Write an atom to the provided buffer for the specified bagKey and level.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="typeNameLabel">HeaderSerialization.</span><code><span class="memberNameLink"><a href="../../../../brown/tracingplane/baggageprotocol/HeaderSerialization.html#writeAtomPayload-java.nio.ByteBuffer-brown.tracingplane.baggageprotocol.BagKey.Keyed-">writeAtomPayload</a></span>(java.nio.ByteBuffer buf,
<a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> bagKey)</code>
<div class="block">Write the payload of an Keyed header atom to the provided buf</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><span class="typeNameLabel">HeaderSerialization.</span><code><span class="memberNameLink"><a href="../../../../brown/tracingplane/baggageprotocol/HeaderSerialization.html#writeAtomPrefix-java.nio.ByteBuffer-brown.tracingplane.baggageprotocol.BagKey.Keyed-int-">writeAtomPrefix</a></span>(java.nio.ByteBuffer buf,
<a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">BagKey.Keyed</a> bagKey,
int level)</code>
<div class="block">Write the prefix byte of a Keyed header atom to the provided buf</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../brown/tracingplane/baggageprotocol/BagKey.Keyed.html" title="class in brown.tracingplane.baggageprotocol">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-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?brown/tracingplane/baggageprotocol/class-use/BagKey.Keyed.html" target="_top">Frames</a></li>
<li><a href="BagKey.Keyed.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>
| {
"content_hash": "9a41e53ba21496ffbda5b0fce2ab031e",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 449,
"avg_line_length": 50.58048780487805,
"alnum_prop": 0.6863728421255666,
"repo_name": "tracingplane/tracingplane-java",
"id": "2148ae1d42770606873591fde55c4db763f8fa8c",
"size": "10369",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/brown/tracingplane/baggageprotocol/class-use/BagKey.Keyed.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "BlitzBasic",
"bytes": "1763"
},
{
"name": "CSS",
"bytes": "12981"
},
{
"name": "Java",
"bytes": "616325"
},
{
"name": "Scala",
"bytes": "52646"
}
],
"symlink_target": ""
} |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.culiu.mhvp.core">
<!-- <application android:allowBackup="false" >
</application>-->
</manifest>
| {
"content_hash": "820e875ffbbdf1c504aa57d3f57678e7",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 68,
"avg_line_length": 24,
"alnum_prop": 0.6770833333333334,
"repo_name": "XavierSAndroid/MagicHeaderViewPager",
"id": "223ea86d1e9f2c931d01ed9f92d186ff883ca7ad",
"size": "192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mhvp-core/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "333052"
}
],
"symlink_target": ""
} |
<?php
namespace xleeuwx\Affiliate\Model;
abstract class ProductImport
{
abstract function getExternalProductDetails($productID);
abstract function getExternalProduct($productID);
abstract function getExternalProductPrice($productID);
abstract function updateExternalProduct($productID);
} | {
"content_hash": "8dc1fa5ee604f6819e766ffa4a672c21",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 60,
"avg_line_length": 19.4375,
"alnum_prop": 0.7909967845659164,
"repo_name": "xleeuwx/octobercms-plugin-affiliate",
"id": "9ef5a4fe6aba1cc90a5eb6119c34d2983b376215",
"size": "311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Model/ProductImport.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "12191"
}
],
"symlink_target": ""
} |
Welcome to the example app used in the
[Tour of Heroes: Multiple Components](https://webdev.dartlang.org/angular/tutorial/toh-pt3) page
of [Dart for the web](https://webdev.dartlang.org).
You can run a [hosted copy](https://webdev.dartlang.org/examples/toh-3) of this
sample. Or run your own copy:
1. Create a local copy of this repo (use the "Clone or download" button above).
2. Get the dependencies: `pub get`
3. Get the webdev tool: `pub global activate webdev`
4. Launch a development server: `webdev serve`
5. In a browser, open [http://localhost:8080](http://localhost:8080)
---
*Note:* The content of this repository is generated from the
[Angular docs repository][docs repo] by running the
[dart-doc-syncer](//github.com/dart-lang/dart-doc-syncer) tool.
If you find a problem with this sample's code, please open an [issue][].
[docs repo]: //github.com/dart-lang/site-webdev/tree/master/examples/ng/doc/toh-3
[issue]: //github.com/dart-lang/site-webdev/issues/new?title=[master]%20examples/ng/doc/toh-3
| {
"content_hash": "c1abc85126de48853ef858a9bdd9fdef",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 96,
"avg_line_length": 46.22727272727273,
"alnum_prop": 0.7453294001966568,
"repo_name": "angular-examples/toh-3",
"id": "0f5c876879244b26f5583360a3329e6ce7f1cc22",
"size": "1057",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2792"
},
{
"name": "Dart",
"bytes": "8019"
},
{
"name": "HTML",
"bytes": "1011"
}
],
"symlink_target": ""
} |
package mesosphere.marathon
package core.matcher.manager.impl
import java.util.UUID
import java.time.Clock
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.instance.TestInstanceBuilder._
import mesosphere.marathon.core.instance.{ Instance, TestInstanceBuilder }
import mesosphere.marathon.core.launcher.InstanceOp
import mesosphere.marathon.core.launcher.impl.InstanceOpFactoryHelper
import mesosphere.marathon.core.leadership.{ AlwaysElectedLeadershipModule, LeadershipModule }
import mesosphere.marathon.core.matcher.base.OfferMatcher
import mesosphere.marathon.core.matcher.base.OfferMatcher.{ InstanceOpSource, InstanceOpWithSource, MatchedInstanceOps }
import mesosphere.marathon.core.matcher.base.util.OfferMatcherSpec
import mesosphere.marathon.core.matcher.manager.{ OfferMatcherManagerConfig, OfferMatcherManagerModule }
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.state.PathId
import mesosphere.marathon.stream.Implicits._
import mesosphere.marathon.tasks.ResourceUtil
import mesosphere.marathon.test.MarathonTestHelper
import org.apache.mesos.Protos.{ Offer, TaskInfo }
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.Random
class OfferMatcherManagerModuleTest extends AkkaUnitTest with OfferMatcherSpec {
// FIXME: Missing Tests
// Adding matcher while matching offers
// Removing matcher while matching offers, removed matcher does not get offers anymore
// Timeout for matching
// Deal with randomness?
object F {
import org.apache.mesos.{ Protos => Mesos }
val runSpecId = PathId("/test")
val instanceId = Instance.Id.forRunSpec(runSpecId)
val launch = new InstanceOpFactoryHelper(
Some("principal"),
Some("role")).launchEphemeral(_: Mesos.TaskInfo, _: Task, _: Instance)
}
class Fixture {
val clock: Clock = Clock.systemUTC()
val random: Random.type = Random
val leaderModule: LeadershipModule = AlwaysElectedLeadershipModule.forRefFactory(system)
val config: OfferMatcherManagerConfig = new OfferMatcherManagerConfig {
verify()
}
val module: OfferMatcherManagerModule =
new OfferMatcherManagerModule(clock, random, config, leaderModule, () => None,
actorName = UUID.randomUUID().toString)
}
/**
* Simplistic matcher which always matches the same tasks, even if not enough resources are available.
*/
private class ConstantOfferMatcher(tasks: Seq[TaskInfo]) extends OfferMatcher {
var results = Vector.empty[MatchedInstanceOps]
var processCycle = 0
protected def numberedTasks() = {
processCycle += 1
tasks.map { task =>
task
.toBuilder
.setTaskId(task.getTaskId.toBuilder.setValue(task.getTaskId.getValue + "-" + processCycle))
.build()
}
}
protected def matchTasks(offer: Offer): Seq[TaskInfo] = numberedTasks() // linter:ignore:UnusedParameter
override def matchOffer(offer: Offer): Future[MatchedInstanceOps] = {
val opsWithSources = matchTasks(offer).map { taskInfo =>
val instance = TestInstanceBuilder.newBuilderWithInstanceId(F.instanceId).addTaskWithBuilder().taskFromTaskInfo(taskInfo, offer).build().getInstance()
val task: Task = instance.appTask
val launch = F.launch(taskInfo, task.copy(taskId = Task.Id(taskInfo.getTaskId)), instance)
InstanceOpWithSource(Source, launch)
}(collection.breakOut)
val result = MatchedInstanceOps(offer.getId, opsWithSources)
results :+= result
Future.successful(result)
}
object Source extends InstanceOpSource {
var acceptedOps = Vector.empty[InstanceOp]
var rejectedOps = Vector.empty[InstanceOp]
override def instanceOpAccepted(taskOp: InstanceOp): Unit = acceptedOps :+= taskOp
override def instanceOpRejected(taskOp: InstanceOp, reason: String): Unit = rejectedOps :+= taskOp
}
}
/**
* Simplistic matcher which only looks if there are sufficient CPUs in the offer
* for the given tasks. It has no state and thus continues matching infinitely.
*/
private class CPUOfferMatcher(tasks: Seq[TaskInfo]) extends ConstantOfferMatcher(tasks) {
val totalCpus: Double = {
val cpuValues = for {
task <- tasks
resource <- task.getResourcesList
if resource.getName == "cpus"
cpuScalar <- Option(resource.getScalar)
cpus = cpuScalar.getValue
} yield cpus
cpuValues.sum
}
override def matchTasks(offer: Offer): Seq[TaskInfo] = {
val cpusInOffer: Double =
offer.getResourcesList.find(_.getName == "cpus")
.flatMap(r => Option(r.getScalar))
.map(_.getValue)
.getOrElse(0)
if (cpusInOffer >= totalCpus) numberedTasks() else Seq.empty
}
}
"OfferMatcherModule" should {
"no registered matchers result in empty result" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOffer().build()
val matchedTasksFuture: Future[MatchedInstanceOps] =
module.globalOfferMatcher.matchOffer(offer)
val matchedTasks: MatchedInstanceOps = matchedTasksFuture.futureValue(Timeout(3.seconds))
assert(matchedTasks.opsWithSource.isEmpty)
}
"single offer is passed to matcher" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0).build()
val task = MarathonTestHelper.makeOneCPUTask(Task.EphemeralOrReservedTaskId(F.instanceId, None)).build()
val matcher: CPUOfferMatcher = new CPUOfferMatcher(Seq(task))
module.subOfferMatcherManager.setLaunchTokens(10)
module.subOfferMatcherManager.addSubscription(matcher)
val matchedTasksFuture: Future[MatchedInstanceOps] =
module.globalOfferMatcher.matchOffer(offer)
val matchedTasks: MatchedInstanceOps = matchedTasksFuture.futureValue(Timeout(3.seconds))
assert(matchedTasks.offerId == offer.getId)
assert(launchedTaskInfos(matchedTasks) == Seq(MarathonTestHelper.makeOneCPUTask(s"${task.getTaskId.getValue}-1").build()))
}
"deregistering only matcher works" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0).build()
val task = MarathonTestHelper.makeOneCPUTask(Task.Id.forInstanceId(F.instanceId, None)).build()
val matcher: CPUOfferMatcher = new CPUOfferMatcher(Seq(task))
module.subOfferMatcherManager.setLaunchTokens(10)
module.subOfferMatcherManager.addSubscription(matcher)
module.subOfferMatcherManager.removeSubscription(matcher)
val matchedTasksFuture: Future[MatchedInstanceOps] =
module.globalOfferMatcher.matchOffer(offer)
val matchedTasks: MatchedInstanceOps = matchedTasksFuture.futureValue(Timeout(3.seconds))
assert(matchedTasks.opsWithSource.isEmpty)
}
"single offer is passed to multiple matchers" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOffer(cpus = 2.0).build()
module.subOfferMatcherManager.setLaunchTokens(10)
val task1: TaskInfo = MarathonTestHelper.makeOneCPUTask(Task.Id.forInstanceId(F.instanceId, None)).build()
module.subOfferMatcherManager.addSubscription(new CPUOfferMatcher(Seq(task1)))
val task2: TaskInfo = MarathonTestHelper.makeOneCPUTask(Task.Id.forInstanceId(F.instanceId, None)).build()
module.subOfferMatcherManager.addSubscription(new CPUOfferMatcher(Seq(task2)))
val matchedTasksFuture: Future[MatchedInstanceOps] =
module.globalOfferMatcher.matchOffer(offer)
val matchedTasks: MatchedInstanceOps = matchedTasksFuture.futureValue(Timeout(3.seconds))
assert(launchedTaskInfos(matchedTasks).toSet == Set(
MarathonTestHelper.makeOneCPUTask(task1.getTaskId.getValue + "-1").build(),
MarathonTestHelper.makeOneCPUTask(task2.getTaskId.getValue + "-1").build())
)
}
for (launchTokens <- Seq(0, 1, 5)) {
s"launch as many tasks as there are launch tokens: $launchTokens" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOffer(cpus = 1.3).build()
module.subOfferMatcherManager.setLaunchTokens(launchTokens)
val task1: TaskInfo = MarathonTestHelper.makeOneCPUTask(Task.Id.forInstanceId(F.instanceId, None)).build()
module.subOfferMatcherManager.addSubscription(new ConstantOfferMatcher(Seq(task1)))
val matchedTasksFuture: Future[MatchedInstanceOps] =
module.globalOfferMatcher.matchOffer(offer)
val matchedTasks: MatchedInstanceOps = matchedTasksFuture.futureValue(Timeout(3.seconds))
assert(matchedTasks.opsWithSource.size == launchTokens)
}
}
"single offer is passed to multiple matchers repeatedly" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOffer(cpus = 4.0).build()
module.subOfferMatcherManager.setLaunchTokens(10)
val task1: TaskInfo = MarathonTestHelper.makeOneCPUTask(Task.Id.forInstanceId(F.instanceId, None)).build()
module.subOfferMatcherManager.addSubscription(new CPUOfferMatcher(Seq(task1)))
val task2: TaskInfo = MarathonTestHelper.makeOneCPUTask(Task.Id.forInstanceId(F.instanceId, None)).build()
module.subOfferMatcherManager.addSubscription(new CPUOfferMatcher(Seq(task2)))
val matchedTasksFuture: Future[MatchedInstanceOps] =
module.globalOfferMatcher.matchOffer(offer)
val matchedTasks: MatchedInstanceOps = matchedTasksFuture.futureValue(Timeout(3.seconds))
assert(launchedTaskInfos(matchedTasks).toSet == Set(
MarathonTestHelper.makeOneCPUTask(task1.getTaskId.getValue + "-1").build(),
MarathonTestHelper.makeOneCPUTask(task1.getTaskId.getValue + "-2").build(),
MarathonTestHelper.makeOneCPUTask(task2.getTaskId.getValue + "-1").build(),
MarathonTestHelper.makeOneCPUTask(task2.getTaskId.getValue + "-2").build())
)
}
"ports of an offer should be displayed in a short notation if they exceed a certain quantity" in new Fixture {
val offer: Offer = MarathonTestHelper.makeBasicOfferWithManyPortRanges(100).build()
val resources = ResourceUtil.displayResources(offer.getResourcesList.toSeq, 10)
resources should include("ports(*) 1->2,3->4,5->6,7->8,9->10,11->12,13->14,15->16,17->18,19->20 ... (90 more)")
}
}
}
| {
"content_hash": "90c76acbd1c64210d0951c0afe616b0a",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 158,
"avg_line_length": 45.629955947136565,
"alnum_prop": 0.7372079552037073,
"repo_name": "meln1k/marathon",
"id": "27f68587594bcdf037d6d2545d0f39470ecb9ecb",
"size": "10358",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/scala/mesosphere/marathon/core/matcher/manager/impl/OfferMatcherManagerModuleTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Clojure",
"bytes": "59270"
},
{
"name": "Groovy",
"bytes": "14255"
},
{
"name": "HTML",
"bytes": "502"
},
{
"name": "Java",
"bytes": "778"
},
{
"name": "Makefile",
"bytes": "4005"
},
{
"name": "Python",
"bytes": "169779"
},
{
"name": "Ruby",
"bytes": "772"
},
{
"name": "Scala",
"bytes": "4280011"
},
{
"name": "Shell",
"bytes": "41549"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="la" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Apollocoin</source>
<translation>Informatio de Apollocoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Apollocoin</b> version</source>
<translation><b>Apollocoin</b> versio</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>Hoc est experimentale programma.
Distributum sub MIT/X11 licentia programmatum, vide comitantem plicam COPYING vel http://www.opensource.org/licenses/mit-license.php.
Hoc productum continet programmata composita ab OpenSSL Project pro utendo in OpenSSL Toolkit (http://www.openssl.org/) et programmata cifrarum scripta ab Eric Young (eay@cryptsoft.com) et UPnP programmata scripta ab Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Apollocoin developers</source>
<translation>Apollocoin curatores</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Liber Inscriptionum</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dupliciter-clicca ut inscriptionem vel titulum mutes</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crea novam inscriptionem</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia inscriptionem iam selectam in latibulum systematis</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nova Inscriptio</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Apollocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Haec sunt inscriptiones Apollocoin tuae pro accipendo pensitationes. Cupias variam ad quemque mittentem dare ut melius scias quem tibi pensare.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copia Inscriptionem</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Monstra codicem &QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Apollocoin address</source>
<translation>Signa nuntium ut demonstres inscriptionem Apollocoin a te possessam esse</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signa &Nuntium</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Dele active selectam inscriptionem ex enumeratione</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporta data in hac tabella in plicam</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exporta</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Apollocoin address</source>
<translation>Verifica nuntium ut cures signatum esse cum specificata inscriptione Apollocoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifica Nuntium</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Dele</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Apollocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Hae sunt inscriptiones mittendi pensitationes. Semper inspice quantitatem et inscriptionem accipiendi antequam nummos mittis.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copia &Titulum</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Muta</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Mitte &Nummos</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exporta Data Libri Inscriptionum</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma Separata Plica (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error exportandi</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Non potuisse scribere in plicam %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Titulus</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Inscriptio</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(nullus titulus)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialogus Tesserae</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Insere tesseram</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova tessera</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Itera novam tesseram</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Insero novam tesseram cassidili.<br/>Sodes tessera <b>10 pluriumve fortuitarum litterarum</b> utere aut <b>octo pluriumve verborum</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Cifra cassidile</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Huic operationi necesse est tessera cassidili tuo ut cassidile reseret.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Resera cassidile</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Huic operationi necesse est tessera cassidili tuo ut cassidile decifret.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decifra cassidile</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Muta tesseram</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Insero veterem novamque tesseram cassidili.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirma cifrationem cassidilis</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR APOLLOCOINS</b>!</source>
<translation>Monitio: Si cassidile tuum cifras et tesseram amittis, tu <b>AMITTES OMNES TUOS NUMMOS BITOS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Certusne es te velle tuum cassidile cifrare?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>GRAVE: Oportet ulla prioria conservata quae fecisti de plica tui cassidilis reponi a nove generata cifrata plica cassidilis. Propter securitatem, prioria conservata de plica non cifrata cassidilis inutilia fiet simul atque incipis uti novo cifrato cassidili.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Monitio: Litterae ut capitales seratae sunt!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Cassidile cifratum</translation>
</message>
<message>
<location line="-56"/>
<source>Apollocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your apollocoins from being stolen by malware infecting your computer.</source>
<translation>Apollocoin iam desinet ut finiat actionem cifrandi. Memento cassidile cifrare non posse cuncte curare ne tui nummi clepantur ab malis programatibus in tuo computatro.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Cassidile cifrare abortum est</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Cassidile cifrare abortum est propter internum errorem. Tuum cassidile cifratum non est.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Tesserae datae non eaedem sunt.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Cassidile reserare abortum est.</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Tessera inserta pro cassidilis decifrando prava erat.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Cassidile decifrare abortum est.</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Tessera cassidilis successa est in mutando.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Signa &nuntium...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronizans cum rete...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Summarium</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Monstra generale summarium cassidilis</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transactiones</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Inspicio historiam transactionum</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Muta indicem salvatarum inscriptionum titulorumque</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Monstra indicem inscriptionum quibus pensitationes acceptandae</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>E&xi</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Exi applicatione</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Apollocoin</source>
<translation>Monstra informationem de Apollocoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Informatio de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Monstra informationem de Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Optiones</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Cifra Cassidile...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Conserva Cassidile...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Muta tesseram...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importans frusta ab disco...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Recreans indicem frustorum in disco...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Apollocoin address</source>
<translation>Mitte nummos ad inscriptionem Apollocoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Apollocoin</source>
<translation>Muta configurationis optiones pro Apollocoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Conserva cassidile in locum alium</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Muta tesseram utam pro cassidilis cifrando</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>Fenestra &Debug</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Aperi terminalem debug et diagnosticalem</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verifica nuntium...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Apollocoin</source>
<translation>Apollocoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Cassidile</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Mitte</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Accipe</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Inscriptiones</translation>
</message>
<message>
<location line="+22"/>
<source>&About Apollocoin</source>
<translation>&Informatio de Apollocoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Monstra/Occulta</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Monstra vel occulta Fenestram principem</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Cifra claves privatas quae cassidili tui sunt</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Apollocoin addresses to prove you own them</source>
<translation>Signa nuntios cum tuis inscriptionibus Apollocoin ut demonstres te eas possidere</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Apollocoin addresses</source>
<translation>Verifica nuntios ut certus sis eos signatos esse cum specificatis inscriptionibus Apollocoin</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Plica</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Configuratio</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Auxilium</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Tabella instrumentorum "Tabs"</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Apollocoin client</source>
<translation>Apollocoin cliens</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Apollocoin network</source>
<translation><numerusform>%n activa conexio ad rete Apollocoin</numerusform><numerusform>%n activae conexiones ad rete Apollocoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Nulla fons frustorum absens...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Perfecta %1 de %2 (aestimato) frusta historiae transactionum.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Processae %1 frusta historiae transactionum.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horae</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dies</numerusform><numerusform>%n dies</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n hebdomas</numerusform><numerusform>%n hebdomades</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 post</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Postremum acceptum frustum generatum est %1 abhinc.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transactiones post hoc nondum visibiles erunt.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Monitio</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informatio</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Haec transactio maior est quam limen magnitudinis. Adhuc potes id mittere mercede %1, quae it nodis qui procedunt tuam transactionem et adiuvat sustinere rete. Visne mercedem solvere?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Recentissimo</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Persequens...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirma mercedem transactionis</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transactio missa</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transactio incipiens</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dies: %1
Quantitas: %2
Typus: %3
Inscriptio: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Tractatio URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Apollocoin address or malformed URI parameters.</source>
<translation>URI intellegi non posse! Huius causa possit inscriptionem Apollocoin non validam aut URI parametra maleformata.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cassidile <b>cifratum</b> est et iam nunc <b>reseratum</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cassidile <b>cifratum</b> est et iam nunc <b>seratum</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Apollocoin can no longer continue safely and will quit.</source>
<translation>Error fatalis accidit. Apollocoin nondum pergere tute potest, et exibit.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Monitio Retis</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Muta Inscriptionem</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Titulus</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Titulus associatus huic insertione libri inscriptionum</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Inscriptio</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Titulus associatus huic insertione libri inscriptionum. Haec tantum mutari potest pro inscriptionibus mittendi</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nova inscriptio accipiendi</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nova inscriptio mittendi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Muta inscriptionem accipiendi</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Muta inscriptionem mittendi</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Inserta inscriptio "%1" iam in libro inscriptionum est.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Apollocoin address.</source>
<translation>Inscriptio inserta "%1" non valida inscriptio Apollocoin est.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Non potuisse cassidile reserare</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generare novam clavem abortum est.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Apollocoin-Qt</source>
<translation>Apollocoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versio</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Usus:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Optiones mandati intiantis</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI optiones</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Constitue linguam, exempli gratia "de_DE" (praedefinitum: lingua systematis)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Incipe minifactum ut icon</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Monstra principem imaginem ad initium (praedefinitum: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Optiones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Princeps</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Optionalis merces transactionum singulis kB quae adiuvat curare tuas transactiones processas esse celeriter. Plurimi transactiones 1kB sunt.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Solve &mercedem transactionis</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Apollocoin after logging in to the system.</source>
<translation>Pelle Apollocoin per se postquam in systema inire.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Apollocoin on system login</source>
<translation>&Pelle Apollocoin cum inire systema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Reconstitue omnes optiones clientis ad praedefinita.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Reconstitue Optiones</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Rete</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Apollocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Aperi per se portam clientis Apollocoin in itineratore. Hoc tantum effectivum est si itineratrum tuum supportat UPnP et id activum est.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Designa portam utendo &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Apollocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connecte ad rete Apollocoin per SOCKS vicarium (e.g. quando conectens per Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Conecte per SOCKS vicarium:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP vicarii:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Inscriptio IP vicarii (e.g. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Porta:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Porta vicarii (e.g. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versio:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS versio vicarii (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Fenestra</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Monstra tantum iconem in tabella systematis postquam fenestram minifactam est.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minifac in tabellam systematis potius quam applicationum</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minifac potius quam exire applicatione quando fenestra clausa sit. Si haec optio activa est, applicatio clausa erit tantum postquam selegeris Exi in menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inifac ad claudendum</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&UI</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Lingua monstranda utenti:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Apollocoin.</source>
<translation>Lingua monstranda utenti hic constitui potest. Haec configuratio effectiva erit postquam Apollocoin iterum initiatum erit.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unita qua quantitates monstrare:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Selige praedefinitam unitam subdivisionis monstrare in interfacie et quando nummos mittere</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Apollocoin addresses in the transaction list or not.</source>
<translation>Num monstrare inscriptiones Apollocoin in enumeratione transactionum.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Monstra inscriptiones in enumeratione transactionum</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancella</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Applica</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>praedefinitum</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirma optionum reconstituere</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Aliis configurationibus fortasse necesse est clientem iterum initiare ut effectivae sint.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Vis procedere?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Monitio</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Apollocoin.</source>
<translation>Haec configuratio effectiva erit postquam Apollocoin iterum initiatum erit.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Inscriptio vicarii tradita non valida est.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Schema</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Apollocoin network after a connection is established, but this process has not completed yet.</source>
<translation>Monstrata informatio fortasse non recentissima est. Tuum cassidile per se synchronizat cum rete Apollocoin postquam conexio constabilita est, sed hoc actio nondum perfecta est.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Pendendum:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Non confirmata:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Cassidile</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Immatura:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Fossum pendendum quod nondum maturum est</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Recentes transactiones</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Tuum pendendum iam nunc</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Totali nummi transactionum quae adhuc confirmandae sunt, et nondum afficiunt pendendum</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>non synchronizato</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start apollocoin: click-to-pay handler</source>
<translation>Apollocoin incipere non potest: cliccare-ad-pensandum handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Dialogus QR Codicis</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Posce Pensitationem</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Quantitas:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Titulus:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Nuntius:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Salva ut...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error codificandi URI in codicem QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Inserta quantitas non est valida, sodes proba.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resultato URI nimis longo, conare minuere verba pro titulo / nuntio.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Salva codicem QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imagines PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nomen clientis</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versio clientis</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informatio</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Utens OpenSSL versione</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Tempus initiandi</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rete</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Numerus conexionum</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>In testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Catena frustorum</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Numerus frustorum iam nunc</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Aestimatus totalis numerus frustorum</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Hora postremi frusti</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Aperi</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Optiones mandati initiantis</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Apollocoin-Qt help message to get a list with possible Apollocoin command-line options.</source>
<translation>Monstra nuntium auxilii Apollocoin-Qt ut videas enumerationem possibilium optionum Apollocoin mandati initiantis.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Monstra</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Terminale</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Dies aedificandi</translation>
</message>
<message>
<location line="-104"/>
<source>Apollocoin - Debug window</source>
<translation>Apollocoin - Fenestra debug</translation>
</message>
<message>
<location line="+25"/>
<source>Apollocoin Core</source>
<translation>Apollocoin Nucleus</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug catalogi plica</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Apollocoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Aperi plicam catalogi de Apollocoin debug ex activo indice datorum. Hoc possit pauca secunda pro plicis magnis catalogi.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Vacuefac terminale</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Apollocoin RPC console.</source>
<translation>Bene ventio in terminale RPC de Apollocoin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utere sagittis sursum deorsumque ut per historiam naviges, et <b>Ctrl+L</b> ut scrinium vacuefacias.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Scribe <b>help</b> pro summario possibilium mandatorum.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Mitte Nummos</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Mitte pluribus accipientibus simul</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Adde &Accipientem</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remove omnes campos transactionis</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Vacuefac &Omnia</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Pendendum:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirma actionem mittendi</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Mitte</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> ad %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirma mittendum nummorum</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Certus es te velle mittere %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>et</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Inscriptio accipientis non est valida, sodes reproba.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Oportet quantitatem ad pensandum maiorem quam 0 esse.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Quantitas est ultra quod habes.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Quantitas est ultra quod habes cum merces transactionis %1 includitur.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Geminata inscriptio inventa, tantum posse mittere ad quamque inscriptionem semel singulare operatione.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Error: Creare transactionem abortum est!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: transactio reiecta est. Hoc fiat si alii nummorum in tuo cassidili iam soluti sunt, ut si usus es exemplar de wallet.dat et nummi soluti sunt in exemplari sed non hic notati ut soluti.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Schema</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Quantitas:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Pensa &Ad:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Inscriptio cui mittere pensitationem (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Insero titulum huic inscriptioni ut eam in tuum librum inscriptionum addas.</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Titulus:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Selige inscriptionem ex libro inscriptionum</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Conglutina inscriptionem ex latibulo</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Remove hunc accipientem</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Apollocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Insero inscriptionem Apollocoin (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signationes - Signa / Verifica nuntium</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Signa Nuntium</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Potes nuntios signare inscriptionibus tuis ut demonstres te eas possidere. Cautus es non amibiguum signare, quia impetus phiscatorum conentur te fallere ut signes identitatem tuam ad eos. Solas signa sententias cuncte descriptas quibus convenis.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Inscriptio qua signare nuntium (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Selige inscriptionem ex librum inscriptionum</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Glutina inscriptionem ex latibulo</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Insere hic nuntium quod vis signare</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signatio</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copia signationem in latibulum systematis</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Apollocoin address</source>
<translation>Signa nuntium ut demonstres hanc inscriptionem Apollocoin a te possessa esse</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signa &Nuntium</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Reconstitue omnes campos signandi nuntii</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Vacuefac &Omnia</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verifica Nuntium</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Insere inscriptionem signantem, nuntium (cura ut copias intermissiones linearum, spatia, tabs, et cetera exacte) et signationem infra ut nuntium verifices. Cautus esto ne magis legas in signationem quam in nuntio signato ipso est, ut vites falli ab impetu homo-in-medio.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Inscriptio qua nuntius signatus est (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Apollocoin address</source>
<translation>Verifica nuntium ut cures signatum esse cum specifica inscriptione Apollocoin</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verifica &Nuntium</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Reconstitue omnes campos verificandi nuntii</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Apollocoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Insere inscriptionem Apollocoin (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Clicca "Signa Nuntium" ut signatio generetur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Apollocoin signature</source>
<translation>Insere signationem Apollocoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Inscriptio inserta non valida est.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Sodes inscriptionem proba et rursus conare.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Inserta inscriptio clavem non refert.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Cassidilis reserare cancellatum est.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Clavis privata absens est pro inserta inscriptione.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Nuntium signare abortum est.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Nuntius signatus.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signatio decodificari non potuit.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Sodes signationem proba et rursus conare.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signatio non convenit digesto nuntii</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Nuntium verificare abortum est.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Nuntius verificatus.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Apollocoin developers</source>
<translation>Apollocoin curatores</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Apertum donec %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/non conecto</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/non confirmata</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmationes</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, disseminatum per %n nodo</numerusform><numerusform>, disseminata per %n nodis</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dies</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Fons</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generatum</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Ab</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Ad</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>inscriptio propria</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>titulus</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Creditum</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>maturum erit in %n plure frusto</numerusform><numerusform>maturum erit in %n pluribus frustis</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>non acceptum</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debitum</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transactionis merces</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cuncta quantitas</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Nuntius</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Annotatio</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID transactionis</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Nummis generatis necesse est maturitas 120 frustorum antequam illi transmitti possunt. Cum hoc frustum generavisti, disseminatum est ad rete ut addatur ad catenam frustorum. Si aboritur inire catenam, status eius mutabit in "non acceptum" et non transmittabile erit. Hoc interdum accidat si alter nodus frustum generat paucis secundis ante vel post tuum.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informatio de debug</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transactio</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Lectenda</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Quantitas</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verum</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falsum</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, nondum prospere disseminatum est</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform>Aperi pro %n pluribus frustis</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ignotum</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Particularia transactionis</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Haec tabula monstrat descriptionem verbosam transactionis</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dies</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Typus</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Inscriptio</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Quantitas</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aperi pro %n plure frusto</numerusform><numerusform>Aperi pro %n pluribus frustis</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Apertum donec %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Non conectum (%1 confirmationes)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Non confirmatum (%1 de %2 confirmationibus)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmatum (%1 confirmationes)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Fossum pendendum utibile erit quando id maturum est post %n plus frustum</numerusform><numerusform>Fossum pendendum utibile erit quando id maturum est post %n pluria frusta</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Hoc frustum non acceptum est ab ulla alia nodis et probabiliter non acceptum erit!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generatum sed non acceptum</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Acceptum cum</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Acceptum ab</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Missum ad</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pensitatio ad te ipsum</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Fossa</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status transactionis. Supervola cum mure ut monstretur numerus confirmationum.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dies et tempus quando transactio accepta est.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Typus transactionis.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Inscriptio destinationis transactionis.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Quantitas remota ex pendendo aut addita ei.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Omne</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hodie</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Hac hebdomade</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Hoc mense</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Postremo mense</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Hoc anno</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervallum...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Acceptum cum</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Missum ad</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Ad te ipsum</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Fossa</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Alia</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Insere inscriptionem vel titulum ut quaeras</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Quantitas minima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copia inscriptionem</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copia titulum</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copia quantitatem</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copia transactionis ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Muta titulum</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Monstra particularia transactionis</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exporta Data Transactionum</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma Separata Plica (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmatum</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dies</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Typus</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Titulus</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Inscriptio</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Quantitas</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exportandi</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Non potuisse scribere ad plicam %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervallum:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ad</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Mitte Nummos</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exporta</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporta data in hac tabella in plicam</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Conserva cassidile</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Data cassidilis (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Conservare abortum est.</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Error erat conante salvare data cassidilis ad novum locum.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Successum in conservando</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Successum in salvando data cassidilis in novum locum.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Apollocoin version</source>
<translation>Versio de Apollocoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Usus:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or apollocoind</source>
<translation>Mitte mandatum ad -server vel apollocoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Enumera mandata</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Accipe auxilium pro mandato</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Optiones:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: apollocoin.conf)</source>
<translation>Specifica configurationis plicam (praedefinitum: apollocoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: apollocoind.pid)</source>
<translation>Specifica pid plicam (praedefinitum: apollocoin.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Specifica indicem datorum</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Constitue magnitudinem databasis cache in megabytes (praedefinitum: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Ausculta pro conexionibus in <porta> (praedefinitum: 9333 vel testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Manutene non plures quam <n> conexiones ad paria (praedefinitum: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Conecta ad nodum acceptare inscriptiones parium, et disconecte</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Specifica tuam propriam publicam inscriptionem</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Limen pro disconectendo paria improba (praedefinitum: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Numerum secundorum prohibere ne paria improba reconectant (praedefinitum: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Error erat dum initians portam RPC %u pro auscultando in IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Ausculta pro conexionibus JSON-RPC in <porta> (praedefinitum: 9332 vel testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accipe terminalis et JSON-RPC mandata.</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Operare infere sicut daemon et mandata accipe</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Utere rete experimentale</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accipe conexiones externas (praedefinitum: 1 nisi -proxy neque -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=apollocoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Apollocoin Alert" admin@foo.com
</source>
<translation>%s, necesse est te rpcpassword constituere in plica configurationis:
%s
Hortatur te hanc fortuitam tesseram uti:
rpcuser=apollocoinrpc
rpcpassword=%s
(non est necesse te hanc tesseram meminisse)
Nomen usoris et tessera eadem esse NON POSSUNT.
Si plica non existit, eam crea cum permissionibus ut eius dominus tantum sinitur id legere.
Quoque hortatur alertnotify constituere ut tu notificetur de problematibus;
exempli gratia: alertnotify=echo %%s | mail -s "Apollocoin Notificatio" admin@foo.com
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Error erat dum initians portam RPC %u pro auscultando in IPv6, labens retrorsum ad IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Conglutina ad inscriptionem datam et semper in eam ausculta. Utere [moderatrum]:porta notationem pro IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Apollocoin is probably already running.</source>
<translation>Non posse serare datorum indicem %s. Apollocoin probabiliter iam operatur.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: Transactio eiecta est! Hoc possit accidere si alii nummorum in cassidili tuo iam soluti sint, ut si usus es exemplar de wallet.dat et nummi soluti sunt in exemplari sed non hic notati ut soluti.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Error: Huic transactioni necesse est merces saltem %s propter eius magnitudinem, complexitatem, vel usum recentum acceptorum nummorum!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Facere mandatum quotiescumque notificatio affinis accipitur (%s in mandato mutatur in nuntium) </translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Facere mandatum quotiescumque cassidilis transactio mutet (%s in mandato sbstituitur ab TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Constitue magnitudinem maximam transactionum magnae-prioritatis/parvae-mercedis in octetis/bytes (praedefinitum: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Hoc est prae-dimittum experimentala aedes - utere eo periculo tuo proprio - nolite utere fodendo vel applicationibus mercatoriis</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Monitio: -paytxfee constitutum valde magnum! Hoc est merces transactionis solves si mittis transactionem.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Monitio: Monstratae transactiones fortasse non recta sint! Forte oportet tibi progredere, an aliis nodis progredere.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Apollocoin will not work properly.</source>
<translation>Monitio: Sodes cura ut dies tempusque computatri tui recti sunt! Si horologium tuum pravum est, Apollocoin non proprie fungetur.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Monitio: error legendo wallet.dat! Omnes claves recte lectae, sed data transactionum vel libri inscriptionum fortasse desint vel prava sint.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Monitio: wallet.data corrupta, data salvata! Originalis wallet.dat salvata ut wallet.{timestamp}.bak in %s; si pendendum tuum vel transactiones pravae sunt, oportet ab conservato restituere.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Conare recipere claves privatas de corrupto wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Optiones creandi frustorum:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Conecte sole ad nodos specificatos (vel nodum specificatum)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corruptum databasum frustorum invenitur</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Discooperi propriam inscriptionem IP (praedefinitum: 1 quando auscultans et nullum -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Visne reficere databasum frustorum iam?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Error initiando databasem frustorum</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Error initiando systematem databasi cassidilis %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Error legendo frustorum databasem</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Error aperiendo databasum frustorum</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Error: Inopia spatii disci!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Error: Cassidile seratum, non posse transactionem creare!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Error: systematis error:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Non potuisse auscultare in ulla porta. Utere -listen=0 si hoc vis.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Non potuisse informationem frusti legere </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Non potuisse frustum legere</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Synchronizare indicem frustorum abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Scribere indicem frustorum abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Scribere informationem abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Scribere frustum abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Scribere informationem plicae abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Scribere databasem nummorum abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Scribere indicem transactionum abortum est</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Scribere data pro cancellando mutationes abortum est</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Inveni paria utendo DNS quaerendo (praedefinitum: 1 nisi -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Genera nummos (praedefinitum: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Quot frusta proba ad initium (praedefinitum: 288, 0 = omnia)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Quam perfecta frustorum verificatio est (0-4, praedefinitum: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Inopia descriptorum plicarum.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Restituere indicem catenae frustorum ex activis plicis blk000??.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Constitue numerum filorum ad tractandum RPC postulationes (praedefinitum: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verificante frusta...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verificante cassidilem...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importat frusta ab externa plica blk000??.dat</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Constitue numerum filorum verificationis scriptorum (Maximum 16, 0 = auto, <0 = tot corda libera erunt, praedefinitum: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Informatio</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Inscriptio -tor non valida: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Quantitas non valida pro -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Quantitas non valida pro -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Manutene completam indicem transactionum (praedefinitum: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maxima magnitudo memoriae pro datis accipendis singulis conexionibus, <n>*1000 octetis/bytes (praedefinitum: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maxima magnitudo memoriae pro datis mittendis singulis conexionibus, <n>*1000 octetis/bytes (praedefinitum: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Tantum accipe catenam frustorum convenientem internis lapidibus (praedefinitum: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Tantum conecte ad nodos in rete <net> (IPv4, IPv6 aut Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Exscribe additiciam informationem pro debug. Implicat omnes alias optiones -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Exscribe additiciam informationem pro retis debug.</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Antepone pittacium temporis ante exscriptum de debug </translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Apollocoin Wiki for SSL setup instructions)</source>
<translation>Optiones SSL: (vide vici de Apollocoin pro instructionibus SSL configurationis)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Selige versionem socks vicarii utendam (4-5, praedefinitum: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Mitte informationem vestigii/debug ad terminale potius quam plicam debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Mitte informationem vestigii/debug ad debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Constitue maximam magnitudinem frusti in octetis/bytes (praedefinitum: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Constitue minimam magnitudinem frusti in octetis/bytes (praedefinitum: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Diminue plicam debug.log ad initium clientis (praedefinitum: 1 nisi -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Signandum transactionis abortum est</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specifica tempumfati conexionis in millisecundis (praedefinitum: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Systematis error:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Magnitudo transactionis nimis parva</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Necesse est magnitudines transactionum positivas esse.</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transactio nimis magna</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Utere UPnP designare portam auscultandi (praedefinitum: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Utere UPnP designare portam auscultandi (praedefinitum: 1 quando auscultans)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utere vicarium ut extendas ad tor servitia occulta (praedefinitum: idem ut -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Nomen utentis pro conexionibus JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Monitio</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Monitio: Haec versio obsoleta est, progressio postulata!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Oportet recreare databases utendo -reindex ut mutes -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupta, salvare abortum est</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Tessera pro conexionibus JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitte conexionibus JSON-RPC ex inscriptione specificata</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Mitte mandata nodo operanti in <ip> (praedefinitum: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Pelle mandatum quando optissimum frustum mutat (%s in mandato substituitur ab hash frusti)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Progredere cassidile ad formam recentissimam</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Constitue magnitudinem stagni clavium ad <n> (praedefinitum: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Iterum perlege catenam frustorum propter absentes cassidilis transactiones</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Utere OpenSSL (https) pro conexionibus JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Plica certificationis daemonis moderantis (praedefinitum: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clavis privata daemonis moderans (praedefinitum: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptabiles cifrae (praedefinitum: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Hic nuntius auxilii</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Non posse conglutinare ad %s in hoc computatro (conglutinare redidit errorem %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Conecte per socks vicarium</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitte quaerenda DNS pro -addnode, -seednode, et -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Legens inscriptiones...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error legendi wallet.dat: Cassidile corruptum</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Apollocoin</source>
<translation>Error legendi wallet.dat: Cassidili necesse est recentior versio Apollocoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Apollocoin to complete</source>
<translation>Cassidili necesse erat rescribi: Repelle Apollocoin ut compleas</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error legendi wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Inscriptio -proxy non valida: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ignotum rete specificatum in -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Ignota -socks vicarii versio postulata: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Non posse resolvere -bind inscriptonem: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Non posse resolvere -externalip inscriptionem: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Quantitas non valida pro -paytxfee=<quantitas>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Quantitas non valida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Inopia nummorum</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Legens indicem frustorum...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adice nodum cui conectere et conare sustinere conexionem apertam</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Apollocoin is probably already running.</source>
<translation>Non posse conglutinare ad %s in hoc cumputatro. Apollocoin probabiliter iam operatur.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Merces per KB addere ad transactiones tu mittas</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Legens cassidile...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Non posse cassidile regredi</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Non posse scribere praedefinitam inscriptionem</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Iterum perlegens...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Completo lengendi</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Ut utaris optione %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Necesse est te rpcpassword=<tesseram> constituere in plica configurationum:
%s
Si plica non existat, crea eam cum permissionibus ut solus eius dominus eam legere sinatur.</translation>
</message>
</context>
</TS>
| {
"content_hash": "19d3342255feffb89344aef11ac75fca",
"timestamp": "",
"source": "github",
"line_count": 2937,
"max_line_length": 402,
"avg_line_length": 39.97003745318352,
"alnum_prop": 0.6379054790786425,
"repo_name": "apollocoin/apollocoin",
"id": "db3fb9c190e8d97daaaf24d1447a8cb334f3c46f",
"size": "117392",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_la.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "92422"
},
{
"name": "C++",
"bytes": "2553924"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69724"
},
{
"name": "Shell",
"bytes": "13173"
},
{
"name": "TypeScript",
"bytes": "5244761"
}
],
"symlink_target": ""
} |
<?php
/*
* This file is copied from the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*/
namespace Composer\Autoload;
use Symfony\Component\Finder\Finder;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
/**
* ClassMapGenerator
*
* @author Gyula Sallai <salla016@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ClassMapGenerator
{
/**
* Generate a class map file
*
* @param \Traversable<string>|array<string> $dirs Directories or a single path to search in
* @param string $file The name of the class map file
* @return void
*/
public static function dump($dirs, $file)
{
$maps = array();
foreach ($dirs as $dir) {
$maps = array_merge($maps, static::createMap($dir));
}
file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
}
/**
* Iterate over all files in the given directory searching for classes
*
* @param \Traversable<\SplFileInfo>|string|array<string> $path The path to search in or an iterator
* @param string $excluded Regex that matches file paths to be excluded from the classmap
* @param ?IOInterface $io IO object
* @param ?string $namespace Optional namespace prefix to filter by
* @param ?string $autoloadType psr-0|psr-4 Optional autoload standard to use mapping rules
* @param array<string, true> $scannedFiles
* @return array<class-string, string> A class map array
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public static function createMap($path, $excluded = null, IOInterface $io = null, $namespace = null, $autoloadType = null, &$scannedFiles = array())
{
$basePath = $path;
if (is_string($path)) {
if (is_file($path)) {
$path = array(new \SplFileInfo($path));
} elseif (is_dir($path) || strpos($path, '*') !== false) {
$path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "'.$path.
'" which does not appear to be a file nor a folder'
);
}
} elseif (null !== $autoloadType) {
throw new \RuntimeException('Path must be a string when specifying an autoload type');
}
$map = array();
$filesystem = new Filesystem();
$cwd = realpath(getcwd());
foreach ($path as $file) {
$filePath = $file->getPathname();
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
continue;
}
if (!$filesystem->isAbsolutePath($filePath)) {
$filePath = $cwd . '/' . $filePath;
$filePath = $filesystem->normalizePath($filePath);
} else {
$filePath = preg_replace('{[\\\\/]{2,}}', '/', $filePath);
}
$realPath = realpath($filePath);
// if a list of scanned files is given, avoid scanning twice the same file to save cycles and avoid generating warnings
// in case a PSR-0/4 declaration follows another more specific one, or a classmap declaration, which covered this file already
if (isset($scannedFiles[$realPath])) {
continue;
}
// check the realpath of the file against the excluded paths as the path might be a symlink and the excluded path is realpath'd so symlink are resolved
if ($excluded && preg_match($excluded, strtr($realPath, '\\', '/'))) {
continue;
}
// check non-realpath of file for directories symlink in project dir
if ($excluded && preg_match($excluded, strtr($filePath, '\\', '/'))) {
continue;
}
$classes = self::findClasses($filePath);
if (null !== $autoloadType) {
$classes = self::filterByNamespace($classes, $filePath, $namespace, $autoloadType, $basePath, $io);
// if no valid class was found in the file then we do not mark it as scanned as it might still be matched by another rule later
if ($classes) {
$scannedFiles[$realPath] = true;
}
} else {
// classmap autoload rules always collect all classes so for these we definitely do not want to scan again
$scannedFiles[$realPath] = true;
}
foreach ($classes as $class) {
// skip classes not within the given namespace prefix
if (null === $autoloadType && null !== $namespace && '' !== $namespace && 0 !== strpos($class, $namespace)) {
continue;
}
if (!isset($map[$class])) {
$map[$class] = $filePath;
} elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))) {
$io->writeError(
'<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>'
);
}
}
}
return $map;
}
/**
* Remove classes which could not have been loaded by namespace autoloaders
*
* @param array<int, class-string> $classes found classes in given file
* @param string $filePath current file
* @param string $baseNamespace prefix of given autoload mapping
* @param string $namespaceType psr-0|psr-4
* @param string $basePath root directory of given autoload mapping
* @param ?IOInterface $io IO object
* @return array<int, class-string> valid classes
*/
private static function filterByNamespace($classes, $filePath, $baseNamespace, $namespaceType, $basePath, $io)
{
$validClasses = array();
$rejectedClasses = array();
$realSubPath = substr($filePath, strlen($basePath) + 1);
$realSubPath = substr($realSubPath, 0, strrpos($realSubPath, '.'));
foreach ($classes as $class) {
// silently skip if ns doesn't have common root
if ('' !== $baseNamespace && 0 !== strpos($class, $baseNamespace)) {
continue;
}
// transform class name to file path and validate
if ('psr-0' === $namespaceType) {
$namespaceLength = strrpos($class, '\\');
if (false !== $namespaceLength) {
$namespace = substr($class, 0, $namespaceLength + 1);
$className = substr($class, $namespaceLength + 1);
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $namespace)
. str_replace('_', DIRECTORY_SEPARATOR, $className);
} else {
$subPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
}
} elseif ('psr-4' === $namespaceType) {
$subNamespace = ('' !== $baseNamespace) ? substr($class, strlen($baseNamespace)) : $class;
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $subNamespace);
} else {
throw new \RuntimeException("namespaceType must be psr-0 or psr-4, $namespaceType given");
}
if ($subPath === $realSubPath) {
$validClasses[] = $class;
} else {
$rejectedClasses[] = $class;
}
}
// warn only if no valid classes, else silently skip invalid
if (empty($validClasses)) {
foreach ($rejectedClasses as $class) {
if ($io) {
$io->writeError("<warning>Class $class located in ".preg_replace('{^'.preg_quote(getcwd()).'}', '.', $filePath, 1)." does not comply with $namespaceType autoloading standard. Skipping.</warning>");
}
}
return array();
}
return $validClasses;
}
/**
* Extract the classes in the given file
*
* @param string $path The file to check
* @throws \RuntimeException
* @return array<int, class-string> The found classes
*/
private static function findClasses($path)
{
$extraTypes = self::getExtraTypes();
// Use @ here instead of Silencer to actively suppress 'unhelpful' output
// @link https://github.com/composer/composer/pull/4886
$contents = @php_strip_whitespace($path);
if (!$contents) {
if (!file_exists($path)) {
$message = 'File at "%s" does not exist, check your classmap definitions';
} elseif (!Filesystem::isReadable($path)) {
$message = 'File at "%s" is not readable, check its permissions';
} elseif ('' === trim(file_get_contents($path))) {
// The input file was really empty and thus contains no classes
return array();
} else {
$message = 'File at "%s" could not be parsed as PHP, it may be binary or corrupted';
}
$error = error_get_last();
if (isset($error['message'])) {
$message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message'];
}
throw new \RuntimeException(sprintf($message, $path));
}
// return early if there is no chance of matching anything in this file
preg_match_all('{\b(?:class|interface'.$extraTypes.')\s}i', $contents, $matches);
if (!$matches) {
return array();
}
$p = new PhpFileCleaner($contents, count($matches[0]));
$contents = $p->clean();
unset($p);
preg_match_all('{
(?:
\b(?<![\$:>])(?P<type>class|interface'.$extraTypes.') \s++ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s++[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+)? \s*+ [\{;]
)
}ix', $contents, $matches);
$classes = array();
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
// skip anon classes extending/implementing
if ($name === 'extends' || $name === 'implements') {
continue;
}
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
// In Hack, something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
$name = rtrim($name, ':');
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
}
/**
* @return string
*/
private static function getExtraTypes()
{
static $extraTypes = null;
if (null === $extraTypes) {
$extraTypes = PHP_VERSION_ID < 50400 ? '' : '|trait';
if (PHP_VERSION_ID >= 80100 || (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>='))) {
$extraTypes .= '|enum';
}
PhpFileCleaner::setTypeConfig(array_merge(array('class', 'interface'), array_filter(explode('|', $extraTypes))));
}
return $extraTypes;
}
}
| {
"content_hash": "6d079bb74a27caa6bffe7bd123f1de5e",
"timestamp": "",
"source": "github",
"line_count": 295,
"max_line_length": 217,
"avg_line_length": 42.14915254237288,
"alnum_prop": 0.51407431236931,
"repo_name": "nicolas-grekas/composer",
"id": "6910fcb6fc8ff0b1697d9e48e187543dda71d2b7",
"size": "12694",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "src/Composer/Autoload/ClassMapGenerator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Hack",
"bytes": "154"
},
{
"name": "PHP",
"bytes": "6114023"
}
],
"symlink_target": ""
} |
<?php
require 'config_files.php';
require 'int_debug.php';
require 'int_get_message.php';
require 'signin_post.php';
$response = '';
$link = @mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE_NAME);
if (!$link) {
require 'response_500_db_open_error.php';
} else {
$debugState = int_GetDebug($link, 'signin', '');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// get the request data
if (!empty($HTTP_RAW_POST_DATA)) {
$postData = json_decode($HTTP_RAW_POST_DATA,true);
}
// if the data is not in the raw post data, try the post form
if (empty($postData)) {
$postData = $_POST;
}
if (empty($postData)) {
$postData = $_GET;
}
$response = _signin_post($link, $postData);
} else {
// method not supported
$errData = get_error_message ($link, 405);
$response['error'] = $errData;
if ($debugState) {
$response['debug']['module'] = __FILE__;
}
}
mysqli_close($link);
}
require 'format_response.php';
print ($fnResponse);
?> | {
"content_hash": "ef01b24d95fb561ed16692da79ed0a3c",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 71,
"avg_line_length": 23.829268292682926,
"alnum_prop": 0.6192425793244627,
"repo_name": "weblabux/wluxui",
"id": "817d915fe978b66beff3f511aab9425f052f752b",
"size": "2200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/signin.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12857"
},
{
"name": "JavaScript",
"bytes": "40146"
},
{
"name": "PHP",
"bytes": "210537"
},
{
"name": "Shell",
"bytes": "23657"
}
],
"symlink_target": ""
} |
import SimpleHTTPServer
import SocketServer
import sys
from requests import get
PORT = 8000
if __name__ == '__main__':
old_stderr = sys.stderr
with open('httpd.log', 'a') as f:
sys.stderr = f
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
try:
httpd = SocketServer.TCPServer(("", PORT), Handler)
httpd.serve_forever()
except Exception:
sys.stderr = old_stderr
raise
| {
"content_hash": "498502714c6fbee2a8c8af0f8c61536b",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 63,
"avg_line_length": 21.5,
"alnum_prop": 0.587737843551797,
"repo_name": "theonewolf/straplay",
"id": "e6fdfa700e4d7d7b81a840ef3b15c20059274c10",
"size": "496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/test-http.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "285"
},
{
"name": "Python",
"bytes": "33969"
}
],
"symlink_target": ""
} |
package org.monarchinitiative.phenotefx.gui;
import org.monarchinitiative.phenotefx.gui.infoviewer.InfoViewerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* A simple class to tally up mentions of features from typical spread sheets in which column 1 is the
* name of the item and the other columns represent observations in individuals.
*/
public class SpreadsheetTallyTool {
private final File spreadsheet;
private final Map<String, List<String>> items;
public SpreadsheetTallyTool() {
spreadsheet = PopUps.selectFileToOpen(null, null, "Open spreadsheet");
items = new HashMap<>();
}
public void calculateTally() {
int uniqueint = 0;
if (! spreadsheet.exists()) {
PopUps.showInfoMessage("Error", "Could not find spreadsheet");
return;
}
try (BufferedReader br = new BufferedReader(new FileReader(spreadsheet))) {
String line;
line = br.readLine(); // skip header
while ((line=br.readLine()) != null) {
String []fields = line.split("\t");
if (fields.length<2) {
System.out.println("[ERROR] Skipping line (only one field):" + line);
continue;
}
String itemname = fields[0];
if (itemname == null || itemname.isEmpty()) {
continue;
}
if (items.containsKey(itemname)){
// duplicate field name
itemname = String.format("%s-%d", itemname, uniqueint++);
} else {
items.put(itemname, new ArrayList<>());
}
for (int i=1;i<fields.length;i++) {
String field = fields[i] ==null ? "n/a" : fields[i]; // replace null entries
items.get(itemname).add(field);
}
}
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
sb.append(getHTMLHead());
for (String item : items.keySet()) {
List<String> itemlist = items.get(item);
Map<String, Long> counted = itemlist.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
sb.append(getTable(item, counted));
}
sb.append(getFooter());
InfoViewerFactory.openDialog(sb.toString());
}
private static String getTable(String title, Map<String, Long> counted) {
StringBuilder sb = new StringBuilder();
sb.append("<table>\n<caption>").append( title).append( "</caption>\n")
.append(" <tr><th>Item</th><th>Count</th></tr>\n");
for (Map.Entry<String, Long> entry : counted.entrySet()) {
sb.append("<tr><td>" + entry.getKey() + "</td><td>" + entry.getValue() + "</td></tr>\n");
}
sb.append("</table>\n<br/><br/>");
return sb.toString();
}
private static String getHTMLHead() {
return "<html><body>\n" +
inlineCSS() +
"<h1>PhenoteFX: Tallying Phenotypes from Spreadsheet</h1>";
}
private static String getFooter() {
return "</body></html>";
}
private static String inlineCSS() {
return "<head><style>\n" +
" html { margin: 0; padding: 0; }" +
"body { font: 75% georgia, sans-serif; line-height: 1.88889;color: #001f3f; margin: 10; padding: 10; }"+
"p { margin-top: 0;text-align: justify;}"+
"h2,h3 {font-family: 'serif';font-size: 1.4em;font-style: normal;font-weight: bold;"+
"letter-spacing: 1px; margin-bottom: 0; color: #001f3f;}"+
"caption {\n" +
" font-weight: bold;\n" +
" text-align: left;\n" +
" border-style: solid;\n" +
" border-width: 1px;\n" +
" border-color: #666666;\n" +
"}" +
"table {\n" +
"font-family: \"Lato\",\"sans-serif\"; } /* added custom font-family */\n" +
" \n" +
"table.one { \n" +
"margin-bottom: 3em; \n" +
"border-collapse:collapse; } \n" +
" \n" +
"td { \n" +
"text-align: center; \n" +
"width: 10em; \n" +
"padding: 1em; } \n" +
" \n" +
"th { \n" +
"text-align: center; \n" +
"padding: 1em;\n" +
"background-color: #e8503a; /* added a red background color to the heading cells */\n" +
"color: white; } /* added a white font color to the heading text */\n" +
" \n" +
"tr { \n" +
"height: 1em; }\n" +
" \n" +
"table tr:nth-child(even) { /* added all even rows a #eee color */\n" +
" background-color: #eee; }\n" +
" \n" +
"table tr:nth-child(odd) { /* added all odd rows a #fff color */\n" +
"background-color:#fff; }" +
" </style></head>";
}
}
| {
"content_hash": "55d811778588f1e78df2ecf2dd7f3d9d",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 120,
"avg_line_length": 39.082191780821915,
"alnum_prop": 0.48615492464072907,
"repo_name": "pnrobinson/hphenote",
"id": "148cc99f5a25f9f3b70461890d762f01cb1910d8",
"size": "6353",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/monarchinitiative/phenotefx/gui/SpreadsheetTallyTool.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5118"
},
{
"name": "Java",
"bytes": "196227"
},
{
"name": "Shell",
"bytes": "55"
}
],
"symlink_target": ""
} |
using System;
using System.Data.SqlClient;
using System.Data;
namespace BaseLibrary
{
/// <summary>
/// Methods to connect to SQL Server
/// </summary>
internal class ConnectionTools
{
static string getConnectionStr = System.Configuration.ConfigurationManager.AppSettings["ConnStr"].ToString();
/// <summary>
/// Get the connection object
/// </summary>
/// <param name="text">The query or Stored procedure to execute</param>
/// <param name="type">Define if it's a query or a stored procedure</param>
/// <returns>The connection</returns>
internal static SqlCommand _createConnection(string text, CommandType type)
{
SqlCommand Command;
SqlConnection Connection = new SqlConnection(getConnectionStr);
Command = new SqlCommand(text, Connection);
Command.CommandType = type;
return Command;
}
/// <summary>
/// Get the connection object
/// </summary>
/// <param name="text">The query or Stored procedure to execute</param>
/// <param name="type">Define if it's a query or a stored procedure</param>
/// <param name="connStr">Connection string to use</param>
/// <returns>The connection</returns>
internal static SqlCommand _createConnection(string text, CommandType type, string connStr)
{
SqlCommand Command;
SqlConnection Connection = new SqlConnection(connStr);
Command = new SqlCommand(text, Connection);
Command.CommandType = type;
return Command;
}
/// <summary>
/// Get the result of the SELECT statement in a DataTable
/// </summary>
/// <param name="Command">The command to open</param>
/// <returns>The DataTable with the SELECT statement</returns>
internal static DataTable _getDataTable(SqlCommand Command)
{
DataTable dt = new DataTable();
try
{
Command.Connection.Open();
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = Command;
Adapter.Fill(dt);
}
catch (Exception ex) { ex.logThisException(); }
finally
{
Command.Connection.Dispose();
Command.Dispose();
}
return dt;
}
/// <summary>
/// Get the result of the SELECT statements in a DataSet
/// </summary>
/// <param name="Command">The command to open</param>
/// <returns>The DataSet with the SELECT statements</returns>
internal static DataSet _getDataSet(SqlCommand Command)
{
DataSet ds = new DataSet();
try
{
Command.Connection.Open();
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = Command;
Adapter.Fill(ds);
}
catch (Exception ex) { ex.logThisException(); }
finally
{
Command.Connection.Dispose();
Command.Dispose();
}
return ds;
}
/// <summary>
/// Execute the command
/// </summary>
/// <param name="Command">The command to open</param>
/// <returns>True if one or more rows were affected, other way False </returns>
internal static bool _executeNonQuery(SqlCommand Command)
{
try
{
Command.Connection.Open();
return (Command.ExecuteNonQuery() > 0) ? true : false;
}
catch (Exception ex) { ex.logThisException(); return false; }
finally
{
Command.Connection.Dispose();
Command.Dispose();
}
}
}
} | {
"content_hash": "4fb9c8d07c706462d86a6ec8afa6b2a2",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 117,
"avg_line_length": 36.43119266055046,
"alnum_prop": 0.5434399395618232,
"repo_name": "JEnriqueZS/DAL-BaseLibrary",
"id": "377de84188dbf77508463dd88a30f40718ec7c24",
"size": "3973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BaseLibrary/ConnectionTools.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "29790"
}
],
"symlink_target": ""
} |
<mvc:View
controllerName="sap.ui.demo.walkthrough.controller.HelloPanel"
xmlns="sap.m"
xmlns:mvc="sap.ui.core.mvc">
<Panel
headerText="{i18n>helloPanelTitle}"
class="sapUiResponsiveMargin"
width="auto">
<content>
<Button
id="helloDialogButton"
text="{i18n>openDialogButtonText}"
press=".onOpenDialog"
class="sapUiSmallMarginEnd"/>
<Button
text="{i18n>showHelloButtonText}"
press=".onShowHello"
class="myCustomButton"/>
<Input
value="{/recipient/name}"
valueLiveUpdate="true"
width="60%"/>
<FormattedText
htmlText="Hello {/recipient/name}"
class="sapUiSmallMargin sapThemeHighlight-asColor myCustomText"/>
</content>
</Panel>
</mvc:View>
| {
"content_hash": "8d7f1d61a338d7b5a753d6ce642eed71",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 69,
"avg_line_length": 25.428571428571427,
"alnum_prop": 0.6910112359550562,
"repo_name": "SAP/openui5",
"id": "f13ca82cd40fda673a98af2ebdabfbbb88a80f85",
"size": "712",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/sap.m/test/sap/m/demokit/tutorial/walkthrough/17/webapp/view/HelloPanel.view.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "294216"
},
{
"name": "Gherkin",
"bytes": "17201"
},
{
"name": "HTML",
"bytes": "6443688"
},
{
"name": "Java",
"bytes": "83398"
},
{
"name": "JavaScript",
"bytes": "109546491"
},
{
"name": "Less",
"bytes": "8741757"
},
{
"name": "TypeScript",
"bytes": "20918"
}
],
"symlink_target": ""
} |
package org.mamasdelrio.android.views;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import org.mamasdelrio.android.R;
/**
* Created by sudars on 8/19/16.
*/
public class TwoItemSingleChoiceView extends RelativeLayout implements
Checkable {
public TwoItemSingleChoiceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TwoItemSingleChoiceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TwoItemSingleChoiceView(Context context) {
super(context);
}
@Override
public boolean isChecked() {
RadioButton c = (RadioButton) findViewById(R.id.radiobutton);
return c.isChecked();
}
@Override
public void setChecked(boolean checked) {
RadioButton c = (RadioButton) findViewById(R.id.radiobutton);
c.setChecked(checked);
}
@Override
public void toggle() {
RadioButton c = (RadioButton) findViewById(R.id.radiobutton);
c.setChecked(!c.isChecked());
}
}
| {
"content_hash": "c9650c8da383fe48ff4ed9bf812f2b2a",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 85,
"avg_line_length": 22.725490196078432,
"alnum_prop": 0.7394305435720449,
"repo_name": "srsudar/MamasDelRioAndroid",
"id": "2988b385ed39a1682e68e05ff282314bef6929a7",
"size": "1159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/org/mamasdelrio/android/views/TwoItemSingleChoiceView.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1577314"
}
],
"symlink_target": ""
} |
var split = require('./')
var salad = {
apples: 1,
bananas: 3,
carrots: 2
}
var loudIngredients = split(salad).map(function (ingredient) {
return {
key: ingredient.key.toUpperCase(),
value: ingredient.value * 3
}
})
inspect('loud ingredients', loudIngredients)
var loudSalad = split.join(loudIngredients)
inspect('loud salad', loudSalad)
function inspect (msg, item) {
console.log(msg + '\n', require('util').inspect(item, {colors: true, depth: 30}))
return item
}
| {
"content_hash": "5d760216b81782c0c396d5e646d88639",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 83,
"avg_line_length": 19.72,
"alnum_prop": 0.6734279918864098,
"repo_name": "timoxley/split-object",
"id": "09b3db01973092414585d1591633c34bdfbea2b7",
"size": "493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3430"
}
],
"symlink_target": ""
} |
Here's an example of a module that has two parts: a service and a db.
The service depends on the db.
Here's the `db.js`:
```javascript
module.exports = Db;
function Db() {
}
Db.$inject = [];
Db.prototype.answer = function () {
return 42;
};
```
And here's `service.js`:
```javascript
module.exports = Service;
function Service(db) {
this._db = db;
}
Service.$inject = [
'./db'
];
Service.prototype.answer = function () {
return this._db.answer();
};
```
Note how the service has one special property `$inject`.
It is an array of paths of modules that are to be "injected".
Use this just as you use `require()`. The [exact same rules
that Node.js uses for resolving the modules](http://nodejs.org/api/modules.html#modules_all_together)
apply.
The only difference is that if the `$inject`ed module
is a "class" (function) which has an `$inject` property
that is an array, a new instance of that class will be created
and provided as an argument of the constructor
of the class that `$inject`ed it. This happens recursively.
Thus, if the injected class had an `$inject` of its own, that
would be resolved first.
For example, in this case the `Db` has no dependencies to inject,
so a new instance of the `Db` class will be created
and provided as the first argument in `Service`'s constructor.
Finally, here's `index.js` that gets a fresh new instance
of the `Service` class.
```javascript
var DI = require('areus-di'),
di = DI(__dirname);
exports.create = function () {
return di.create('./service');
};
```
The `__dirname` is the root directory, relative to which
`./service` is locataed.
## Providing Existing Packages
Use the `.provide()` method to provide existing packages.
Any package that you give to `.provide()` will be available
in `$inject`. Here's an example:
`index.js`
```javascript
var DI = require('areus-di'),
mongo = require('mongoskin'),
di = DI(__dirname);
di.provide({
db: mongo.db(process.env.MONGO_URI)
});
di.create('./article_service');
```
`article_service.js`
```javascript
module.exports = ArticleService;
function ArticleService(db) {
this._articles = db.collection('articles');
}
ArticleService.$inject = [
'db'
];
ArticleService.prototype.findOne = function (id, cb) {
this._articles.findOne(id, cb);
};
```
## Why Use a Dependency Injector?
- **Isolation** In the example above `Service` did not need to know how `Db`
was created. It did not have to be aware of the dependencies
of `Db` or care whether it was backed by `LevelDB`, `MongoDB`
or `PostgreSQL`. This is important because this implies that
`Db` can change independently from `Service`.
- **Testability** to test `Service` a new instance can be created
with a fake Db as the first argument. For example:
```javascript
var Service = require('../service'),
assert = require('assert'),
fakeDb, service;
fakeDb = {
answer: function () {
return 7;
}
};
service = new Service(fakeDb);
assert.equal(7, service.answer());
```
## Guiding Principles
- No new knowledge needed for basic operation.
- Path resolution follows the [require()](http://nodejs.org/api/modules.html#modules_all_together) algorithm to a T.
- In addition to `require()`, `$inject` instantiates the "class".
## License
[MIT](LICENSE)
| {
"content_hash": "bd7ffd49c1d15b50cafa776ff41faae8",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 118,
"avg_line_length": 22.73611111111111,
"alnum_prop": 0.6985339034819792,
"repo_name": "dowjones/di",
"id": "f7bc3b9a81718732319dcdf5a3a29ea2cb3514b0",
"size": "3485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10919"
}
],
"symlink_target": ""
} |
'use strict';
var VersionChecker = require('ember-cli-version-checker');
var path = require('path');
var isModuleUnification;
module.exports = {
name: 'ember-resolver',
emberResolverFeatureFlags() {
var resolverConfig = {}; //TODO: load from ember-cli-build.js
return Object.assign({
/* Add default feature flags here, for now there is none */
}, resolverConfig.features);
},
init: function() {
this._super.init.apply(this, arguments);
this.options = this.options || {};
if (process.env.EMBER_CLI_MODULE_UNIFICATION) {
this.project.isModuleUnification = function () {
return true;
}
}
this._emberResolverFeatureFlags = this.emberResolverFeatureFlags();
isModuleUnification = !!this.project.isModuleUnification && this.project.isModuleUnification();
this.options.babel = {
loose: true,
plugins: [
[require('babel-plugin-debug-macros').default, {
debugTools: {
source: '@ember/debug'
},
envFlags: {
source: 'ember-resolver-env-flags',
flags: { DEBUG: process.env.EMBER_ENV != 'production' }
},
features: {
name: 'ember-resolver',
source: 'ember-resolver/features',
flags: this._emberResolverFeatureFlags
}
}]
]
};
},
treeForAddon: function() {
var MergeTrees = require('broccoli-merge-trees');
let addonTrees = [].concat(
this._super.treeForAddon.apply(this, arguments),
isModuleUnification && this._moduleUnificationTrees()
).filter(Boolean);
return new MergeTrees(addonTrees);
},
_moduleUnificationTrees() {
var resolve = require('resolve');
var Funnel = require('broccoli-funnel');
let featureTreePath = path.join(this.root, 'mu-trees/addon');
var featureTree = new Funnel(featureTreePath, {
destDir: 'ember-resolver'
});
var glimmerResolverSrc = require.resolve('@glimmer/resolver/package');
var glimmerResolverPath = path.dirname(glimmerResolverSrc);
var glimmerResolverTree = new Funnel(glimmerResolverPath, {
srcDir: 'dist/modules/es2017',
destDir: '@glimmer/resolver'
});
var glimmerDISrc = resolve.sync('@glimmer/di', { basedir: glimmerResolverPath });
var glimmerDITree = new Funnel(path.join(glimmerDISrc, '../../../..'), {
srcDir: 'dist/modules/es2017',
destDir: '@glimmer/di'
});
return [
this.preprocessJs(featureTree, { registry: this.registry }),
this.preprocessJs(glimmerResolverTree, { registry: this.registry }),
this.preprocessJs(glimmerDITree, { registry: this.registry }),
];
},
included: function() {
this._super.included.apply(this, arguments);
var checker = new VersionChecker(this);
var dep = checker.for('ember-cli', 'npm');
if (dep.lt('2.0.0')) {
this.monkeyPatchVendorFiles();
}
this.app.import('vendor/ember-resolver/legacy-shims.js');
},
monkeyPatchVendorFiles: function() {
var filesToAppend = this.app.legacyFilesToAppend;
var legacyResolverIndex = filesToAppend.indexOf(this.app.bowerDirectory + '/ember-resolver/dist/modules/ember-resolver.js');
if (legacyResolverIndex > -1) {
filesToAppend.splice(legacyResolverIndex, 1);
}
}
};
| {
"content_hash": "d5e399b0d82477c445a30164da557dd9",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 128,
"avg_line_length": 30.272727272727273,
"alnum_prop": 0.6396396396396397,
"repo_name": "gabz75/ember-cli-deploy-redis-publish",
"id": "3713b81f0e6f10783c6fa7aaa26728cd9119efb7",
"size": "3330",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/ember-resolver/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1708"
},
{
"name": "JavaScript",
"bytes": "11587"
}
],
"symlink_target": ""
} |
#include <string>
#include <iostream>
using namespace std;
template <class T>
class StringTest {
public:
virtual void runTest();
void testFunction();
};
template <class T>
void StringTest<T>:: runTest() {
testFunction ();
}
template <class T>
void StringTest <T>::testFunction() {
// initialize s with string literal
cout << "in StringTest" << endl;
string s("I am a shot string");
cout << s << endl;
// insert 'r' to fix "shot"
s.insert(s.begin()+10,'r' );
cout << s << endl;
// concatenate another string
s += "and now a longer string";
cout << s << endl;
// find position where blank needs to be inserted
string::size_type spos = s.find("and");
s.insert(spos, " ");
cout << s << endl;
// erase the concatenated part
s.erase(spos);
cout << s << endl;
}
int main() {
StringTest<wchar_t> ts;
ts.runTest();
}
/* output:
I am a shot string
I am a short string
I am a short stringand now a longer string
I am a short string and now a longer string
I am a short string
*/
| {
"content_hash": "63b5f491512c4887524addb7d2ec2475",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 52,
"avg_line_length": 19,
"alnum_prop": 0.6267942583732058,
"repo_name": "execunix/vinos",
"id": "2e491883d73237b30146dc29b37fd923cf77e5d1",
"size": "1797",
"binary": false,
"copies": "41",
"ref": "refs/heads/master",
"path": "external/gpl3/gdb/dist/gdb/testsuite/gdb.cp/bs15503.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
The MIT License (MIT)
Copyright (c) 2015 108anup
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.
| {
"content_hash": "662cdc6856ea73895677b958448f3ae5",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 78,
"avg_line_length": 51.142857142857146,
"alnum_prop": 0.8035381750465549,
"repo_name": "108anup/course-comparator",
"id": "f525c2be94b7223be727667f4581c53d878bc5df",
"size": "1074",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "651"
},
{
"name": "PHP",
"bytes": "9056"
}
],
"symlink_target": ""
} |
require File.dirname(__FILE__) + '/unit_test_helper'
require 'crack'
require 'restclient'
require File.dirname(__FILE__) + "/../init"
class TicketTest < Test::Unit::TestCase
def test_query_ticket
result = UuyoooTicket.get_with('queryTicket',{:goodsId=>"xxxxxx"})
p result.inspect,'----queryTicket---'
end
#第三方接口有问题
def test_query_film
result = UuyoooTicket.get_with('queryFilm',{:goodsId=>"xxxxxx"})
p result.inspect,'----queryFilm---'
end
def test_buy_film
result = UuyoooTicket.get_with('buyFilm',{:goodsId=>"xxxxxx",:goodsNum=>"1",:tranSeq=>"xxxxxx",:time=>"20120531154000",:userPhone=>"xxxxxx"})
p result.inspect,'----buyFilm---'
end
end
| {
"content_hash": "25777bff71f9e6106f3f19d4b46b1acd",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 145,
"avg_line_length": 30,
"alnum_prop": 0.6594202898550725,
"repo_name": "foyoto/uuyooo_sdk",
"id": "fac7ea2ca3148b855dd86998dc3986f04ec404c5",
"size": "706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/ticket_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "4537"
}
],
"symlink_target": ""
} |
package com.codefollower.douyu.http.ssl;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.TrustManager;
public interface SSLUtil {
public SSLContext createSSLContext() throws Exception;
public KeyManager[] getKeyManagers() throws Exception;
public TrustManager[] getTrustManagers() throws Exception;
public void configureSessionContext(SSLSessionContext sslSessionContext);
}
| {
"content_hash": "59e196cd5e3df999f6786ba4e85cbc0f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 77,
"avg_line_length": 27,
"alnum_prop": 0.7839506172839507,
"repo_name": "codefollower/Open-Source-Research",
"id": "35e9ac2d62a8c0dd40bd4c2eeb91db338e254eca",
"size": "1299",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Douyu-0.7.1/douyu-http/src/main/java/com/codefollower/douyu/http/ssl/SSLUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "146130"
},
{
"name": "C",
"bytes": "1175615"
},
{
"name": "C++",
"bytes": "52932465"
},
{
"name": "CSS",
"bytes": "13948"
},
{
"name": "D",
"bytes": "90195"
},
{
"name": "Java",
"bytes": "32377266"
},
{
"name": "JavaScript",
"bytes": "39651"
},
{
"name": "Objective-C",
"bytes": "18238"
},
{
"name": "Shell",
"bytes": "276979"
},
{
"name": "XSLT",
"bytes": "351083"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Leveillula taurica f. saussureae Jacz.
### Remarks
null | {
"content_hash": "8051116f744e35f13313f262852dc346",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 38,
"avg_line_length": 11,
"alnum_prop": 0.7132867132867133,
"repo_name": "mdoering/backbone",
"id": "cc53b00d7fc61480eb77704bb25d959d97b695b3",
"size": "217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Leotiomycetes/Erysiphales/Erysiphaceae/Leveillula/Leveillula taurica/Leveillula compositarum saussureae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.alibaba.rocketmq</groupId>
<artifactId>rocketmq-all</artifactId>
<version>3.2.2.R4-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>rocketmq-broker</artifactId>
<name>rocketmq-broker ${project.version}</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-common</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-store</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-remoting</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-client</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-srvutil</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>jboss</groupId>
<artifactId>javassist</artifactId>
</dependency>
</dependencies>
</project>
| {
"content_hash": "d896a936af2f87fbd90dd4e49bcfa8db",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 68,
"avg_line_length": 28.1875,
"alnum_prop": 0.7012195121951219,
"repo_name": "lizhanhui/Alibaba_RocketMQ",
"id": "8fdd761ad6736b84a69861ff8bf39d0ae2b58dcb",
"size": "1804",
"binary": false,
"copies": "1",
"ref": "refs/heads/hotfix",
"path": "rocketmq-broker/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "127"
},
{
"name": "Java",
"bytes": "3225615"
},
{
"name": "Python",
"bytes": "9929"
},
{
"name": "Shell",
"bytes": "22319"
},
{
"name": "Thrift",
"bytes": "1523"
}
],
"symlink_target": ""
} |
At this point we're going to talk about best practices to work with git.
## Index
* [Prologue](#prologue)
* [Getting Started](#getting-started)
* [Setting up git](#setting-up-git)
* [gitignore](#gitignore)
* [Commit Messages](#commit-messages)
* [Commit Often](#commit-often)
* [Push only finished and tested code](#push-only-finished-and-tested-code)
* [Divide repositories](#divide-repositories)
* [History](#history)
* [Use the shell](#use-the-shell)
* [Moving files](#moving-files)
* [Large files](#large-files)
* [README.md](#readme-md)
* [Git Flow](#git-flow)
* [Git Flow Rules](#git-flow-rules)
* [Branches](#branches)
* [Main branches](#main-branches)
* [Master branch](#master-branch)
* [Develop branch](#develop-branch)
* [Support branches](#support-branches)
* [Feature branches](#feature-branches)
* [Flow](#flow)
* [Feature flow](#feature-flow)
* [Releases](#releases)
* [Hotfixes](#hotfixes)
* [Support branches](#support-branches)
* [Working Git Project](#working-git-project)
* [Repositories](#repositories)
* [Commands](#commands)
* [Set up repository](#set-up-repository)
* [Save changes](#save-changes)
* [Sync up](#sync-up)
* [Use branches](#use-branches)
* [Check repository](#check-repository)
* [Undo changes](#undo-changes)
* [Tips](#tips)
* [Versioning](#versioning)
* [Semantic Versioning](#semantic-versioning)
* [Redmine's id-track](#redmines-id-track)
* [Use hooks](#use-hooks)
* [Use tools](#use-tools)
* [Use ssh key](#use-ssh-key)
* [References](#references)
## Prologue
This guide try to help to working teams to use git and git flows correctly. Is very recommended that all team's members working with git in the same way, for this goal this guide will contain some usefull advices and tips for the correct use of git and help to unify the way of work with it.
## Getting Started
### Setting up git
The first thing to do is setting up git.
```
git config --global user.name Nombre
git config --global user.email correo@dominio.com
git config --global core.filemode false
```
### gitignore
When you work with git there are some files that's you shouldn't upload to the repository like configuration files, ide files, files with passwords or connection params, etc. For this goal, exists the .gitignore file, and you need create it and include here the list of files or folders to exclude of the version control.
It's very important **include at .gitignore the files that contains confidential information like credendials** to services, by security reasons these type of information should never be uploaded to the remote repository.
Usually, you can create some templates files for this type of information with its fields empty. For example a file db.config.sample with content:
```
db.host=
db.url=
db.password=
```
Next, there are some folders and files thats usually have to be added at .gitignore list depending on the programming languaje or ide used:
* General files or folders:
* .log
* log/
* tmp/
* .settings/
* Java applications:
* target/
* .project
* .classpath
* target/
* bin/
* .metadata/
* RemoteSystemsTempFiles/
* Servers/
* NodeJS:
* node_modules/
* Python:
* Files with pyc extension: .pyc
* The jetbrains ides like Pycharm or WebStorm, have a settings folder with the name:
* idea/
### Commit messages
Write descriptive commit messages that explain the changes maked at the commit and his reason. For this goal, is recommended so configure the git repository to force to use messages in commits.
### Commit often
Do commit early and often, have periodic checkpoints help you to have control and solve problems when your code fails, will be easier understand what is different and where the problem may be.
### Push only finished and tested code
Its very important that all code that you push into the remote repository works properly and be tested. All people that synchronize within the repository should be able to execute it without problems.
For ensure this is very recommended using continuous delivery tools for testing code, you can find more information at this [guide](../../qa_testing/sonar/README.md).
### Divide repositories
Often is a good idea create different repositories depending of his functionallity, project or team who work with it. For example, may be interesting have a different repositories for the backend application than the frontend application, and may be interesting have one for the devops configuration files like puppet.
### History
Don't change the history published, for mantain a true traceability of the changes and preserving for problems.
For this goal you should use the option *--no-ff* with merge commands to maintain all commit history in the merged branch. The differences from a merge with --no-ff option and other without it is shown in the next picture:
![alt text](static/merge-without-ff.jpg "difference-merges")
You should configure your repository against history changes. If you initialize a bare git repository with *--shared* it will automatically get the *git-config "receive.denyNonFastForwards"* set to true.
### Use the shell
There are a lot of IDEs that have its own git plugins, but very often this plugins doesn't works fine in determinated features. The most reliable way to syncronize with git is install git and use the shell to work with git.
### Moving Files
If you need move some file or directory to another path, use the git mv command. For preserving correctly traceability of the changes, you should commit separate the moving of file before make changes of the file, because when you move a file the git internally delete and create new file and you can't see the differences between latest version.
### Large Files
Don't commit binary files or very large files if you can avoid it. Git is not intended for it.
### README.md
Write a text file called README.md in the main directory of project. This file must have the main information about the code, how use and configure it and how can execute it. This file must contains:
* Information about the application configuration, must cover configuration files, dependencies, libraries or tools that are needed for use or install it.
* Information about how install and execute the application.
* Information to test the application and test the qa quality.
* If is a application or library that you can invoke, like an web application or an service web, is important include the information about you can call it.
* For applications which will run on Docker container, is important include here the information necessary to build the Docker image and how run the container.
## Git Flow
It is highly recommended that **all team members follow the same procedural rules** when using git. The workflow described below is an accepted procedure worldwide for small work teams.
![git flow graph][]
[git flow graph]: static/gitflow.jpg "git flow graph"
### Git Flow Rules
Git Flow establishes the following restrictions:
* There are only one central repository: **origin**. Every developer pull and pushes to origin.
* There are only two main branches: **develop** and **master**.
* There are three support branch types: **feature**, **release** and **hotfix**.
* Always merge with --no-ff option.
### Branches
Git Flow defines two branch types, main branches and support branches.
### Main branches
The Main branches are **develop** and **master**.
#### Master branch
The master branch is the default git branch. This is a special branch.
Git flow establishes the following restictions on this branch:
* Never delete this branch.
* Never do commits over this branch directly: only merge commits are allowed.
* Only do merges from release and hotfix branches.
#### Develop branch
The develop branch is a long running branch and must be created from master.
* Never delete this branch.
* Never do commits over this branch directly: only merge commits are allowed.
* All features must be merged in develop
* When develop reaches a stable point, will be merged back into master, throug a release branch.
* Once a release process is finished, the release branch must be merged back into develop.
* Once a hotfix process is finished, the hotfix branch must be merged back into develop.
#### Support branches
The support branches are **short running branches**.
Those branches are created to follow one of the three processes defined on Git Flow.
Every support branch has defined from what branch must be created and on what branch/es must be merged.
#### Feature branch
This is the developer working branch.
* The feature branch always is created from develop branch.
* We can create several feature branches.
* It's recommended to create only a feature for each developer and feature to develop, and to create shorter features as posible.
* The feature branch always must be merged back into develop.
* Don't merge any other branch into feature branch. (i.e.: develop branch)
* The feature branch must be deleted once finished: merged back into develop.
### Flow
Git Flow defines three sub work flows:
#### Feature Flow
Each task of development must be created in a feature branch following the Feature flow.
![git flow feature graph][]
[git flow feature graph]: static/feature-gitflow.jpg "git flow feature graph"
Steps in the feature flow:
``` sh
# gitflow feature Start
git checkout -b feature/lorem-ipsum develop
# Editing
edit, git add .., git commit ..
# gitflow feature Finish
git checkout develop
git merge --no-ff feature/lorem-ipsum
git branch -d feature/lorem-ipsum
# Publish code
git pull origin develop
git push origin develop
```
#### Releases
When the source code in the develop branch reaches a stable point and is ready to be released, all of the changes should be merged back into master somehow and then tagged with a release number.
![git flow release graph][]
[git flow release graph]: static/release.jpg "git flow release graph"
Steps in the release flow:
``` sh
# gitflow release start
git checkout -b release/0.1.0 develop
# Editing
edit, git add .., git commit ..
# gitflow release finish
git checkout master
git merge --no-ff release/0.1.0
git tag -a v0.1.0
git checkout develop
git merge --no-ff release/0.1.0
git branch -d release/0.1.0
git push origin 0.1.0
git push origin develop
git push origin master
```
#### Hotfixes
They arise from the necessity to act immediately upon an undesired state of a live production version.
When a critical bug in a production version must be resolved immediately, a hotfix branch may be branched off from the corresponding tag on the master branch that marks the production version.
![git flow hotfix graph][]
[git flow hotfix graph]: static/hotfix.jpg "git flow hotfix graph"
Steps in the release flow:
``` sh
# gitflow hotfix start
git checkout -b hotfix/0.1.1 master
# Editing
edit, git add .., git commit ..
# gitflow hotfix finish
git checkout master
git merge --no-ff hotfix/0.1.1
git tag -a 0.1.1
git checkout develop
git merge --no-ff hotfix/0.1.1
git branch -d hotfix/0.1.1
git push origin develop
git push origin master
```
## Working Git Project
In a real Git project in addition to use [Git Flow](#git-flow), users must know stage where they are working on, that is to say, leads to having to play two different types of repositories.
### Repositories
The purpose of Git is to manage a project or a set of files as they change over time, therefore, Git stores this information in a data structure called a **repository** which often located in a ``.git`` subdirectory at the root of working repository.
![stage git project image](static/repositories.png)
As shown in the image above, Git project is made up of:
* Local repository: local work area is split into:
* Working directory: folders/files that you are currently working on.
* Staging area (Index): is a holding area for changes that will be committed, so you can control what parts of the working directory go into the next level.
* HEAD: a reference to a specific commit (usually points to the most recent commit on the current branch) and it serves two major purposes: tells Git which commit to take files when checkout is executed and tells Git where to put new commits when commit is executed.
* Remote repository: place where code is stored like GitHub, Bitbucket, etc.
In summary, each file will go moving through of the distinct phases until to Remote repository.
### Commands
Once we know the stage of Git project we can start using Git commands, as shown in the image below:
![git commands image](static/git-commands.png)
Therefore, we will check each of main Git commands regarding to different cases: *set up repository*, *save changes*, *sync up*, *use branches*, *check repository* and *undo changes*.
#### Set up repository
##### git init
Creates a new Git repository that way can transform an existing and unversioned project to a Git repository or initialize a new empty repository.
``` sh
$ git init
```
##### git clone
Clones an existing Git repository into a new directory with a isolated environment that has its own history and manages its own files.
``` sh
$ git clone <repository> <directory>
```
##### git remote
Lets users can create, list and delete connections to repositories so a specified URL is linked to a quick access.
``` sh
# List all connections.
$ git remote
# List all connections along with the URL of each one.
$ git remote -v
# Create a new connection called <name> to a remote repository <url>.
$ git remote add <name> <url>
# Remove the connection called <name> to the remote repository.
$ git remote rm <name>
```
#### Save changes
##### git add
Aggregates the new/updated content from the Working directory to the Staging area(Index) for the next commit.
``` sh
$ git add <file/directory>
```
##### git rm
Deletes files from the Staging area(Index) or from Working directory and Staging area(Index).
``` sh
# Delete a single file from Git repository and also delete it from the Working directory.
$ git rm <file>
# Delete a single file from Git repository without deleting from the Working directory.
$ git rm --cached <file>
```
##### git commit
Stores the current contents from the Staging area(Index) to HEAD in a new commit along with a message describing the changes.
``` sh
$ git commit -m <message>
```
##### git tag
Lets users can create, list and delete tags. A tag is just a reference which points to the current commit.
The two main types of tags are **lightweight** and **annotated**:
- Lightweight tag is just a reference to a specified commit.
- Annotated tag is almost like a lightweight tag but contains a message.
``` sh
# List the available tags in Git.
$ git tag
# Create a lightweight tag
$ git tag <tag_name>
# Create an annotated tag
$ git tag -a -m "<tag_message>" <tag_name>
# Delete a tag
$ git tag -d <tag_name>
# Push all tags to the Remote repository
$ git push origin --tags
```
##### git stash
Stores the current state from the Working directory and Staging area(Index) on a **stack** to get it back later, so that, user can switch branches and it is not necessary to commit half-done work.
``` sh
# Store Working directory and Staging area state
$ git stash
# List the stashes that have been stored
$ git stash list
# Apply the most recent stash to the current line of development
$ git stash apply
# Apply the second most recent stash to the current line of development
$ git stash apply stash@{1}
```
#### Sync up
##### git push
Transfers all commits from HEAD to Remote repository.
``` sh
# Push the work from the specified branch to the named remote repository
$ git push <remote> <branch>
```
##### git fetch
Transfers all commits from Remote repository to HEAD.
``` sh
# Fetch all branches
$ git fetch <remote>
# Fetch only the specified branch
$ git fetch <remote> <branch>
```
##### git pull
Updates the Working directory to the newest commit from Remote repository executing ``git fetch`` and ``git merge`` between the retrieved changes and the current branch.
``` sh
# Update the specified branch from named remote repository
$ git pull <remote> <branch>
```
#### Use branches
##### git checkout
Lets users can navigate between the different branches in this way the Working directory will be updated to the specified branch.
``` sh
# Switch from current branch to another
$ git checkout <branch>
# Create a new branch and switch to it
$ git checkout -b <new-branch>
```
##### git branch
Lets users can create, list, rename and delete branches. A branch stands for an independent line of development but is just pointer to commits.
``` sh
# List all branches from Git repository
$ git branch -a
# Create a new branch
$ git branch <branch>
# Rename a branch
$ git branch -m <old_name> <new_name>
# Delete a branch called <branch> in a safe way because Git prevents deleting the branch if it has unmerged changes.
$ git branch -d <branch>
# Force deleting the specified branch
$ git branch -D <branch>
```
##### git merge
Combines the current development line and a feature branch into a single branch. Git can execute distinct merge algorithms (**fast-forward** or **non-fast-forward**) according to the state of the branches, in order to display differently the merges.
- Fast-forward merge is applied if the current branch has not diverged of feature branch and will just update the branch pointer without creating a new merge commit, achieving the whole commit sequence is linear.
- Non-fast-forward merge forces to create a new merge commit whether the current branch has diverged regarding feature branch or the current branch has not diverged regarding feature branch. In this case, the commit history will emphasize the merge.
In this [section](#history) can visualize the two algorithms graphically.
``` sh
# Combine the specified branch into the current branch and Git will decide the merge algorithm (by default fast-forward)
$ git merge <branch>
# Combine the specified branch into the current branch but always generate a new commit (non-fast-forward)
$ git merge --no-ff <branch>
```
#### Check repository
##### git status
Displays the state of the Working directory and Staging area, therefore, users can see which changes have been staged, which have not and which files are not being tracked by Git.
``` sh
$ git status
```
##### git log
Shows commit history
``` sh
# Show commit logs
$ git log
# Show commit logs with a pretty format
$ git log --graph --decorate --pretty=oneline
```
##### git reflog
Show an overview of the last actions (commits, pull, push, checkout, reset, etc) user did inside of Git repository. **Highlight** actions are only stored in the local machine.
``` sh
$ git reflog
```
##### git diff
Shows the difference of files between the distinct phases of the Local repository.
``` sh
# Differences between the Working directory and the Staging area(Index)
$ git diff
# Differences between the Staging area and the most recent commit(HEAD)
$ git diff --cached
# Differences between the Working directory and the most recent commit(HEAD)
$ git diff HEAD
```
##### git show
Displays distinct types of objects:
- Commits
- Tags
- Trees
- Plain blobs
``` sh
# Display any object in Git
$ git show <object_id>
```
#### Undo changes
##### git checkout
In addition to use checkout command to switch branches also retrieves the specified state to the current development line.
``` sh
# Undo the modified file located in the Working Directory to the HEAD version
$ git checkout -- <file>
# Retrieve all files to a specific version according a determined commit
$ git checkout <commit>
# Retrieve the file to a specific version according a determined commit
$ git checkout <commit> <file>
```
##### git reset
Reset the Working directory and Staging area(Index) according the last commit in the HEAD to the specified state. **Warning:** some Git history might be lost.
``` sh
# Reset the Staging area(Index) to the most recent commit but keep the Working directory unchanged
$ git reset
# Reset the specified file from the Staging area(Index) and keep it in the Working directory unchanged
$ git reset <file>
# Reset the Staging area(Index) and the Working directory to the most recent commit
$ git reset --hard
# Reset the Staging area(Index) to a specified commit but keep the Working directory unchanged
$ git reset <commit>
# Reset the Staging area(Index) and the Working directory to a specified commit
$ git reset --hard <commit>
```
##### git revert
Rool back a commit which has already been pushed and create a new commit to the history with the undone changes. **Highlight:** no Git history will be lost.
``` sh
# Roll back a specified commit
$ git revert <commit>
```
## Tips
### Versioning
It's very important to version your tags with a concrete versioning system to made easy traceability of all your code. We suggest using of a lightweight version specification called [Semantic Versioning](http://semver.org/) thinking to API versiosing, but totally applicable to git tags
#### Semantic Versioning
This is an specification authored by Tom Preston-Werner based on three digits *MAJOR.MINOR.PATCH*
Theses are the main rules about this specification
* A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically. For instance: 1.9.0 -> 1.10.0 -> 1.11.0.
* Major version zero (0.y.z) is for initial development. Anything may change at any time. The code of this tag should not be considered stable.
* Version 1.0.0 defines the first tag with stable code. The way in which the version number is incremented after this release is dependent on how your code change.
* Patch version Z (x.y.Z | x > 0) MUST be incremented if only backwards compatible bug fixes are introduced. A bug fix is defined as an internal change that fixes incorrect behavior.
* Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the code. It MUST be incremented if any functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.
* Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the code. It MAY include minor and patch level changes. Patch and minor version MUST be reset to 0 when major version is incremented.
### Redmine's id-track
In order to improve the traceability of our developments and integrate it with project management tools as Jira or Redmine (inside Beeva) you can start each commit messages with *#id_task*. In this way is possible link task description into Redmine to know what commits is associated with this task.
For example, if there is a task into Redmine with id *17025* and we start commit message (commit -m "#17025 change label value") each message that starts with *"#17025..."* can will be shown into Redmine task description
### Use hooks
Hooks are a good tool to customize version control behavior. Using hooks we can intercept each step of git cycle, client-side and server-side, and launch custom scripts when certain important actions occur.
developments, for example, related with Amazon Web Services should use a pre-commit hook to search for Amazon AWS API keys and to avoid push to the remote repository these credentials, [see the example](https://gist.github.com/DmZ/3a99d829f17af383712b)
To learn deeply about git hooks, please [see documentation](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks)
### Use tools
There are a lot of tools and sites to help you to work better with git. List below show you some tools and web sites interesting for work with git:
* [Gitflow tool](https://github.com/nvie/gitflow). A tool that help you to implemet gitflow workflow.
* [Gitignore.io](https://www.gitignore.io/). A website that generate *.gitignore* file for operating systems, IDEs or programming languages.
* [Tips and scrpts](http://git-scm.com/book/es/v1/Fundamentos-de-Git-Consejos-y-trucos). A very interesting collection with scripts to do your git experience easier.
* [.bashrc](static/git_bashrc). Code to add inside *~/.bashrc* file and help you to know in which branch you are.
### Use ssh key
Sometimes when we are using as a remote repository as a github, we must write our password in each commit. It's a good practice configure a ssh key to do this task easier and avoid writing password with each git sentence. See example for [GitHub](https://help.github.com/articles/generating-ssh-keys/)
### References
* [Git official documentation](https://git-scm.com/doc)
* [GitHub Help](https://help.github.com/)
* [Git Cheatsheet](http://www.git-tower.com/blog/git-cheat-sheet/)
* [Git Flow Cheatsheet](http://danielkummer.github.io/git-flow-cheatsheet/)
* [Successful branching model](http://nvie.com/posts/a-successful-git-branching-model/)
* [Seth Robertson Best Practices](https://sethrobertson.github.io/GitBestPractices/)
___
[BEEVA](http://www.beeva.com) | 2016
| {
"content_hash": "2a2a56fae810e05735dcfb26a81c474f",
"timestamp": "",
"source": "github",
"line_count": 679,
"max_line_length": 407,
"avg_line_length": 37.273932253313696,
"alnum_prop": 0.7529337389861314,
"repo_name": "beeva-arturomartinez/beeva-best-practices",
"id": "a907bd95a2b2fd3b1c78b1b5e8edafc7919eb8c7",
"size": "25336",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "devops/git/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "8390"
}
],
"symlink_target": ""
} |
layout: documentation
title: Query how-to
---
<a name="_Bazel_Query_How_To"> </a>
# Bazel query how-to
This is a quick tutorial to get you started using Bazel's query language to
trace dependencies in your code.
For a language details and `--output` flag details, please see the reference
manual, [Bazel query reference](query.html). You can get help for Bazel query
by typing `bazel help query`.
To execute a query while ignoring errors such as missing targets, use the
`--keep_going` flag.
<a name="_Contents"></a>
## Contents
* [Finding the Dependencies of a Rule](#Finding_the_Dependencies_of_a_Ru)
* [Tracing the Dependency Chain between Two
Packages](#Tracing_the_Dependency_Chain_bet)
* [Aside: implicit dependencies](#Aside_implicit_dependencies)
* [Reverse Dependencies](#Reverse_Dependencies)
* [Miscellaneous Uses](#Miscellaneous_Uses)
* [What exists ...](#What_exists_)
* [What packages exist beneath
`foo`?](#What_packages_exist_beneath_foo_)
* [What rules are defined in the `foo`
package?](#What_rules_are_defined_in_the_foo)
* [What files are generated by rules in the `foo`
package?](#What_files_are_generated_by_rule)
* [What's the set of BUILD files needed to build
`//foo`?](#What_s_the_set_of_BUILD_files_ne)
* [What are the individual tests that a `test_suite` expands
to?](#What_are_the_individual_tests_th)
* [Which of those are C++ tests?](#Which_of_those_are_C_tests_)
* [Which of those are small? Medium?
Large?](#Which_of_those_are_small_Medium_)
* [What are the tests beneath `foo` that match a
pattern?](#What_are_the_tests_beneath_foo_t)
* [What package contains file
`src/main/java/com/example/cache/LRUCache.java`?
](#What_package_contains_file_java_)
* [What is the build label for
`src/main/java/com/example/cache/LRUCache.java`?
](#What_is_the_build_label_for_java)
* [What build rule contains file
`src/main/java/com/example/cache/LRUCache.java` as a
source?](#What_build_rule_contains_file_ja)
* [What package dependencies exist ...](#What_package_dependencies_exist_)
* [What packages does `foo` depend on? (What do I need to check out
to build `foo`)](#What_packages_does_foo_depend_on)
* [What packages does the `foo` tree depend on, excluding
`foo/contrib`?](#What_packages_does_the_foo_)
* [What rule dependencies exist ...](#What_rule_dependencies_exist_)
* [What genproto rules does bar depend
upon?](#What_genproto_rules_does_bar_)
* [Find the definition of some JNI (C++) library that is transitively
depended upon by a Java binary rule in the servlet
tree.](#Find_the_definition_of_some_JNI_)
* [...Now find the definitions of all the Java binaries that
depend on them](#_Now_find_the_definitions_of_all)
* [What file dependencies exist ...](#What_file_dependencies_exist_)
* [What's the complete set of Java source files required to build
QUX?](#What_s_the_complete_set_of_Java_)
* [What is the complete set of Java source files required to build
QUX's tests?](#What_is_the_complete_set_of_Java)
* [What differences in dependencies between X and Y exist
...](#What_differences_in_dependencies)
* [What targets does `//foo` depend on that `//foo:foolib` does
not?](#What_targets_does_foo_depend_on_)
* [What C++ libraries do the `foo` tests depend on that the `//foo`
production binary does _not_ depend
on?](#What_C_libraries_do_the_foo_test)
* [Why does this dependency exist ...](#Why_does_this_dependency_exist_)
* [Why does `bar` depend on
`groups2`?](#Why_does_bar_depend_on_groups)
* [Show me a path from `docker/updater:updater_systest` (a `py_test`)
to some `cc_library` that it depends
upon:](#Show_me_a_path_from_docker_updater)
* [Why does library `//photos/frontend:lib` depend on two variants of
the same library `//third_party/jpeglib` and
`//third_party/jpeg`?](#Why_does_library_photos_fronten)
* [What depends on ...](#What_depends_on_)
* [What rules under bar depend on Y?](#What_rules_under_bar_depend_o)
* [How do I break a dependency ...](#How_do_I_break_a_dependency_)
* [What dependency paths do I have to break to make `bar` no longer
depend on X?](#What_dependency_paths_do_I_have_)
* [Misc ...](#Misc_)
* [How many sequential steps are there in the `ServletSmokeTests`
build?](#How_many_sequential_steps_are_th)
<a name="Finding_the_Dependencies_of_a_Ru"></a>
## Finding the Dependencies of a Rule
To see the dependencies of `//src/main/java/com/example/base:base`, use the
`deps` function in bazel query:
```
$ bazel query "deps(src/main/java/com/example/base:base)"
//resources:translation.xml
//src/main/java/com/example/base:AbstractPublishedUri.java
...
```
This is the set of all targets required to build <code>//src/main/java/com/example/base:base</code>.
<a name="Tracing_the_Dependency_Chain_bet"></a>
## Tracing the Dependency Chain between Two Packages
The library `//third_party/zlib:zlibonly` isn't in the BUILD file for
`//src/main/java/com/example/base`, but it is an indirect dependency. How can
we trace this dependency path? There are two useful functions here:
`allpaths` and `somepath`
```
$ bazel query "somepath(src/main/java/com/example/base:base, third_party/zlib:zlibonly)"
//src/main/java/com/example/base:base
//translations/tools:translator
//translations/base:base
//third_party/py/MySQL:MySQL
//third_party/py/MySQL:_MySQL.so
//third_party/mysql:mysql
//third_party/zlib:zlibonly
$ bazel query "allpaths(src/main/java/com/example/common/base:base, third_party/...)"
...many errors detected in BUILD files...
//src/main/java/com/example/common/base:base
//third_party/java/jsr166x:jsr166x
//third_party/java/sun_servlet:sun_servlet
//src/main/java/com/example/common/flags:flags
//src/main/java/com/example/common/flags:base
//translations/tools:translator
//translations/tools:aggregator
//translations/base:base
//tools/pkg:pex
//tools/pkg:pex_phase_one
//tools/pkg:pex_lib
//third_party/python:python_lib
//translations/tools:messages
//third_party/py/xml:xml
//third_party/py/xml:utils/boolean.so
//third_party/py/xml:parsers/sgmlop.so
//third_party/py/xml:parsers/pyexpat.so
//third_party/py/MySQL:MySQL
//third_party/py/MySQL:_MySQL.so
//third_party/mysql:mysql
//third_party/openssl:openssl
//third_party/zlib:zlibonly
//third_party/zlib:zlibonly_v1_2_3
//third_party/python:headers
//third_party/openssl:crypto
```
<a name="Aside_implicit_dependencies"></a>
### Aside: implicit dependencies
The BUILD file for `src/main/java/com/example/common/base` never references
`//translations/tools:aggregator`. So, where's the direct dependency?
Certain rules include implicit dependencies on additional libraries or tools.
For example, to build a `genproto` rule, you need first to build the Protocol
Compiler, so every `genproto` rule carries an implicit dependency on the
protocol compiler. These dependencies are not mentioned in the build file,
but added in by the build tool. The full set of implicit dependencies is
currently undocumented; read the source code of
[`RuleClassProvider`](https://github.com/bazelbuild/bazel/tree/master/src/main/java/com/example/devtools/build/lib/packages/RuleClassProvider.java).
<a name="Reverse_Dependencies"></a>
## Reverse Dependencies
You might want to know the set of targets that depends on some target. e.g.,
if you're going to change some code, you might want to know what other code
you're about to break. You can use `rdeps(u, x)` to find the reverse
dependencies of the targets in `x` within the transitive closure of `u`.
Unfortunately, invoking, e.g., `rdeps(..., daffie/annotations2:constants-lib)`
is not practical for a large tree, because it requires parsing every BUILD file
and building a very large dependency graph (Bazel may run out of memory). If
you would like to execute this query across a large repository, you may have to
query subtrees and then combine the results.
<a name="Miscellaneous_Uses"></a>
## Miscellaneous Uses
You can use `bazel query` to analyze many dependency relationships.
<a name="What_exists_"></a>
### What exists ...
<a name="What_packages_exist_beneath_foo_"></a>
#### What packages exist beneath `foo`?
```sh
bazel query 'foo/...' --output package
```
<a name="What_rules_are_defined_in_the_gw"></a>
#### What rules are defined in the `foo` package?
```sh
bazel query 'kind(rule, foo:all)' --output label_kind
```
<a name="What_files_are_generated_by_rule"></a>
#### What files are generated by rules in the `foo` package?
```sh
bazel query 'kind("generated file", //foo:*)'
```
<a name="What_s_the_set_of_BUILD_files_ne"></a>
#### What's the set of BUILD files needed to build `//foo`?
bazel query 'buildfiles(deps(//foo))' --output location | cut -f1 -d:
<a name="What_are_the_individual_tests_th"></a>
#### What are the individual tests that a `test_suite` expands to?
```sh
bazel query 'tests(//foo:smoke_tests)'
```
<a name="Which_of_those_are_C_tests_"></a>
##### Which of those are C++ tests?
```sh
bazel query 'kind(cc_.*, tests(//foo:smoke_tests))'
```
<a name="Which_of_those_are_small_Medium_"></a>
#### Which of those are small? Medium? Large?
```sh
bazel query 'attr(size, small, tests(//foo:smoke_tests))'
bazel query 'attr(size, medium, tests(//foo:smoke_tests))'
bazel query 'attr(size, large, tests(//foo:smoke_tests))'
```
<a name="What_are_the_tests_beneath_foo_t"></a>
#### What are the tests beneath `foo` that match a pattern?
```sh
bazel query 'filter("pa?t", kind(".*_test rule", //foo/...))'
```
The pattern is a regex and is applied to the full name of the rule. It's similar to doing
```sh
bazel query 'kind(".*_test rule", //foo/...)' | grep -E 'pa?t'
```
<a name="What_package_contains_file_java_"></a>
#### What package contains file src/main/java/com/example/cache/LRUCache.java`?
```sh
bazel query 'buildfiles(src/main/java/com/example/cache/LRUCache.java)' --output=package
```
<a name="What_is_the_build_label_for_java"></a>
#### What is the build label for src/main/java/com/example/cache/LRUCache.java?
```sh
bazel query src/main/java/com/example/cache/LRUCache.java
```
<a name="What_build_rule_contains_file_ja"></a>
#### What build rule contains file `src/main/java/com/example/cache/LRUCache.java` as a source?
```sh
fullname=$(bazel query src/main/java/com/example/cache/LRUCache.java)
bazel query "attr('srcs', $fullname, ${fullname//:*/}:*)"
```
<a name="What_package_dependencies_exist_"></a>
### What package dependencies exist ...
<a name="What_packages_does_foo_depend_on"></a>
#### What packages does `foo` depend on? (What do I need to check out to build `foo`)
```sh
bazel query 'buildfiles(deps(//foo:foo))' --output package
```
Note, `buildfiles` is required in order to correctly obtain all files
referenced by `subinclude`; see the reference manual for details.
<a name="What_packages_does_the_foo_"></a>
#### What packages does the `foo` tree depend on, excluding `foo/contrib`?
```sh
bazel query 'deps(foo/... except foo/contrib/...)' --output package
```
<a name="What_rule_dependencies_exist_"></a>
### What rule dependencies exist ...
<a name="What_genproto_rules_does_bar_"></a>
#### What genproto rules does bar depend upon?
```sh
bazel query 'kind(genproto, deps(bar/...))'
```
<a name="Find_the_definition_of_some_JNI_"></a>
#### Find the definition of some JNI (C++) library that is transitively depended upon by a Java binary rule in the servlet tree.
```sh
bazel query 'some(kind(cc_.*library, deps(kind(java_binary, src/main/java/com/example/frontend/...))))' --output location
```
<a name="_Now_find_the_definitions_of_all"></a>
##### ...Now find the definitions of all the Java binaries that depend on them
```sh
bazel query 'let jbs = kind(java_binary, src/main/java/com/example/frontend/...) in
let cls = kind(cc_.*library, deps($jbs)) in
$jbs intersect allpaths($jbs, $cls)'
```
<a name="What_file_dependencies_exist_"></a>
### What file dependencies exist ...
<a name="What_s_the_complete_set_of_Java_"></a>
#### What's the complete set of Java source files required to build QUX?
Source files:
```sh
bazel query 'kind("source file", deps(src/main/java/com/example/qux/...))' | grep java$
```
Generated files:
```sh
bazel query 'kind("generated file", deps(src/main/java/com/example/qux/...))' | grep java$
```
<a name="What_is_the_complete_set_of_Java"></a>
#### What is the complete set of Java source files required to build QUX's tests?
Source files:
```sh
bazel query 'kind("source file", deps(kind(".*_test rule", javatests/com/example/qux/...)))' | grep java$
```
Generated files:
```sh
bazel query 'kind("generated file", deps(kind(".*_test rule", javatests/com/example/qux/...)))' | grep java$
```
<a name="What_differences_in_dependencies"></a>
### What differences in dependencies between X and Y exist ...
<a name="What_targets_does_foo_depend_on_"></a>
#### What targets does `//foo` depend on that `//foo:foolib` does not?
```sh
bazel query 'deps(//foo) except deps(//foo:foolib)'
```
<a name="What_C_libraries_do_the_foo_test"></a>
#### What C++ libraries do the `foo` tests depend on that the `//foo` production binary does _not_ depend on?
```sh
bazel query 'kind("cc_library", deps(kind(".*test rule", foo/...)) except deps(//foo))'
```
<a name="Why_does_this_dependency_exist_"></a>
### Why does this dependency exist ...
<a name="Why_does_bar_depend_on_groups"></a>
#### Why does <code>bar</code> depend on <code>groups2</code>?
```sh
bazel query 'somepath(bar/...,groups2/...:*)'
```
Once you have the results of this query, you will often find that a single
target stands out as being an unexpected or egregious and undesirable
dependency of `bar`. The query can then be further refined to:
<a name="Show_me_a_path_from_docker_updater"></a>
#### Show me a path from `docker/updater:updater_systest` (a `py_test`) to some `cc_library` that it depends upon:
```sh
bazel query 'let cc = kind(cc_library, deps(docker/updater:updater_systest)) in
somepath(docker/updater:updater_systest, $cc)'
```
<a name="Why_does_library_photos_fronten"></a>
#### Why does library `//photos/frontend:lib` depend on two variants of the same library `//third_party/jpeglib` and `//third_party/jpeg`?
This query boils down to: "show me the subgraph of `//photos/frontend:lib` that
depends on both libraries". When shown in topological order, the last element
of the result is the most likely culprit.
```
% bazel query 'allpaths(//photos/frontend:lib, //third_party/jpeglib)
intersect
allpaths(//photos/frontend:lib, //third_party/jpeg)'
//photos/frontend:lib
//photos/frontend:lib_impl
//photos/frontend:lib_dispatcher
//photos/frontend:icons
//photos/frontend/modules/gadgets:gadget_icon
//photos/thumbnailer:thumbnail_lib
//third_party/jpeg/img:renderer
```
<a name="What_depends_on_"></a>
### What depends on ...
<a name="What_rules_under_bar_depend_o"></a>
#### What rules under bar depend on Y?
```sh
bazel query 'bar/... intersect allpaths(bar/..., Y)'
```
Note: `X intersect allpaths(X, Y)` is the general idiom for the query "which X
depend on Y?" If expression X is non-trivial, it may be convenient to bind a
name to it using `let` to avoid duplication.
<a name="How_do_I_break_a_dependency_"></a>
### How do I break a dependency ...
<!-- TODO find a convincing value of X to plug in here -->
<a name="What_dependency_paths_do_I_have_"></a>
#### What dependency paths do I have to break to make `bar` no longer depend on X?
To output the graph to a `png` file:
```sh
bazel query 'allpaths(bar/...,X)' --output graph | dot -Tpng > /tmp/dep.png
```
<a name="Misc_"></a>
### Misc ...
<a name="How_many_sequential_steps_are_th"></a>
#### How many sequential steps are there in the `ServletSmokeTests` build?
Unfortunately, the query language can't currently give you the longest path
from x to y, but it can find the (or rather _a_) most distant node from the
starting point, or show you the _lengths_ of the longest path from x to every
y that it depends on. Use `maxrank`:
```sh
% bazel query 'deps(//src/test/java/com/example/servlet:ServletSmokeTests)' --output maxrank | tail -1
85 //third_party/zlib:zutil.c
```
The result indicates that there exist paths of length 85 that must occur in
order in this build.
| {
"content_hash": "f0fadb9c519beae99423912e2d75222f",
"timestamp": "",
"source": "github",
"line_count": 460,
"max_line_length": 148,
"avg_line_length": 36.68913043478261,
"alnum_prop": 0.6812229661669728,
"repo_name": "kchodorow/bazel-1",
"id": "98e8f87b48a4b8eb449817afef04fa9d2f60392a",
"size": "16881",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "site/versions/master/docs/query-how-to.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "46642"
},
{
"name": "C++",
"bytes": "277276"
},
{
"name": "HTML",
"bytes": "14091"
},
{
"name": "Java",
"bytes": "13220633"
},
{
"name": "Protocol Buffer",
"bytes": "69236"
},
{
"name": "Python",
"bytes": "106831"
},
{
"name": "Shell",
"bytes": "347893"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "49cbcbda510cdc39f91f30f947166d98",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "a740c51a3993af533bcb0c189a6ae247c22564f4",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Campylia/Campylia carinata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
filename: /packages/material-ui/src/Modal/Modal.js
---
<!--- This documentation is automatically generated, do not try to edit it. -->
# Modal API
<p class="description">The API documentation of the Modal React component. Learn more about the props and the CSS customization points.</p>
## Import
```js
import Modal from '@material-ui/core/Modal';
// or
import { Modal } from '@material-ui/core';
```
You can learn more about the difference by [reading this guide](/guides/minimizing-bundle-size/).
Modal is a lower-level construct that is leveraged by the following components:
- [Dialog](/api/dialog/)
- [Drawer](/api/drawer/)
- [Menu](/api/menu/)
- [Popover](/api/popover/)
If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
rather than directly using Modal.
This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
## Props
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| <span class="prop-name">BackdropComponent</span> | <span class="prop-type">elementType</span> | <span class="prop-default">SimpleBackdrop</span> | A backdrop component. This prop enables custom backdrop rendering. |
| <span class="prop-name">BackdropProps</span> | <span class="prop-type">object</span> | | Props applied to the [`Backdrop`](/api/backdrop/) element. |
| <span class="prop-name required">children<abbr title="required">*</abbr></span> | <span class="prop-type">element</span> | | A single child content element.<br>⚠️ [Needs to be able to hold a ref](/guides/composition/#caveat-with-refs). |
| <span class="prop-name">closeAfterTransition</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | When set to true the Modal waits until a nested Transition is completed before closing. |
| <span class="prop-name">container</span> | <span class="prop-type">HTML element<br>| React.Component<br>| func</span> | | A HTML element, component instance, or function that returns either. The `container` will have the portal children appended to it.<br>By default, it uses the body of the top-level document object, so it's simply `document.body` most of the time. |
| <span class="prop-name">disableAutoFocus</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, the modal will not automatically shift focus to itself when it opens, and replace it to the last focused element when it closes. This also works correctly with any modal children that have the `disableAutoFocus` prop.<br>Generally this should never be set to `true` as it makes the modal less accessible to assistive technologies, like screen readers. |
| <span class="prop-name">disableBackdropClick</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, clicking the backdrop will not fire `onClose`. |
| <span class="prop-name">disableEnforceFocus</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, the modal will not prevent focus from leaving the modal while open.<br>Generally this should never be set to `true` as it makes the modal less accessible to assistive technologies, like screen readers. |
| <span class="prop-name">disableEscapeKeyDown</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, hitting escape will not fire `onClose`. |
| <span class="prop-name">disablePortal</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | Disable the portal behavior. The children stay within it's parent DOM hierarchy. |
| <span class="prop-name">disableRestoreFocus</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, the modal will not restore focus to previously focused element once modal is hidden. |
| <span class="prop-name">disableScrollLock</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | Disable the scroll lock behavior. |
| <span class="prop-name">hideBackdrop</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | If `true`, the backdrop is not rendered. |
| <span class="prop-name">keepMounted</span> | <span class="prop-type">bool</span> | <span class="prop-default">false</span> | Always keep the children in the DOM. This prop can be useful in SEO situation or when you want to maximize the responsiveness of the Modal. |
| <span class="prop-name">onBackdropClick</span> | <span class="prop-type">func</span> | | Callback fired when the backdrop is clicked. |
| <span class="prop-name">onClose</span> | <span class="prop-type">func</span> | | Callback fired when the component requests to be closed. The `reason` parameter can optionally be used to control the response to `onClose`.<br><br>**Signature:**<br>`function(event: object, reason: string) => void`<br>*event:* The event source of the callback.<br>*reason:* Can be: `"escapeKeyDown"`, `"backdropClick"`. |
| <span class="prop-name">onEscapeKeyDown</span> | <span class="prop-type">func</span> | | Callback fired when the escape key is pressed, `disableEscapeKeyDown` is false and the modal is in focus. |
| <span class="prop-name">onRendered</span> | <span class="prop-type">func</span> | | Callback fired once the children has been mounted into the `container`. It signals that the `open={true}` prop took effect.<br>This prop will be deprecated and removed in v5, the ref can be used instead. |
| <span class="prop-name required">open<abbr title="required">*</abbr></span> | <span class="prop-type">bool</span> | | If `true`, the modal is open. |
The `ref` is forwarded to the root element.
Any other props supplied will be provided to the root element (native element).
## Demos
- [Modal](/components/modal/)
| {
"content_hash": "03304ad9435cb9102fd4c3cf0d285817",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 496,
"avg_line_length": 90.86153846153846,
"alnum_prop": 0.7202844564849306,
"repo_name": "lgollut/material-ui",
"id": "aef58d703ac875bd3e9b0a1f9bf89f3a339da46c",
"size": "5914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/pages/api-docs/modal.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1202143"
}
],
"symlink_target": ""
} |
@interface ASPOSEWBookmarkData : JSONModel
@property(nonatomic, strong) NSString<Optional> *text;
@end
| {
"content_hash": "f18379c66508a31e37b2321da905dcb2",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 54,
"avg_line_length": 21,
"alnum_prop": 0.7904761904761904,
"repo_name": "asposeforcloud/Aspose_Cloud_SDK_For_iOS",
"id": "026fbacadbd964a6a42237c04949ba55c5e49f9d",
"size": "305",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AsposeCloudSDK/words/model/ASPOSEWBookmarkData.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1441308"
},
{
"name": "Ruby",
"bytes": "4728"
}
],
"symlink_target": ""
} |
/*-------------------------------------------------------------------------
*
* pg_resgroup.h
* definition of the system "resource group" relation (pg_resgroup).
*
*
*
* NOTES
* the genbki.sh script reads this file and generates .bki
* information from the DATA() statements.
*
*-------------------------------------------------------------------------
*/
#ifndef PG_RESGROUP_H
#define PG_RESGROUP_H
#include "catalog/genbki.h"
/* ----------------
* pg_resgroup definition. cpp turns this into
* typedef struct FormData_pg_resgroup
* ----------------
*/
#define ResGroupRelationId 6436
CATALOG(pg_resgroup,6436) BKI_SHARED_RELATION
{
NameData rsgname; /* name of resource group */
Oid parent; /* parent resource group */
} FormData_pg_resgroup;
/* no foreign keys */
/* ----------------
* Form_pg_resgroup corresponds to a pointer to a tuple with
* the format of pg_resgroup relation.
* ----------------
*/
typedef FormData_pg_resgroup *Form_pg_resgroup;
/* ----------------
* compiler constants for pg_resqueue
* ----------------
*/
#define Natts_pg_resgroup 2
#define Anum_pg_resgroup_rsgname 1
#define Anum_pg_resgroup_parent 2
/* Create initial default resource group */
DATA(insert OID = 6437 ( default_group, 0 ));
DATA(insert OID = 6438 ( admin_group, 0 ));
#define DEFAULTRESGROUP_OID 6437
#define ADMINRESGROUP_OID 6438
/* ----------------
* pg_resgroupcapability definition. cpp turns this into
* typedef struct FormData_pg_resgroupcapability
* ----------------
*/
#define ResGroupCapabilityRelationId 6439
#define RESGROUP_LIMIT_TYPE_UNKNOWN 0
#define RESGROUP_LIMIT_TYPE_CONCURRENCY 1
#define RESGROUP_LIMIT_TYPE_CPU 2
#define RESGROUP_LIMIT_TYPE_MEMORY 3
#define RESGROUP_LIMIT_TYPE_MEMORY_SHARED_QUOTA 4
#define RESGROUP_LIMIT_TYPE_MEMORY_SPILL_RATIO 5
CATALOG(pg_resgroupcapability,6439) BKI_SHARED_RELATION
{
Oid resgroupid; /* OID of the group with this capability */
int2 reslimittype; /* resource limit type id (RESGROUP_LIMIT_TYPE_XXX) */
text value; /* resource limit (opaque type) */
text proposed; /* most of the capabilities cannot be updated immediately, we
* do it in an asynchronous way to merge the proposed value
* with the working one */
} FormData_pg_resgroupcapability;
/* GPDB added foreign key definitions for gpcheckcat. */
FOREIGN_KEY(resgroupid REFERENCES pg_resgroup(oid));
/* ----------------
* Form_pg_resgroupcapability corresponds to a pointer to a tuple with
* the format of pg_resgroupcapability relation.
* ----------------
*/
typedef FormData_pg_resgroupcapability *Form_pg_resgroupcapability;
/* ----------------
* compiler constants for pg_resgroupcapability
* ----------------
*/
#define Natts_pg_resgroupcapability 4
#define Anum_pg_resgroupcapability_resgroupid 1
#define Anum_pg_resgroupcapability_reslimittype 2
#define Anum_pg_resgroupcapability_value 3
#define Anum_pg_resgroupcapability_proposed 4
DATA(insert ( 6437, 1, 20, 20 ));
DATA(insert ( 6437, 2, 30, 30 ));
DATA(insert ( 6437, 3, 30, 30 ));
DATA(insert ( 6437, 4, 50, 50 ));
DATA(insert ( 6437, 5, 20, 20 ));
DATA(insert ( 6438, 1, 10, 10 ));
DATA(insert ( 6438, 2, 10, 10 ));
DATA(insert ( 6438, 3, 10, 10 ));
DATA(insert ( 6438, 4, 50, 50 ));
DATA(insert ( 6438, 5, 20, 20 ));
#endif /* PG_RESGROUP_H */
| {
"content_hash": "9ade92e6f239e034805a0c0747525a2d",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 79,
"avg_line_length": 26.1171875,
"alnum_prop": 0.6374513909661981,
"repo_name": "rvs/gpdb",
"id": "c5b1e2b0689a9f3b596309757403eef917a49b3a",
"size": "3343",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/include/catalog/pg_resgroup.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5665"
},
{
"name": "Batchfile",
"bytes": "11492"
},
{
"name": "C",
"bytes": "35013613"
},
{
"name": "C++",
"bytes": "3833252"
},
{
"name": "CMake",
"bytes": "17118"
},
{
"name": "CSS",
"bytes": "7407"
},
{
"name": "Csound Score",
"bytes": "179"
},
{
"name": "DTrace",
"bytes": "1160"
},
{
"name": "Fortran",
"bytes": "14777"
},
{
"name": "GDB",
"bytes": "576"
},
{
"name": "Gherkin",
"bytes": "715430"
},
{
"name": "HTML",
"bytes": "169634"
},
{
"name": "Java",
"bytes": "268348"
},
{
"name": "JavaScript",
"bytes": "23969"
},
{
"name": "Lex",
"bytes": "196275"
},
{
"name": "M4",
"bytes": "102006"
},
{
"name": "Makefile",
"bytes": "420136"
},
{
"name": "PLSQL",
"bytes": "261269"
},
{
"name": "PLpgSQL",
"bytes": "5477026"
},
{
"name": "Perl",
"bytes": "3831299"
},
{
"name": "Perl6",
"bytes": "14219"
},
{
"name": "Python",
"bytes": "8653837"
},
{
"name": "Roff",
"bytes": "51338"
},
{
"name": "Ruby",
"bytes": "26724"
},
{
"name": "SQLPL",
"bytes": "3824391"
},
{
"name": "Shell",
"bytes": "527804"
},
{
"name": "XS",
"bytes": "8405"
},
{
"name": "XSLT",
"bytes": "5779"
},
{
"name": "Yacc",
"bytes": "488001"
}
],
"symlink_target": ""
} |
package io.jeo.android.graphics;
import static io.jeo.map.CartoCSS.COMP_OP;
import static io.jeo.map.CartoCSS.LINE_CAP;
import static io.jeo.map.CartoCSS.LINE_COLOR;
import static io.jeo.map.CartoCSS.LINE_COMP_OP;
import static io.jeo.map.CartoCSS.LINE_DASHARRAY;
import static io.jeo.map.CartoCSS.LINE_DASH_OFFSET;
import static io.jeo.map.CartoCSS.LINE_JOIN;
import static io.jeo.map.CartoCSS.LINE_OPACITY;
import static io.jeo.map.CartoCSS.LINE_WIDTH;
import static io.jeo.map.CartoCSS.MARKER_COMP_OP;
import static io.jeo.map.CartoCSS.MARKER_FILL;
import static io.jeo.map.CartoCSS.MARKER_FILL_OPACITY;
import static io.jeo.map.CartoCSS.MARKER_LINE_COLOR;
import static io.jeo.map.CartoCSS.MARKER_LINE_OPACITY;
import static io.jeo.map.CartoCSS.MARKER_LINE_WIDTH;
import static io.jeo.map.CartoCSS.POLYGON_COMP_OP;
import static io.jeo.map.CartoCSS.POLYGON_FILL;
import static io.jeo.map.CartoCSS.POLYGON_OPACITY;
import static io.jeo.map.CartoCSS.TEXT_ALIGN;
import static io.jeo.map.CartoCSS.TEXT_FILL;
import static io.jeo.map.CartoCSS.TEXT_HALO_FILL;
import static io.jeo.map.CartoCSS.TEXT_HALO_RADIUS;
import static io.jeo.map.CartoCSS.TEXT_SIZE;
import io.jeo.tile.Tile;
import io.jeo.vector.Feature;
import io.jeo.geom.CoordinatePath;
import io.jeo.map.RGB;
import io.jeo.map.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint.Align;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
/**
* Collection of Android Canvas/2D utility methods.
*
* @author Justin Deoliveira, OpenGeo
*/
public class Graphics {
static Logger LOG = LoggerFactory.getLogger(Graphics.class);
public static Paint paint(Object obj, Rule rule) {
Paint p = new Paint();
if (rule != null && rule.bool(obj, "anti-alias", true)) {
p.setAntiAlias(true);
}
return p;
}
public static Paint labelPaint(Object obj, Rule rule) {
Paint p = paint(obj, rule);
p.setColor(color(rule.color(obj, TEXT_FILL, RGB.black)));
p.setTextSize(rule.number(obj, TEXT_SIZE, 10f));
p.setTextAlign(align(rule.string(obj, TEXT_ALIGN, "left")));
RGB haloColor = rule.color(obj, TEXT_HALO_FILL, null);
if (haloColor != null) {
float radius = rule.number(obj, TEXT_HALO_RADIUS, 0f);
p.setShadowLayer(radius, 0f, 0f, color(haloColor));
}
return p;
}
public static Paint markFillPaint(Object obj, Rule rule) {
//TODO: marker type
//String type = rule.string(f, MARKER_TYPE, "circle");
RGB fillColor = rule.color(obj, MARKER_FILL, null);
if (fillColor == null) {
return null;
}
fillColor = fillColor.alpha(rule.number(obj, MARKER_FILL_OPACITY, 1f));
String compOp = rule.string(obj, COMP_OP, null);
String markCompOp = rule.string(obj, MARKER_COMP_OP, null);
Paint paint = paint(obj, rule);
paint.setStyle(Style.FILL);
paint.setColor(color(fillColor));
if (markCompOp != null || compOp != null) {
PorterDuffXfermode pdMode = pdMode(markCompOp != null ? markCompOp : compOp);
if (pdMode != null) {
paint.setXfermode(pdMode);
}
}
return paint;
}
public static Paint markLinePaint(Object obj, Rule rule) {
RGB lineColor = rule.color(obj, MARKER_LINE_COLOR, null);
if (lineColor == null) {
return null;
}
lineColor = lineColor.alpha(rule.number(obj, MARKER_LINE_OPACITY, 1f));
float lineWidth = rule.number(obj, MARKER_LINE_WIDTH, 1f);
String compOp = rule.string(obj, COMP_OP, null);
String lineCompOp = rule.string(obj, LINE_COMP_OP, null);
Paint paint = paint(obj, rule);
paint.setStyle(Style.STROKE);
paint.setColor(color(lineColor));
paint.setStrokeWidth(lineWidth);
if (lineCompOp != null || compOp != null) {
PorterDuffXfermode pdMode = pdMode(lineCompOp != null ? lineCompOp : compOp);
if (pdMode != null) {
paint.setXfermode(pdMode);
}
}
return paint;
}
public static Paint linePaint(Feature f, Rule rule, Matrix tx) {
// line color + width
RGB color = rule.color(f, LINE_COLOR, RGB.black);
float width = strokeWidth(rule.number(f, LINE_WIDTH, 1f), tx);
// line join
Join join = join(rule.string(f, LINE_JOIN, "miter"));
// line cap
Cap cap = cap(rule.string(f, LINE_CAP, "butt"));
// line dash
float[] dash = dash(rule.numbers(f, LINE_DASHARRAY, (Float[])null));
if (dash != null && dash.length % 2 != 0) {
LOG.debug("dash specified odd number of entries");
float[] tmp;
if (dash.length > 2) {
// strip off last
tmp = new float[dash.length-1];
System.arraycopy(dash, 0, tmp, 0, tmp.length);
}
else {
// pad it
tmp = new float[dash.length*2];
System.arraycopy(dash, 0, tmp, 0, dash.length);
System.arraycopy(dash, 0, tmp, dash.length, dash.length);
}
}
float dashOffset = rule.number(f, LINE_DASH_OFFSET, 0f);
//float gamma = rule.number(f, "line-gamma", 1f);
//String gammaMethod = rule.string(f, "line-gamma-method", "power");
String compOp = rule.string(f, LINE_COMP_OP, null);
Paint paint = paint(f, rule);
paint.setStyle(Style.STROKE);
paint.setColor(color(color));
paint.setStrokeWidth(width);
paint.setStrokeJoin(join);
paint.setStrokeCap(cap);
if (dash != null && dash.length > 0) {
// scale the strokes
for (int i = 0; i < dash.length; i++) {
dash[i] = strokeWidth(dash[i], tx);
}
paint.setPathEffect(new DashPathEffect(dash, dashOffset));
}
if (compOp != null) {
paint.setXfermode(pdMode(compOp));
}
return paint;
}
public static Paint polyFillPaint(Feature f, Rule rule) {
// fill color
RGB polyFill = rule.color(f, POLYGON_FILL, null);
if (polyFill == null) {
return null;
}
// look for an opacity to apply
polyFill = polyFill.alpha(rule.number(f, POLYGON_OPACITY, 1f));
String compOp = rule.string(f, COMP_OP, null);
String polyCompOp = rule.string(f, POLYGON_COMP_OP, null);
Paint paint = paint(f, rule);
paint.setStyle(Style.FILL);
paint.setColor(color(polyFill));
if (polyCompOp != null || compOp != null) {
PorterDuffXfermode pdMode = pdMode(polyCompOp != null ? polyCompOp : compOp);
if (pdMode != null) {
paint.setXfermode(pdMode);
}
}
return paint;
}
public static Paint polyLinePaint(Feature f, Rule rule, Matrix m) {
// line color
RGB lineColor = rule.color(f, LINE_COLOR, null);
if (lineColor == null) {
return null;
}
// look for an opacity to apply
lineColor = lineColor.alpha(rule.number(f, LINE_OPACITY, 1f));
// line width
float lineWidth = strokeWidth((float) rule.number(f, LINE_WIDTH, 1f), m);
String compOp = rule.string(f, COMP_OP, null);
String lineCompOp = rule.string(f, LINE_COMP_OP , null);
Paint paint = paint(f, rule);
paint.setStyle(Style.STROKE);
paint.setColor(color(lineColor));
paint.setStrokeWidth(lineWidth);
if (lineCompOp != null || compOp != null) {
PorterDuffXfermode pdMode = pdMode(lineCompOp != null ? lineCompOp : compOp);
if (pdMode != null) {
paint.setXfermode(pdMode);
}
}
return paint;
}
public static Cap cap(String str) {
Cap cap = null;
if (str != null) {
try {
cap = Cap.valueOf(str.toUpperCase());
}
catch(IllegalArgumentException e) {
LOG.debug("Unrecognized " + LINE_CAP + " value: " + str);
}
}
return cap != null ? cap : Cap.BUTT;
}
public static Join join(String str) {
Join join = null;
if (str != null) {
try {
join = Join.valueOf(str.toUpperCase());
}
catch(IllegalArgumentException e) {
LOG.debug("Unrecognized " + LINE_JOIN + " value: " + str);
}
}
return join != null ? join : Join.MITER;
}
public static Align align(String str) {
Align align = null;
if (str != null) {
try {
align = Align.valueOf(str.toUpperCase());
}
catch(IllegalArgumentException e) {
LOG.debug("Unrecognized " + TEXT_ALIGN + " value: " + str);
}
}
return align != null ? align : Align.LEFT;
}
public static int color(RGB rgb) {
return Color.argb(rgb.getAlpha(), rgb.getRed(), rgb.getGreen(), rgb.getBlue());
}
public static float[] dash(Float[] dash) {
if (dash == null) {
return null;
}
float[] prim = new float[dash.length];
for (int i = 0; i < prim.length; i++) {
prim[i] = dash[i].floatValue();
}
return prim;
}
public static PorterDuffXfermode pdMode(String compOp) {
String pd = compOp.replace("-", "_").toUpperCase();
try {
return new PorterDuffXfermode(PorterDuff.Mode.valueOf(pd));
}
catch(IllegalArgumentException e) {
LOG.debug("Unsupported composition operation: " + compOp);
}
return null;
}
public static Path path(CoordinatePath path) {
Path p = new Path();
O: while(path.hasNext()) {
Coordinate c = path.next();
float x = (float) c.x;
float y = (float) c.y;
switch(path.step()) {
case MOVE_TO:
p.moveTo(x, y);
break;
case LINE_TO:
p.lineTo(x, y);
break;
case CLOSE:
p.close();
break;
case STOP:
break O;
}
}
return p;
}
public static Rect expand(Rect r, float val) {
Rect n = new Rect(r);
n.top -= val;
n.left -= val;
n.bottom += val;
n.right += val;
return n;
}
public static RectF rectFromCenter(PointF p, float width, float height) {
float left = p.x - width/2f;
float top = p.y - height/2f;
return new RectF(left, top, left + width, top + height);
}
public static RectF rectFromBottomLeft(PointF p, float width, float height) {
float left = p.x;
float top = p.y + height;
return new RectF(left, top, left + width, p.y);
}
public static RectF rectFromBottomCenter(PointF p, float width, float height) {
float left = p.x - width/2f;
float top = p.y + height;
return new RectF(left, top, left + width, p.y);
}
public static RectF rectFromBottomRight(PointF p, float width, float height) {
float left = p.x - width;
float top = p.y + height;
return new RectF(left, top, p.x, p.y);
}
public static Envelope envelope(RectF rect) {
//double h = map.getHeight();
//return new Envelope(rect.left, rect.right, h - rect.top, h - rect.bottom);
return new Envelope(rect.left, rect.right, rect.bottom, rect.top);
}
public static RectF rect(Envelope e) {
return rect(e, new RectF());
}
public static RectF rect(Envelope e, RectF r) {
r.left = (float)e.getMinX();
r.top = (float)e.getMaxY();
r.right = (float)e.getMaxX();
r.bottom = (float) e.getMinY();
return r;
}
public static PointF point(Coordinate c) {
return point(c, new PointF());
}
public static PointF point(Coordinate c, PointF p) {
p.x = (float) c.x;
p.y = (float) c.y;
return p;
}
static float strokeWidth(float width, Matrix m) {
if (width != 0f && m != null) {
// since strokes are scaled by the map transform it into world space
width = m.mapRadius(width);
}
return width;
}
public static Bitmap bitmap(Tile t) {
byte[] data = t.data();
if (data == null) {
return Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888);
}
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
}
| {
"content_hash": "c470c4bfa473c7031a879bbfe58bc552",
"timestamp": "",
"source": "github",
"line_count": 437,
"max_line_length": 89,
"avg_line_length": 30.954233409610985,
"alnum_prop": 0.573519627411843,
"repo_name": "jeo/jeo-android",
"id": "5499634c29ff3fbfaa7096dd65b14b2552c0a3fb",
"size": "14145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/jeo/android/graphics/Graphics.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "70609"
}
],
"symlink_target": ""
} |
"""
Handles all requests relating to volumes + cinder.
"""
import collections
import copy
import functools
import sys
from cinderclient import client as cinder_client
from cinderclient import exceptions as cinder_exception
from cinderclient.v1 import client as v1_client
from keystoneauth1 import exceptions as keystone_exception
from keystoneauth1 import loading as ks_loading
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import strutils
import six
from nova import availability_zones as az
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LW
cinder_opts = [
cfg.StrOpt('catalog_info',
default='volumev2:cinderv2:publicURL',
help='Info to match when looking for cinder in the service '
'catalog. Format is: separated values of the form: '
'<service_type>:<service_name>:<endpoint_type>'),
cfg.StrOpt('endpoint_template',
help='Override service catalog lookup with template for cinder '
'endpoint e.g. http://localhost:8776/v1/%(project_id)s'),
cfg.StrOpt('os_region_name',
help='Region name of this node'),
cfg.IntOpt('http_retries',
default=3,
help='Number of cinderclient retries on failed http calls'),
cfg.BoolOpt('cross_az_attach',
default=True,
help='Allow attach between instance and volume in different '
'availability zones. If False, volumes attached to an '
'instance must be in the same availability zone in '
'Cinder as the instance availability zone in Nova. '
'This also means care should be taken when booting an '
'instance from a volume where source is not "volume" '
'because Nova will attempt to create a volume using '
'the same availability zone as what is assigned to the '
'instance. If that AZ is not in Cinder (or '
'allow_availability_zone_fallback=False in cinder.conf), '
'the volume create request will fail and the instance '
'will fail the build request.'),
]
CONF = cfg.CONF
CINDER_OPT_GROUP = 'cinder'
# cinder_opts options in the DEFAULT group were deprecated in Juno
CONF.register_opts(cinder_opts, group=CINDER_OPT_GROUP)
deprecated = {'timeout': [cfg.DeprecatedOpt('http_timeout',
group=CINDER_OPT_GROUP)],
'cafile': [cfg.DeprecatedOpt('ca_certificates_file',
group=CINDER_OPT_GROUP)],
'insecure': [cfg.DeprecatedOpt('api_insecure',
group=CINDER_OPT_GROUP)]}
ks_loading.register_session_conf_options(CONF,
CINDER_OPT_GROUP,
deprecated_opts=deprecated)
LOG = logging.getLogger(__name__)
_SESSION = None
_V1_ERROR_RAISED = False
def reset_globals():
"""Testing method to reset globals.
"""
global _SESSION
_SESSION = None
def cinderclient(context):
global _SESSION
global _V1_ERROR_RAISED
if not _SESSION:
_SESSION = ks_loading.load_session_from_conf_options(CONF,
CINDER_OPT_GROUP)
url = None
endpoint_override = None
auth = context.get_auth_plugin()
service_type, service_name, interface = CONF.cinder.catalog_info.split(':')
service_parameters = {'service_type': service_type,
'service_name': service_name,
'interface': interface,
'region_name': CONF.cinder.os_region_name}
if CONF.cinder.endpoint_template:
url = CONF.cinder.endpoint_template % context.to_dict()
endpoint_override = url
else:
url = _SESSION.get_endpoint(auth, **service_parameters)
# TODO(jamielennox): This should be using proper version discovery from
# the cinder service rather than just inspecting the URL for certain string
# values.
version = cinder_client.get_volume_api_from_url(url)
if version == '1' and not _V1_ERROR_RAISED:
msg = _LW('Cinder V1 API is deprecated as of the Juno '
'release, and Nova is still configured to use it. '
'Enable the V2 API in Cinder and set '
'cinder.catalog_info in nova.conf to use it.')
LOG.warning(msg)
_V1_ERROR_RAISED = True
return cinder_client.Client(version,
session=_SESSION,
auth=auth,
endpoint_override=endpoint_override,
connect_retries=CONF.cinder.http_retries,
**service_parameters)
def _untranslate_volume_summary_view(context, vol):
"""Maps keys for volumes summary view."""
d = {}
d['id'] = vol.id
d['status'] = vol.status
d['size'] = vol.size
d['availability_zone'] = vol.availability_zone
d['created_at'] = vol.created_at
# TODO(jdg): The calling code expects attach_time and
# mountpoint to be set. When the calling
# code is more defensive this can be
# removed.
d['attach_time'] = ""
d['mountpoint'] = ""
d['multiattach'] = getattr(vol, 'multiattach', False)
if vol.attachments:
d['attachments'] = collections.OrderedDict()
for attachment in vol.attachments:
a = {attachment['server_id']:
{'attachment_id': attachment.get('attachment_id'),
'mountpoint': attachment.get('device')}
}
d['attachments'].update(a.items())
d['attach_status'] = 'attached'
else:
d['attach_status'] = 'detached'
# NOTE(dzyu) volume(cinder) v2 API uses 'name' instead of 'display_name',
# and use 'description' instead of 'display_description' for volume.
if hasattr(vol, 'display_name'):
d['display_name'] = vol.display_name
d['display_description'] = vol.display_description
else:
d['display_name'] = vol.name
d['display_description'] = vol.description
# TODO(jdg): Information may be lost in this translation
d['volume_type_id'] = vol.volume_type
d['snapshot_id'] = vol.snapshot_id
d['bootable'] = strutils.bool_from_string(vol.bootable)
d['volume_metadata'] = {}
for key, value in vol.metadata.items():
d['volume_metadata'][key] = value
if hasattr(vol, 'volume_image_metadata'):
d['volume_image_metadata'] = copy.deepcopy(vol.volume_image_metadata)
return d
def _untranslate_snapshot_summary_view(context, snapshot):
"""Maps keys for snapshots summary view."""
d = {}
d['id'] = snapshot.id
d['status'] = snapshot.status
d['progress'] = snapshot.progress
d['size'] = snapshot.size
d['created_at'] = snapshot.created_at
# NOTE(dzyu) volume(cinder) v2 API uses 'name' instead of 'display_name',
# 'description' instead of 'display_description' for snapshot.
if hasattr(snapshot, 'display_name'):
d['display_name'] = snapshot.display_name
d['display_description'] = snapshot.display_description
else:
d['display_name'] = snapshot.name
d['display_description'] = snapshot.description
d['volume_id'] = snapshot.volume_id
d['project_id'] = snapshot.project_id
d['volume_size'] = snapshot.size
return d
def translate_cinder_exception(method):
"""Transforms a cinder exception but keeps its traceback intact."""
@functools.wraps(method)
def wrapper(self, ctx, *args, **kwargs):
try:
res = method(self, ctx, *args, **kwargs)
except (cinder_exception.ConnectionError,
keystone_exception.ConnectionError):
exc_type, exc_value, exc_trace = sys.exc_info()
_reraise(exception.CinderConnectionFailed(
reason=six.text_type(exc_value)))
except (keystone_exception.BadRequest,
cinder_exception.BadRequest):
exc_type, exc_value, exc_trace = sys.exc_info()
_reraise(exception.InvalidInput(reason=six.text_type(exc_value)))
except (keystone_exception.Forbidden,
cinder_exception.Forbidden):
exc_type, exc_value, exc_trace = sys.exc_info()
_reraise(exception.Forbidden(six.text_type(exc_value)))
return res
return wrapper
def translate_volume_exception(method):
"""Transforms the exception for the volume but keeps its traceback intact.
"""
def wrapper(self, ctx, volume_id, *args, **kwargs):
try:
res = method(self, ctx, volume_id, *args, **kwargs)
except (keystone_exception.NotFound, cinder_exception.NotFound):
_reraise(exception.VolumeNotFound(volume_id=volume_id))
except cinder_exception.OverLimit:
_reraise(exception.OverQuota(overs='volumes'))
return res
return translate_cinder_exception(wrapper)
def translate_snapshot_exception(method):
"""Transforms the exception for the snapshot but keeps its traceback
intact.
"""
def wrapper(self, ctx, snapshot_id, *args, **kwargs):
try:
res = method(self, ctx, snapshot_id, *args, **kwargs)
except (keystone_exception.NotFound, cinder_exception.NotFound):
_reraise(exception.SnapshotNotFound(snapshot_id=snapshot_id))
return res
return translate_cinder_exception(wrapper)
def translate_mixed_exceptions(method):
"""Transforms exceptions that can come from both volumes and snapshots."""
def wrapper(self, ctx, res_id, *args, **kwargs):
try:
res = method(self, ctx, res_id, *args, **kwargs)
except (keystone_exception.NotFound, cinder_exception.NotFound):
_reraise(exception.VolumeNotFound(volume_id=res_id))
except cinder_exception.OverLimit:
_reraise(exception.OverQuota(overs='snapshots'))
return res
return translate_cinder_exception(wrapper)
def _reraise(desired_exc):
exc_type, exc_value, exc_trace = sys.exc_info()
exc_value = desired_exc
six.reraise(exc_value, None, exc_trace)
class API(object):
"""API for interacting with the volume manager."""
@translate_volume_exception
def get(self, context, volume_id):
item = cinderclient(context).volumes.get(volume_id)
return _untranslate_volume_summary_view(context, item)
@translate_cinder_exception
def get_all(self, context, search_opts=None):
search_opts = search_opts or {}
items = cinderclient(context).volumes.list(detailed=True,
search_opts=search_opts)
rval = []
for item in items:
rval.append(_untranslate_volume_summary_view(context, item))
return rval
def check_attached(self, context, volume):
if volume['status'] != "in-use":
msg = _("volume '%(vol)s' status must be 'in-use'. Currently in "
"'%(status)s' status") % {"vol": volume['id'],
"status": volume['status']}
raise exception.InvalidVolume(reason=msg)
def check_attach(self, context, volume, instance=None):
# TODO(vish): abstract status checking?
if volume['status'] != "available":
msg = _("volume '%(vol)s' status must be 'available'. Currently "
"in '%(status)s'") % {'vol': volume['id'],
'status': volume['status']}
raise exception.InvalidVolume(reason=msg)
if volume['attach_status'] == "attached":
msg = _("volume %s already attached") % volume['id']
raise exception.InvalidVolume(reason=msg)
if instance and not CONF.cinder.cross_az_attach:
instance_az = az.get_instance_availability_zone(context, instance)
if instance_az != volume['availability_zone']:
msg = _("Instance %(instance)s and volume %(vol)s are not in "
"the same availability_zone. Instance is in "
"%(ins_zone)s. Volume is in %(vol_zone)s") % {
"instance": instance['id'],
"vol": volume['id'],
'ins_zone': instance_az,
'vol_zone': volume['availability_zone']}
raise exception.InvalidVolume(reason=msg)
def check_detach(self, context, volume, instance=None):
# TODO(vish): abstract status checking?
if volume['status'] == "available":
msg = _("volume %s already detached") % volume['id']
raise exception.InvalidVolume(reason=msg)
if volume['attach_status'] == 'detached':
msg = _("Volume must be attached in order to detach.")
raise exception.InvalidVolume(reason=msg)
# NOTE(ildikov):Preparation for multiattach support, when a volume
# can be attached to multiple hosts and/or instances,
# so just check the attachment specific to this instance
if instance is not None and instance.uuid not in volume['attachments']:
# TODO(ildikov): change it to a better exception, when enable
# multi-attach.
raise exception.VolumeUnattached(volume_id=volume['id'])
@translate_volume_exception
def reserve_volume(self, context, volume_id):
cinderclient(context).volumes.reserve(volume_id)
@translate_volume_exception
def unreserve_volume(self, context, volume_id):
cinderclient(context).volumes.unreserve(volume_id)
@translate_volume_exception
def begin_detaching(self, context, volume_id):
cinderclient(context).volumes.begin_detaching(volume_id)
@translate_volume_exception
def roll_detaching(self, context, volume_id):
cinderclient(context).volumes.roll_detaching(volume_id)
@translate_volume_exception
def attach(self, context, volume_id, instance_uuid, mountpoint, mode='rw'):
cinderclient(context).volumes.attach(volume_id, instance_uuid,
mountpoint, mode=mode)
@translate_volume_exception
def detach(self, context, volume_id, instance_uuid=None,
attachment_id=None):
if attachment_id is None:
volume = self.get(context, volume_id)
if volume['multiattach']:
attachments = volume.get('attachments', {})
if instance_uuid:
attachment_id = attachments.get(instance_uuid, {}).\
get('attachment_id')
if not attachment_id:
LOG.warning(_LW("attachment_id couldn't be retrieved "
"for volume %(volume_id)s with "
"instance_uuid %(instance_id)s. The "
"volume has the 'multiattach' flag "
"enabled, without the attachment_id "
"Cinder most probably cannot perform "
"the detach."),
{'volume_id': volume_id,
'instance_id': instance_uuid})
else:
LOG.warning(_LW("attachment_id couldn't be retrieved for "
"volume %(volume_id)s. The volume has the "
"'multiattach' flag enabled, without the "
"attachment_id Cinder most probably "
"cannot perform the detach."),
{'volume_id': volume_id})
cinderclient(context).volumes.detach(volume_id, attachment_id)
@translate_volume_exception
def initialize_connection(self, context, volume_id, connector):
try:
connection_info = cinderclient(
context).volumes.initialize_connection(volume_id, connector)
connection_info['connector'] = connector
return connection_info
except cinder_exception.ClientException as ex:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Initialize connection failed for volume '
'%(vol)s on host %(host)s. Error: %(msg)s '
'Code: %(code)s. Attempting to terminate '
'connection.'),
{'vol': volume_id,
'host': connector.get('host'),
'msg': six.text_type(ex),
'code': ex.code})
try:
self.terminate_connection(context, volume_id, connector)
except Exception as exc:
LOG.error(_LE('Connection between volume %(vol)s and host '
'%(host)s might have succeeded, but attempt '
'to terminate connection has failed. '
'Validate the connection and determine if '
'manual cleanup is needed. Error: %(msg)s '
'Code: %(code)s.'),
{'vol': volume_id,
'host': connector.get('host'),
'msg': six.text_type(exc),
'code': (
exc.code if hasattr(exc, 'code') else None)})
@translate_volume_exception
def terminate_connection(self, context, volume_id, connector):
return cinderclient(context).volumes.terminate_connection(volume_id,
connector)
@translate_cinder_exception
def migrate_volume_completion(self, context, old_volume_id, new_volume_id,
error=False):
return cinderclient(context).volumes.migrate_volume_completion(
old_volume_id, new_volume_id, error)
@translate_volume_exception
def create(self, context, size, name, description, snapshot=None,
image_id=None, volume_type=None, metadata=None,
availability_zone=None):
client = cinderclient(context)
if snapshot is not None:
snapshot_id = snapshot['id']
else:
snapshot_id = None
kwargs = dict(snapshot_id=snapshot_id,
volume_type=volume_type,
user_id=context.user_id,
project_id=context.project_id,
availability_zone=availability_zone,
metadata=metadata,
imageRef=image_id)
if isinstance(client, v1_client.Client):
kwargs['display_name'] = name
kwargs['display_description'] = description
else:
kwargs['name'] = name
kwargs['description'] = description
item = client.volumes.create(size, **kwargs)
return _untranslate_volume_summary_view(context, item)
@translate_volume_exception
def delete(self, context, volume_id):
cinderclient(context).volumes.delete(volume_id)
@translate_volume_exception
def update(self, context, volume_id, fields):
raise NotImplementedError()
@translate_snapshot_exception
def get_snapshot(self, context, snapshot_id):
item = cinderclient(context).volume_snapshots.get(snapshot_id)
return _untranslate_snapshot_summary_view(context, item)
@translate_cinder_exception
def get_all_snapshots(self, context):
items = cinderclient(context).volume_snapshots.list(detailed=True)
rvals = []
for item in items:
rvals.append(_untranslate_snapshot_summary_view(context, item))
return rvals
@translate_mixed_exceptions
def create_snapshot(self, context, volume_id, name, description):
item = cinderclient(context).volume_snapshots.create(volume_id,
False,
name,
description)
return _untranslate_snapshot_summary_view(context, item)
@translate_mixed_exceptions
def create_snapshot_force(self, context, volume_id, name, description):
item = cinderclient(context).volume_snapshots.create(volume_id,
True,
name,
description)
return _untranslate_snapshot_summary_view(context, item)
@translate_snapshot_exception
def delete_snapshot(self, context, snapshot_id):
cinderclient(context).volume_snapshots.delete(snapshot_id)
@translate_cinder_exception
def get_volume_encryption_metadata(self, context, volume_id):
return cinderclient(context).volumes.get_encryption_metadata(volume_id)
@translate_snapshot_exception
def update_snapshot_status(self, context, snapshot_id, status):
vs = cinderclient(context).volume_snapshots
# '90%' here is used to tell Cinder that Nova is done
# with its portion of the 'creating' state. This can
# be removed when we are able to split the Cinder states
# into 'creating' and a separate state of
# 'creating_in_nova'. (Same for 'deleting' state.)
vs.update_snapshot_status(
snapshot_id,
{'status': status,
'progress': '90%'}
)
| {
"content_hash": "f237d44512763f41fdbf45a36441cba2",
"timestamp": "",
"source": "github",
"line_count": 533,
"max_line_length": 79,
"avg_line_length": 41.70544090056285,
"alnum_prop": 0.5715506770435017,
"repo_name": "zhimin711/nova",
"id": "5be9d5bbec06b3769cff109aa82f9f6699444376",
"size": "22961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nova/volume/cinder.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "16549579"
},
{
"name": "Shell",
"bytes": "20716"
},
{
"name": "Smarty",
"bytes": "259485"
}
],
"symlink_target": ""
} |
//===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing dwarf debug info into asm files.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "dwarfdebug"
#include "DwarfDebug.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ValueHandle.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Timer.h"
#include "llvm/System/Path.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
/// Configuration values for initial hash set sizes (log2).
///
static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
namespace llvm {
//===----------------------------------------------------------------------===//
/// CompileUnit - This dwarf writer support class manages information associate
/// with a source file.
class CompileUnit {
/// ID - File identifier for source.
///
unsigned ID;
/// Die - Compile unit debug information entry.
///
DIE *CUDie;
/// IndexTyDie - An anonymous type for index type.
DIE *IndexTyDie;
/// GVToDieMap - Tracks the mapping of unit level debug informaton
/// variables to debug information entries.
/// FIXME : Rename GVToDieMap -> NodeToDieMap
DenseMap<MDNode *, DIE *> GVToDieMap;
/// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
/// descriptors to debug information entries using a DIEEntry proxy.
/// FIXME : Rename
DenseMap<MDNode *, DIEEntry *> GVToDIEEntryMap;
/// Globals - A map of globally visible named entities for this unit.
///
StringMap<DIE*> Globals;
/// GlobalTypes - A map of globally visible types for this unit.
///
StringMap<DIE*> GlobalTypes;
public:
CompileUnit(unsigned I, DIE *D)
: ID(I), CUDie(D), IndexTyDie(0) {}
~CompileUnit() { delete CUDie; delete IndexTyDie; }
// Accessors.
unsigned getID() const { return ID; }
DIE* getCUDie() const { return CUDie; }
const StringMap<DIE*> &getGlobals() const { return Globals; }
const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
/// hasContent - Return true if this compile unit has something to write out.
///
bool hasContent() const { return !CUDie->getChildren().empty(); }
/// addGlobal - Add a new global entity to the compile unit.
///
void addGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
/// addGlobalType - Add a new global type to the compile unit.
///
void addGlobalType(const std::string &Name, DIE *Die) {
GlobalTypes[Name] = Die;
}
/// getDIE - Returns the debug information entry map slot for the
/// specified debug variable.
DIE *getDIE(MDNode *N) { return GVToDieMap.lookup(N); }
/// insertDIE - Insert DIE into the map.
void insertDIE(MDNode *N, DIE *D) {
GVToDieMap.insert(std::make_pair(N, D));
}
/// getDIEEntry - Returns the debug information entry for the speciefied
/// debug variable.
DIEEntry *getDIEEntry(MDNode *N) {
DenseMap<MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
if (I == GVToDIEEntryMap.end())
return NULL;
return I->second;
}
/// insertDIEEntry - Insert debug information entry into the map.
void insertDIEEntry(MDNode *N, DIEEntry *E) {
GVToDIEEntryMap.insert(std::make_pair(N, E));
}
/// addDie - Adds or interns the DIE to the compile unit.
///
void addDie(DIE *Buffer) {
this->CUDie->addChild(Buffer);
}
// getIndexTyDie - Get an anonymous type for index type.
DIE *getIndexTyDie() {
return IndexTyDie;
}
// setIndexTyDie - Set D as anonymous type for index which can be reused
// later.
void setIndexTyDie(DIE *D) {
IndexTyDie = D;
}
};
//===----------------------------------------------------------------------===//
/// DbgVariable - This class is used to track local variable information.
///
class DbgVariable {
DIVariable Var; // Variable Descriptor.
unsigned FrameIndex; // Variable frame index.
DbgVariable *AbstractVar; // Abstract variable for this variable.
DIE *TheDIE;
public:
DbgVariable(DIVariable V, unsigned I)
: Var(V), FrameIndex(I), AbstractVar(0), TheDIE(0) {}
// Accessors.
DIVariable getVariable() const { return Var; }
unsigned getFrameIndex() const { return FrameIndex; }
void setAbstractVariable(DbgVariable *V) { AbstractVar = V; }
DbgVariable *getAbstractVariable() const { return AbstractVar; }
void setDIE(DIE *D) { TheDIE = D; }
DIE *getDIE() const { return TheDIE; }
};
//===----------------------------------------------------------------------===//
/// DbgScope - This class is used to track scope information.
///
class DbgScope {
DbgScope *Parent; // Parent to this scope.
DIDescriptor Desc; // Debug info descriptor for scope.
// Location at which this scope is inlined.
AssertingVH<MDNode> InlinedAtLocation;
bool AbstractScope; // Abstract Scope
unsigned StartLabelID; // Label ID of the beginning of scope.
unsigned EndLabelID; // Label ID of the end of scope.
const MachineInstr *LastInsn; // Last instruction of this scope.
const MachineInstr *FirstInsn; // First instruction of this scope.
SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
// Private state for dump()
mutable unsigned IndentLevel;
public:
DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0)
: Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
StartLabelID(0), EndLabelID(0),
LastInsn(0), FirstInsn(0), IndentLevel(0) {}
virtual ~DbgScope();
// Accessors.
DbgScope *getParent() const { return Parent; }
void setParent(DbgScope *P) { Parent = P; }
DIDescriptor getDesc() const { return Desc; }
MDNode *getInlinedAt() const {
return InlinedAtLocation;
}
MDNode *getScopeNode() const { return Desc.getNode(); }
unsigned getStartLabelID() const { return StartLabelID; }
unsigned getEndLabelID() const { return EndLabelID; }
SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
void setStartLabelID(unsigned S) { StartLabelID = S; }
void setEndLabelID(unsigned E) { EndLabelID = E; }
void setLastInsn(const MachineInstr *MI) { LastInsn = MI; }
const MachineInstr *getLastInsn() { return LastInsn; }
void setFirstInsn(const MachineInstr *MI) { FirstInsn = MI; }
void setAbstractScope() { AbstractScope = true; }
bool isAbstractScope() const { return AbstractScope; }
const MachineInstr *getFirstInsn() { return FirstInsn; }
/// addScope - Add a scope to the scope.
///
void addScope(DbgScope *S) { Scopes.push_back(S); }
/// addVariable - Add a variable to the scope.
///
void addVariable(DbgVariable *V) { Variables.push_back(V); }
void fixInstructionMarkers(DenseMap<const MachineInstr *,
unsigned> &MIIndexMap) {
assert (getFirstInsn() && "First instruction is missing!");
// Use the end of last child scope as end of this scope.
SmallVector<DbgScope *, 4> &Scopes = getScopes();
const MachineInstr *LastInsn = getFirstInsn();
unsigned LIndex = 0;
if (Scopes.empty()) {
assert (getLastInsn() && "Inner most scope does not have last insn!");
return;
}
for (SmallVector<DbgScope *, 4>::iterator SI = Scopes.begin(),
SE = Scopes.end(); SI != SE; ++SI) {
DbgScope *DS = *SI;
DS->fixInstructionMarkers(MIIndexMap);
const MachineInstr *DSLastInsn = DS->getLastInsn();
unsigned DSI = MIIndexMap[DSLastInsn];
if (DSI > LIndex) {
LastInsn = DSLastInsn;
LIndex = DSI;
}
}
unsigned CurrentLastInsnIndex = 0;
if (const MachineInstr *CL = getLastInsn())
CurrentLastInsnIndex = MIIndexMap[CL];
unsigned FIndex = MIIndexMap[getFirstInsn()];
// Set LastInsn as the last instruction for this scope only if
// it follows
// 1) this scope's first instruction and
// 2) current last instruction for this scope, if any.
if (LIndex >= CurrentLastInsnIndex && LIndex >= FIndex)
setLastInsn(LastInsn);
}
#ifndef NDEBUG
void dump() const;
#endif
};
#ifndef NDEBUG
void DbgScope::dump() const {
raw_ostream &err = dbgs();
err.indent(IndentLevel);
MDNode *N = Desc.getNode();
N->dump();
err << " [" << StartLabelID << ", " << EndLabelID << "]\n";
if (AbstractScope)
err << "Abstract Scope\n";
IndentLevel += 2;
if (!Scopes.empty())
err << "Children ...\n";
for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
if (Scopes[i] != this)
Scopes[i]->dump();
IndentLevel -= 2;
}
#endif
DbgScope::~DbgScope() {
for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
delete Scopes[i];
for (unsigned j = 0, M = Variables.size(); j < M; ++j)
delete Variables[j];
}
} // end llvm namespace
DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T)
: DwarfPrinter(OS, A, T, "dbg"), ModuleCU(0),
AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
DIEValues(), StringPool(),
SectionSourceLines(), didInitial(false), shouldEmit(false),
CurrentFnDbgScope(0), DebugTimer(0) {
if (TimePassesIsEnabled)
DebugTimer = new Timer("Dwarf Debug Writer");
}
DwarfDebug::~DwarfDebug() {
for (unsigned j = 0, M = DIEValues.size(); j < M; ++j)
delete DIEValues[j];
delete DebugTimer;
}
/// assignAbbrevNumber - Define a unique number for the abbreviation.
///
void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
// Profile the node so that we can make it unique.
FoldingSetNodeID ID;
Abbrev.Profile(ID);
// Check the set for priors.
DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
// If it's newly added.
if (InSet == &Abbrev) {
// Add to abbreviation list.
Abbreviations.push_back(&Abbrev);
// Assign the vector position + 1 as its number.
Abbrev.setNumber(Abbreviations.size());
} else {
// Assign existing abbreviation number.
Abbrev.setNumber(InSet->getNumber());
}
}
/// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
/// information entry.
DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
DIEEntry *Value = new DIEEntry(Entry);
DIEValues.push_back(Value);
return Value;
}
/// addUInt - Add an unsigned integer attribute data and value.
///
void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
unsigned Form, uint64_t Integer) {
if (!Form) Form = DIEInteger::BestForm(false, Integer);
DIEValue *Value = new DIEInteger(Integer);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addSInt - Add an signed integer attribute data and value.
///
void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
unsigned Form, int64_t Integer) {
if (!Form) Form = DIEInteger::BestForm(true, Integer);
DIEValue *Value = new DIEInteger(Integer);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addString - Add a string attribute data and value. DIEString only
/// keeps string reference.
void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
StringRef String) {
DIEValue *Value = new DIEString(String);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addLabel - Add a Dwarf label attribute data and value.
///
void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
const DWLabel &Label) {
DIEValue *Value = new DIEDwarfLabel(Label);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addObjectLabel - Add an non-Dwarf label attribute data and value.
///
void DwarfDebug::addObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
const MCSymbol *Sym) {
DIEValue *Value = new DIEObjectLabel(Sym);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addSectionOffset - Add a section offset label attribute data and value.
///
void DwarfDebug::addSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
const DWLabel &Label, const DWLabel &Section,
bool isEH, bool useSet) {
DIEValue *Value = new DIESectionOffset(Label, Section, isEH, useSet);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addDelta - Add a label delta attribute data and value.
///
void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
const DWLabel &Hi, const DWLabel &Lo) {
DIEValue *Value = new DIEDelta(Hi, Lo);
DIEValues.push_back(Value);
Die->addValue(Attribute, Form, Value);
}
/// addBlock - Add block data.
///
void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
DIEBlock *Block) {
Block->ComputeSize(TD);
DIEValues.push_back(Block);
Die->addValue(Attribute, Block->BestForm(), Block);
}
/// addSourceLine - Add location information to specified debug information
/// entry.
void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
// If there is no compile unit specified, don't add a line #.
if (V->getCompileUnit().isNull())
return;
unsigned Line = V->getLineNumber();
unsigned FileID = findCompileUnit(V->getCompileUnit())->getID();
assert(FileID && "Invalid file id");
addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
}
/// addSourceLine - Add location information to specified debug information
/// entry.
void DwarfDebug::addSourceLine(DIE *Die, const DIGlobal *G) {
// If there is no compile unit specified, don't add a line #.
if (G->getCompileUnit().isNull())
return;
unsigned Line = G->getLineNumber();
unsigned FileID = findCompileUnit(G->getCompileUnit())->getID();
assert(FileID && "Invalid file id");
addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
}
/// addSourceLine - Add location information to specified debug information
/// entry.
void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
// If there is no compile unit specified, don't add a line #.
if (SP->getCompileUnit().isNull())
return;
// If the line number is 0, don't add it.
if (SP->getLineNumber() == 0)
return;
unsigned Line = SP->getLineNumber();
unsigned FileID = findCompileUnit(SP->getCompileUnit())->getID();
assert(FileID && "Invalid file id");
addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
}
/// addSourceLine - Add location information to specified debug information
/// entry.
void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
// If there is no compile unit specified, don't add a line #.
DICompileUnit CU = Ty->getCompileUnit();
if (CU.isNull())
return;
unsigned Line = Ty->getLineNumber();
unsigned FileID = findCompileUnit(CU)->getID();
assert(FileID && "Invalid file id");
addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
}
/// addSourceLine - Add location information to specified debug information
/// entry.
void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
// If there is no compile unit specified, don't add a line #.
if (NS->getCompileUnit().isNull())
return;
unsigned Line = NS->getLineNumber();
StringRef FN = NS->getFilename();
StringRef Dir = NS->getDirectory();
unsigned FileID = GetOrCreateSourceID(Dir, FN);
assert(FileID && "Invalid file id");
addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
}
/* Byref variables, in Blocks, are declared by the programmer as
"SomeType VarName;", but the compiler creates a
__Block_byref_x_VarName struct, and gives the variable VarName
either the struct, or a pointer to the struct, as its type. This
is necessary for various behind-the-scenes things the compiler
needs to do with by-reference variables in blocks.
However, as far as the original *programmer* is concerned, the
variable should still have type 'SomeType', as originally declared.
The following function dives into the __Block_byref_x_VarName
struct to find the original type of the variable. This will be
passed back to the code generating the type for the Debug
Information Entry for the variable 'VarName'. 'VarName' will then
have the original type 'SomeType' in its debug information.
The original type 'SomeType' will be the type of the field named
'VarName' inside the __Block_byref_x_VarName struct.
NOTE: In order for this to not completely fail on the debugger
side, the Debug Information Entry for the variable VarName needs to
have a DW_AT_location that tells the debugger how to unwind through
the pointers and __Block_byref_x_VarName struct to find the actual
value of the variable. The function addBlockByrefType does this. */
/// Find the type the programmer originally declared the variable to be
/// and return that type.
///
DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
DIType subType = Ty;
unsigned tag = Ty.getTag();
if (tag == dwarf::DW_TAG_pointer_type) {
DIDerivedType DTy = DIDerivedType(Ty.getNode());
subType = DTy.getTypeDerivedFrom();
}
DICompositeType blockStruct = DICompositeType(subType.getNode());
DIArray Elements = blockStruct.getTypeArray();
if (Elements.isNull())
return Ty;
for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
DIDescriptor Element = Elements.getElement(i);
DIDerivedType DT = DIDerivedType(Element.getNode());
if (Name == DT.getName())
return (DT.getTypeDerivedFrom());
}
return Ty;
}
/// addComplexAddress - Start with the address based on the location provided,
/// and generate the DWARF information necessary to find the actual variable
/// given the extra address information encoded in the DIVariable, starting from
/// the starting location. Add the DWARF information to the die.
///
void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
unsigned Attribute,
const MachineLocation &Location) {
const DIVariable &VD = DV->getVariable();
DIType Ty = VD.getType();
// Decode the original location, and use that as the start of the byref
// variable's location.
unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
DIEBlock *Block = new DIEBlock();
if (Location.isReg()) {
if (Reg < 32) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
} else {
Reg = Reg - dwarf::DW_OP_reg0;
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
}
} else {
if (Reg < 32)
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
else {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
}
addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
}
for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
uint64_t Element = VD.getAddrElement(i);
if (Element == DIFactory::OpPlus) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
} else if (Element == DIFactory::OpDeref) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
} else llvm_unreachable("unknown DIFactory Opcode");
}
// Now attach the location information to the DIE.
addBlock(Die, Attribute, 0, Block);
}
/* Byref variables, in Blocks, are declared by the programmer as "SomeType
VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
gives the variable VarName either the struct, or a pointer to the struct, as
its type. This is necessary for various behind-the-scenes things the
compiler needs to do with by-reference variables in Blocks.
However, as far as the original *programmer* is concerned, the variable
should still have type 'SomeType', as originally declared.
The function getBlockByrefType dives into the __Block_byref_x_VarName
struct to find the original type of the variable, which is then assigned to
the variable's Debug Information Entry as its real type. So far, so good.
However now the debugger will expect the variable VarName to have the type
SomeType. So we need the location attribute for the variable to be an
expression that explains to the debugger how to navigate through the
pointers and struct to find the actual variable of type SomeType.
The following function does just that. We start by getting
the "normal" location for the variable. This will be the location
of either the struct __Block_byref_x_VarName or the pointer to the
struct __Block_byref_x_VarName.
The struct will look something like:
struct __Block_byref_x_VarName {
... <various fields>
struct __Block_byref_x_VarName *forwarding;
... <various other fields>
SomeType VarName;
... <maybe more fields>
};
If we are given the struct directly (as our starting point) we
need to tell the debugger to:
1). Add the offset of the forwarding field.
2). Follow that pointer to get the real __Block_byref_x_VarName
struct to use (the real one may have been copied onto the heap).
3). Add the offset for the field VarName, to find the actual variable.
If we started with a pointer to the struct, then we need to
dereference that pointer first, before the other steps.
Translating this into DWARF ops, we will need to append the following
to the current location description for the variable:
DW_OP_deref -- optional, if we start with a pointer
DW_OP_plus_uconst <forward_fld_offset>
DW_OP_deref
DW_OP_plus_uconst <varName_fld_offset>
That is what this function does. */
/// addBlockByrefAddress - Start with the address based on the location
/// provided, and generate the DWARF information necessary to find the
/// actual Block variable (navigating the Block struct) based on the
/// starting location. Add the DWARF information to the die. For
/// more information, read large comment just above here.
///
void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
unsigned Attribute,
const MachineLocation &Location) {
const DIVariable &VD = DV->getVariable();
DIType Ty = VD.getType();
DIType TmpTy = Ty;
unsigned Tag = Ty.getTag();
bool isPointer = false;
StringRef varName = VD.getName();
if (Tag == dwarf::DW_TAG_pointer_type) {
DIDerivedType DTy = DIDerivedType(Ty.getNode());
TmpTy = DTy.getTypeDerivedFrom();
isPointer = true;
}
DICompositeType blockStruct = DICompositeType(TmpTy.getNode());
// Find the __forwarding field and the variable field in the __Block_byref
// struct.
DIArray Fields = blockStruct.getTypeArray();
DIDescriptor varField = DIDescriptor();
DIDescriptor forwardingField = DIDescriptor();
for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
DIDescriptor Element = Fields.getElement(i);
DIDerivedType DT = DIDerivedType(Element.getNode());
StringRef fieldName = DT.getName();
if (fieldName == "__forwarding")
forwardingField = Element;
else if (fieldName == varName)
varField = Element;
}
assert(!varField.isNull() && "Can't find byref variable in Block struct");
assert(!forwardingField.isNull()
&& "Can't find forwarding field in Block struct");
// Get the offsets for the forwarding field and the variable field.
unsigned int forwardingFieldOffset =
DIDerivedType(forwardingField.getNode()).getOffsetInBits() >> 3;
unsigned int varFieldOffset =
DIDerivedType(varField.getNode()).getOffsetInBits() >> 3;
// Decode the original location, and use that as the start of the byref
// variable's location.
unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
DIEBlock *Block = new DIEBlock();
if (Location.isReg()) {
if (Reg < 32)
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
else {
Reg = Reg - dwarf::DW_OP_reg0;
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
}
} else {
if (Reg < 32)
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
else {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
}
addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
}
// If we started with a pointer to the __Block_byref... struct, then
// the first thing we need to do is dereference the pointer (DW_OP_deref).
if (isPointer)
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
// Next add the offset for the '__forwarding' field:
// DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
// adding the offset if it's 0.
if (forwardingFieldOffset > 0) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
}
// Now dereference the __forwarding field to get to the real __Block_byref
// struct: DW_OP_deref.
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
// Now that we've got the real __Block_byref... struct, add the offset
// for the variable's field to get to the location of the actual variable:
// DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
if (varFieldOffset > 0) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
}
// Now attach the location information to the DIE.
addBlock(Die, Attribute, 0, Block);
}
/// addAddress - Add an address attribute to a die based on the location
/// provided.
void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
const MachineLocation &Location) {
unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
DIEBlock *Block = new DIEBlock();
if (Location.isReg()) {
if (Reg < 32) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
} else {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
}
} else {
if (Reg < 32) {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
} else {
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
}
addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
}
addBlock(Die, Attribute, 0, Block);
}
/// addToContextOwner - Add Die into the list of its context owner's children.
void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
if (Context.isNull())
ModuleCU->addDie(Die);
else if (Context.isType()) {
DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context.getNode()));
ContextDIE->addChild(Die);
} else if (Context.isNameSpace()) {
DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context.getNode()));
ContextDIE->addChild(Die);
} else if (DIE *ContextDIE = ModuleCU->getDIE(Context.getNode()))
ContextDIE->addChild(Die);
else
ModuleCU->addDie(Die);
}
/// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
/// given DIType.
DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
DIE *TyDIE = ModuleCU->getDIE(Ty.getNode());
if (TyDIE)
return TyDIE;
// Create new type.
TyDIE = new DIE(dwarf::DW_TAG_base_type);
ModuleCU->insertDIE(Ty.getNode(), TyDIE);
if (Ty.isBasicType())
constructTypeDIE(*TyDIE, DIBasicType(Ty.getNode()));
else if (Ty.isCompositeType())
constructTypeDIE(*TyDIE, DICompositeType(Ty.getNode()));
else {
assert(Ty.isDerivedType() && "Unknown kind of DIType");
constructTypeDIE(*TyDIE, DIDerivedType(Ty.getNode()));
}
addToContextOwner(TyDIE, Ty.getContext());
return TyDIE;
}
/// addType - Add a new type attribute to the specified entity.
void DwarfDebug::addType(DIE *Entity, DIType Ty) {
if (Ty.isNull())
return;
// Check for pre-existence.
DIEEntry *Entry = ModuleCU->getDIEEntry(Ty.getNode());
// If it exists then use the existing value.
if (Entry) {
Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
return;
}
// Set up proxy.
Entry = createDIEEntry();
ModuleCU->insertDIEEntry(Ty.getNode(), Entry);
// Construct type.
DIE *Buffer = getOrCreateTypeDIE(Ty);
Entry->setEntry(Buffer);
Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
}
/// constructTypeDIE - Construct basic type die from DIBasicType.
void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
// Get core information.
StringRef Name = BTy.getName();
Buffer.setTag(dwarf::DW_TAG_base_type);
addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
BTy.getEncoding());
// Add name if not anonymous or intermediate type.
if (!Name.empty())
addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
uint64_t Size = BTy.getSizeInBits() >> 3;
addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
}
/// constructTypeDIE - Construct derived type die from DIDerivedType.
void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
// Get core information.
StringRef Name = DTy.getName();
uint64_t Size = DTy.getSizeInBits() >> 3;
unsigned Tag = DTy.getTag();
// FIXME - Workaround for templates.
if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
Buffer.setTag(Tag);
// Map to main type, void will not have a type.
DIType FromTy = DTy.getTypeDerivedFrom();
addType(&Buffer, FromTy);
// Add name if not anonymous or intermediate type.
if (!Name.empty())
addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
// Add size if non-zero (derived types might be zero-sized.)
if (Size)
addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
// Add source line info if available and TyDesc is not a forward declaration.
if (!DTy.isForwardDecl())
addSourceLine(&Buffer, &DTy);
}
/// constructTypeDIE - Construct type DIE from DICompositeType.
void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
// Get core information.
StringRef Name = CTy.getName();
uint64_t Size = CTy.getSizeInBits() >> 3;
unsigned Tag = CTy.getTag();
Buffer.setTag(Tag);
switch (Tag) {
case dwarf::DW_TAG_vector_type:
case dwarf::DW_TAG_array_type:
constructArrayTypeDIE(Buffer, &CTy);
break;
case dwarf::DW_TAG_enumeration_type: {
DIArray Elements = CTy.getTypeArray();
// Add enumerators to enumeration type.
for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
DIE *ElemDie = NULL;
DIEnumerator Enum(Elements.getElement(i).getNode());
if (!Enum.isNull()) {
ElemDie = constructEnumTypeDIE(&Enum);
Buffer.addChild(ElemDie);
}
}
}
break;
case dwarf::DW_TAG_subroutine_type: {
// Add return type.
DIArray Elements = CTy.getTypeArray();
DIDescriptor RTy = Elements.getElement(0);
addType(&Buffer, DIType(RTy.getNode()));
// Add prototype flag.
addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
// Add arguments.
for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
DIDescriptor Ty = Elements.getElement(i);
addType(Arg, DIType(Ty.getNode()));
Buffer.addChild(Arg);
}
}
break;
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_class_type: {
// Add elements to structure type.
DIArray Elements = CTy.getTypeArray();
// A forward struct declared type may not have elements available.
if (Elements.isNull())
break;
// Add elements to structure type.
for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
DIDescriptor Element = Elements.getElement(i);
if (Element.isNull())
continue;
DIE *ElemDie = NULL;
if (Element.getTag() == dwarf::DW_TAG_subprogram)
ElemDie = createSubprogramDIE(DISubprogram(Element.getNode()));
else if (Element.getTag() == dwarf::DW_TAG_auto_variable) {
DIVariable DV(Element.getNode());
ElemDie = new DIE(dwarf::DW_TAG_variable);
addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
DV.getName());
addType(ElemDie, DV.getType());
addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
addSourceLine(ElemDie, &DV);
} else
ElemDie = createMemberDIE(DIDerivedType(Element.getNode()));
Buffer.addChild(ElemDie);
}
if (CTy.isAppleBlockExtension())
addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
unsigned RLang = CTy.getRunTimeLang();
if (RLang)
addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
dwarf::DW_FORM_data1, RLang);
DICompositeType ContainingType = CTy.getContainingType();
if (!ContainingType.isNull())
addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
getOrCreateTypeDIE(DIType(ContainingType.getNode())));
break;
}
default:
break;
}
// Add name if not anonymous or intermediate type.
if (!Name.empty())
addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
// Add size if non-zero (derived types might be zero-sized.)
if (Size)
addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
else {
// Add zero size if it is not a forward declaration.
if (CTy.isForwardDecl())
addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
else
addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
}
// Add source line info if available.
if (!CTy.isForwardDecl())
addSourceLine(&Buffer, &CTy);
}
}
/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
int64_t L = SR.getLo();
int64_t H = SR.getHi();
DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
if (L)
addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
Buffer.addChild(DW_Subrange);
}
/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
DICompositeType *CTy) {
Buffer.setTag(dwarf::DW_TAG_array_type);
if (CTy->getTag() == dwarf::DW_TAG_vector_type)
addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
// Emit derived type.
addType(&Buffer, CTy->getTypeDerivedFrom());
DIArray Elements = CTy->getTypeArray();
// Get an anonymous type for index type.
DIE *IdxTy = ModuleCU->getIndexTyDie();
if (!IdxTy) {
// Construct an anonymous type for index type.
IdxTy = new DIE(dwarf::DW_TAG_base_type);
addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
dwarf::DW_ATE_signed);
ModuleCU->addDie(IdxTy);
ModuleCU->setIndexTyDie(IdxTy);
}
// Add subranges to array type.
for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
DIDescriptor Element = Elements.getElement(i);
if (Element.getTag() == dwarf::DW_TAG_subrange_type)
constructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IdxTy);
}
}
/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator *ETy) {
DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
StringRef Name = ETy->getName();
addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
int64_t Value = ETy->getEnumValue();
addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
return Enumerator;
}
/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
/// printer to not emit usual symbol prefix before the symbol name is used then
/// return linkage name after skipping this special LLVM prefix.
static StringRef getRealLinkageName(StringRef LinkageName) {
char One = '\1';
if (LinkageName.startswith(StringRef(&One, 1)))
return LinkageName.substr(1);
return LinkageName;
}
/// createGlobalVariableDIE - Create new DIE using GV.
DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
// If the global variable was optmized out then no need to create debug info
// entry.
if (!GV.getGlobal()) return NULL;
if (GV.getDisplayName().empty()) return NULL;
DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
GV.getDisplayName());
StringRef LinkageName = GV.getLinkageName();
if (!LinkageName.empty())
addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
getRealLinkageName(LinkageName));
addType(GVDie, GV.getType());
if (!GV.isLocalToUnit())
addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
addSourceLine(GVDie, &GV);
return GVDie;
}
/// createMemberDIE - Create new member DIE.
DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
DIE *MemberDie = new DIE(DT.getTag());
StringRef Name = DT.getName();
if (!Name.empty())
addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
addType(MemberDie, DT.getTypeDerivedFrom());
addSourceLine(MemberDie, &DT);
DIEBlock *MemLocationDie = new DIEBlock();
addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
uint64_t Size = DT.getSizeInBits();
uint64_t FieldSize = DT.getOriginalTypeSize();
if (Size != FieldSize) {
// Handle bitfield.
addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
uint64_t Offset = DT.getOffsetInBits();
uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
uint64_t HiMark = (Offset + FieldSize) & AlignMask;
uint64_t FieldOffset = (HiMark - FieldSize);
Offset -= FieldOffset;
// Maybe we need to work from the other end.
if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
// Here WD_AT_data_member_location points to the anonymous
// field that includes this bit field.
addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
} else
// This is not a bitfield.
addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
if (DT.getTag() == dwarf::DW_TAG_inheritance
&& DT.isVirtual()) {
// For C++, virtual base classes are not at fixed offset. Use following
// expression to extract appropriate offset from vtable.
// BaseAddr = ObAddr + *((*ObAddr) - Offset)
DIEBlock *VBaseLocationDie = new DIEBlock();
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
VBaseLocationDie);
} else
addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
if (DT.isProtected())
addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
dwarf::DW_ACCESS_protected);
else if (DT.isPrivate())
addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
dwarf::DW_ACCESS_private);
else if (DT.getTag() == dwarf::DW_TAG_inheritance)
addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
dwarf::DW_ACCESS_public);
if (DT.isVirtual())
addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
dwarf::DW_VIRTUALITY_virtual);
return MemberDie;
}
/// createSubprogramDIE - Create new DIE using SP.
DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
DIE *SPDie = ModuleCU->getDIE(SP.getNode());
if (SPDie)
return SPDie;
SPDie = new DIE(dwarf::DW_TAG_subprogram);
// Constructors and operators for anonymous aggregates do not have names.
if (!SP.getName().empty())
addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
StringRef LinkageName = SP.getLinkageName();
if (!LinkageName.empty())
addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
getRealLinkageName(LinkageName));
addSourceLine(SPDie, &SP);
// Add prototyped tag, if C or ObjC.
unsigned Lang = SP.getCompileUnit().getLanguage();
if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
Lang == dwarf::DW_LANG_ObjC)
addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
// Add Return Type.
DICompositeType SPTy = SP.getType();
DIArray Args = SPTy.getTypeArray();
unsigned SPTag = SPTy.getTag();
if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
addType(SPDie, SPTy);
else
addType(SPDie, DIType(Args.getElement(0).getNode()));
unsigned VK = SP.getVirtuality();
if (VK) {
addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
DIEBlock *Block = new DIEBlock();
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
ContainingTypeMap.insert(std::make_pair(SPDie,
SP.getContainingType().getNode()));
}
if (MakeDecl || !SP.isDefinition()) {
addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
// Add arguments. Do not add arguments for subprogram definition. They will
// be handled while processing variables.
DICompositeType SPTy = SP.getType();
DIArray Args = SPTy.getTypeArray();
unsigned SPTag = SPTy.getTag();
if (SPTag == dwarf::DW_TAG_subroutine_type)
for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
addType(Arg, ATy);
if (ATy.isArtificial())
addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
SPDie->addChild(Arg);
}
}
if (SP.isArtificial())
addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
// DW_TAG_inlined_subroutine may refer to this DIE.
ModuleCU->insertDIE(SP.getNode(), SPDie);
return SPDie;
}
/// findCompileUnit - Get the compile unit for the given descriptor.
///
CompileUnit *DwarfDebug::findCompileUnit(DICompileUnit Unit) {
DenseMap<Value *, CompileUnit *>::const_iterator I =
CompileUnitMap.find(Unit.getNode());
if (I == CompileUnitMap.end())
return constructCompileUnit(Unit.getNode());
return I->second;
}
/// getUpdatedDbgScope - Find or create DbgScope assicated with the instruction.
/// Initialize scope and update scope hierarchy.
DbgScope *DwarfDebug::getUpdatedDbgScope(MDNode *N, const MachineInstr *MI,
MDNode *InlinedAt) {
assert (N && "Invalid Scope encoding!");
assert (MI && "Missing machine instruction!");
bool GetConcreteScope = (MI && InlinedAt);
DbgScope *NScope = NULL;
if (InlinedAt)
NScope = DbgScopeMap.lookup(InlinedAt);
else
NScope = DbgScopeMap.lookup(N);
assert (NScope && "Unable to find working scope!");
if (NScope->getFirstInsn())
return NScope;
DbgScope *Parent = NULL;
if (GetConcreteScope) {
DILocation IL(InlinedAt);
Parent = getUpdatedDbgScope(IL.getScope().getNode(), MI,
IL.getOrigLocation().getNode());
assert (Parent && "Unable to find Parent scope!");
NScope->setParent(Parent);
Parent->addScope(NScope);
} else if (DIDescriptor(N).isLexicalBlock()) {
DILexicalBlock DB(N);
if (!DB.getContext().isNull()) {
Parent = getUpdatedDbgScope(DB.getContext().getNode(), MI, InlinedAt);
NScope->setParent(Parent);
Parent->addScope(NScope);
}
}
NScope->setFirstInsn(MI);
if (!Parent && !InlinedAt) {
StringRef SPName = DISubprogram(N).getLinkageName();
if (SPName == MF->getFunction()->getName())
CurrentFnDbgScope = NScope;
}
if (GetConcreteScope) {
ConcreteScopes[InlinedAt] = NScope;
getOrCreateAbstractScope(N);
}
return NScope;
}
DbgScope *DwarfDebug::getOrCreateAbstractScope(MDNode *N) {
assert (N && "Invalid Scope encoding!");
DbgScope *AScope = AbstractScopes.lookup(N);
if (AScope)
return AScope;
DbgScope *Parent = NULL;
DIDescriptor Scope(N);
if (Scope.isLexicalBlock()) {
DILexicalBlock DB(N);
DIDescriptor ParentDesc = DB.getContext();
if (!ParentDesc.isNull())
Parent = getOrCreateAbstractScope(ParentDesc.getNode());
}
AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
if (Parent)
Parent->addScope(AScope);
AScope->setAbstractScope();
AbstractScopes[N] = AScope;
if (DIDescriptor(N).isSubprogram())
AbstractScopesList.push_back(AScope);
return AScope;
}
/// updateSubprogramScopeDIE - Find DIE for the given subprogram and
/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
/// If there are global variables in this scope then create and insert
/// DIEs for these variables.
DIE *DwarfDebug::updateSubprogramScopeDIE(MDNode *SPNode) {
DIE *SPDie = ModuleCU->getDIE(SPNode);
assert (SPDie && "Unable to find subprogram DIE!");
DISubprogram SP(SPNode);
// There is not any need to generate specification DIE for a function
// defined at compile unit level. If a function is defined inside another
// function then gdb prefers the definition at top level and but does not
// expect specification DIE in parent function. So avoid creating
// specification DIE for a function defined inside a function.
if (SP.isDefinition() && !SP.getContext().isCompileUnit()
&& !SP.getContext().isSubprogram()) {
addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
// Add arguments.
DICompositeType SPTy = SP.getType();
DIArray Args = SPTy.getTypeArray();
unsigned SPTag = SPTy.getTag();
if (SPTag == dwarf::DW_TAG_subroutine_type)
for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
DIType ATy = DIType(DIType(Args.getElement(i).getNode()));
addType(Arg, ATy);
if (ATy.isArtificial())
addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
SPDie->addChild(Arg);
}
DIE *SPDeclDie = SPDie;
SPDie = new DIE(dwarf::DW_TAG_subprogram);
addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
SPDeclDie);
ModuleCU->addDie(SPDie);
}
addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
DWLabel("func_begin", SubprogramCount));
addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
DWLabel("func_end", SubprogramCount));
MachineLocation Location(RI->getFrameRegister(*MF));
addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
if (!DISubprogram(SPNode).isLocalToUnit())
addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
return SPDie;
}
/// constructLexicalScope - Construct new DW_TAG_lexical_block
/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
// Ignore empty scopes.
if (StartID == EndID && StartID != 0)
return NULL;
DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
if (Scope->isAbstractScope())
return ScopeDIE;
addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
StartID ?
DWLabel("label", StartID)
: DWLabel("func_begin", SubprogramCount));
addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
EndID ?
DWLabel("label", EndID)
: DWLabel("func_end", SubprogramCount));
return ScopeDIE;
}
/// constructInlinedScopeDIE - This scope represents inlined body of
/// a function. Construct DIE to represent this concrete inlined copy
/// of the function.
DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
assert (StartID && "Invalid starting label for an inlined scope!");
assert (EndID && "Invalid end label for an inlined scope!");
// Ignore empty scopes.
if (StartID == EndID && StartID != 0)
return NULL;
DIScope DS(Scope->getScopeNode());
if (DS.isNull())
return NULL;
DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
DISubprogram InlinedSP = getDISubprogram(DS.getNode());
DIE *OriginDIE = ModuleCU->getDIE(InlinedSP.getNode());
assert (OriginDIE && "Unable to find Origin DIE!");
addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
dwarf::DW_FORM_ref4, OriginDIE);
addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
DWLabel("label", StartID));
addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
DWLabel("label", EndID));
InlinedSubprogramDIEs.insert(OriginDIE);
// Track the start label for this inlined function.
DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
I = InlineInfo.find(InlinedSP.getNode());
if (I == InlineInfo.end()) {
InlineInfo[InlinedSP.getNode()].push_back(std::make_pair(StartID,
ScopeDIE));
InlinedSPNodes.push_back(InlinedSP.getNode());
} else
I->second.push_back(std::make_pair(StartID, ScopeDIE));
StringPool.insert(InlinedSP.getName());
StringPool.insert(getRealLinkageName(InlinedSP.getLinkageName()));
DILocation DL(Scope->getInlinedAt());
addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
return ScopeDIE;
}
/// constructVariableDIE - Construct a DIE for the given DbgVariable.
DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
// Get the descriptor.
const DIVariable &VD = DV->getVariable();
StringRef Name = VD.getName();
if (Name.empty())
return NULL;
// Translate tag to proper Dwarf tag. The result variable is dropped for
// now.
unsigned Tag;
switch (VD.getTag()) {
case dwarf::DW_TAG_return_variable:
return NULL;
case dwarf::DW_TAG_arg_variable:
Tag = dwarf::DW_TAG_formal_parameter;
break;
case dwarf::DW_TAG_auto_variable: // fall thru
default:
Tag = dwarf::DW_TAG_variable;
break;
}
// Define variable debug information entry.
DIE *VariableDie = new DIE(Tag);
DIE *AbsDIE = NULL;
if (DbgVariable *AV = DV->getAbstractVariable())
AbsDIE = AV->getDIE();
if (AbsDIE) {
DIScope DS(Scope->getScopeNode());
DISubprogram InlinedSP = getDISubprogram(DS.getNode());
DIE *OriginSPDIE = ModuleCU->getDIE(InlinedSP.getNode());
(void) OriginSPDIE;
assert (OriginSPDIE && "Unable to find Origin DIE for the SP!");
DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
assert (AbsDIE && "Unable to find Origin DIE for the Variable!");
addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
dwarf::DW_FORM_ref4, AbsDIE);
}
else {
addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
addSourceLine(VariableDie, &VD);
// Add variable type.
// FIXME: isBlockByrefVariable should be reformulated in terms of complex
// addresses instead.
if (VD.isBlockByrefVariable())
addType(VariableDie, getBlockByrefType(VD.getType(), Name));
else
addType(VariableDie, VD.getType());
}
// Add variable address.
if (!Scope->isAbstractScope()) {
MachineLocation Location;
unsigned FrameReg;
int Offset = RI->getFrameIndexReference(*MF, DV->getFrameIndex(), FrameReg);
Location.set(FrameReg, Offset);
if (VD.hasComplexAddress())
addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
else if (VD.isBlockByrefVariable())
addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
else
addAddress(VariableDie, dwarf::DW_AT_location, Location);
}
if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
DV->setDIE(VariableDie);
return VariableDie;
}
void DwarfDebug::addPubTypes(DISubprogram SP) {
DICompositeType SPTy = SP.getType();
unsigned SPTag = SPTy.getTag();
if (SPTag != dwarf::DW_TAG_subroutine_type)
return;
DIArray Args = SPTy.getTypeArray();
if (Args.isNull())
return;
for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
DIType ATy(Args.getElement(i).getNode());
if (ATy.isNull())
continue;
DICompositeType CATy = getDICompositeType(ATy);
if (!CATy.isNull() && !CATy.getName().empty()) {
if (DIEEntry *Entry = ModuleCU->getDIEEntry(CATy.getNode()))
ModuleCU->addGlobalType(CATy.getName(), Entry->getEntry());
}
}
}
/// constructScopeDIE - Construct a DIE for this scope.
DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
if (!Scope)
return NULL;
DIScope DS(Scope->getScopeNode());
if (DS.isNull())
return NULL;
DIE *ScopeDIE = NULL;
if (Scope->getInlinedAt())
ScopeDIE = constructInlinedScopeDIE(Scope);
else if (DS.isSubprogram()) {
if (Scope->isAbstractScope())
ScopeDIE = ModuleCU->getDIE(DS.getNode());
else
ScopeDIE = updateSubprogramScopeDIE(DS.getNode());
}
else {
ScopeDIE = constructLexicalScopeDIE(Scope);
if (!ScopeDIE) return NULL;
}
// Add variables to scope.
SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
if (VariableDIE)
ScopeDIE->addChild(VariableDIE);
}
// Add nested scopes.
SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
// Define the Scope debug information entry.
DIE *NestedDIE = constructScopeDIE(Scopes[j]);
if (NestedDIE)
ScopeDIE->addChild(NestedDIE);
}
if (DS.isSubprogram())
addPubTypes(DISubprogram(DS.getNode()));
return ScopeDIE;
}
/// GetOrCreateSourceID - Look up the source id with the given directory and
/// source file names. If none currently exists, create a new id and insert it
/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
/// maps as well.
unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName) {
unsigned DId;
StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
if (DI != DirectoryIdMap.end()) {
DId = DI->getValue();
} else {
DId = DirectoryNames.size() + 1;
DirectoryIdMap[DirName] = DId;
DirectoryNames.push_back(DirName);
}
unsigned FId;
StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
if (FI != SourceFileIdMap.end()) {
FId = FI->getValue();
} else {
FId = SourceFileNames.size() + 1;
SourceFileIdMap[FileName] = FId;
SourceFileNames.push_back(FileName);
}
DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
SourceIdMap.find(std::make_pair(DId, FId));
if (SI != SourceIdMap.end())
return SI->second;
unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
SourceIdMap[std::make_pair(DId, FId)] = SrcId;
SourceIds.push_back(std::make_pair(DId, FId));
return SrcId;
}
/// getOrCreateNameSpace - Create a DIE for DINameSpace.
DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
DIE *NDie = ModuleCU->getDIE(NS.getNode());
if (NDie)
return NDie;
NDie = new DIE(dwarf::DW_TAG_namespace);
ModuleCU->insertDIE(NS.getNode(), NDie);
if (!NS.getName().empty())
addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
addSourceLine(NDie, &NS);
addToContextOwner(NDie, NS.getContext());
return NDie;
}
CompileUnit *DwarfDebug::constructCompileUnit(MDNode *N) {
DICompileUnit DIUnit(N);
StringRef FN = DIUnit.getFilename();
StringRef Dir = DIUnit.getDirectory();
unsigned ID = GetOrCreateSourceID(Dir, FN);
DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
addSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
DWLabel("section_line", 0), DWLabel("section_line", 0),
false);
addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
DIUnit.getProducer());
addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
DIUnit.getLanguage());
addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
if (!Dir.empty())
addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
if (DIUnit.isOptimized())
addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
StringRef Flags = DIUnit.getFlags();
if (!Flags.empty())
addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
unsigned RVer = DIUnit.getRunTimeVersion();
if (RVer)
addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
dwarf::DW_FORM_data1, RVer);
CompileUnit *Unit = new CompileUnit(ID, Die);
if (!ModuleCU && DIUnit.isMain()) {
// Use first compile unit marked as isMain as the compile unit
// for this module.
ModuleCU = Unit;
}
CompileUnitMap[DIUnit.getNode()] = Unit;
CompileUnits.push_back(Unit);
return Unit;
}
void DwarfDebug::constructGlobalVariableDIE(MDNode *N) {
DIGlobalVariable DI_GV(N);
// If debug information is malformed then ignore it.
if (DI_GV.Verify() == false)
return;
// Check for pre-existence.
if (ModuleCU->getDIE(DI_GV.getNode()))
return;
DIE *VariableDie = createGlobalVariableDIE(DI_GV);
if (!VariableDie)
return;
// Add to map.
ModuleCU->insertDIE(N, VariableDie);
// Add to context owner.
DIDescriptor GVContext = DI_GV.getContext();
// Do not create specification DIE if context is either compile unit
// or a subprogram.
if (DI_GV.isDefinition() && !GVContext.isCompileUnit()
&& !GVContext.isSubprogram()) {
// Create specification DIE.
DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
dwarf::DW_FORM_ref4, VariableDie);
DIEBlock *Block = new DIEBlock();
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
Asm->GetGlobalValueSymbol(DI_GV.getGlobal()));
addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
ModuleCU->addDie(VariableSpecDIE);
} else {
DIEBlock *Block = new DIEBlock();
addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
addObjectLabel(Block, 0, dwarf::DW_FORM_udata,
Asm->GetGlobalValueSymbol(DI_GV.getGlobal()));
addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
}
addToContextOwner(VariableDie, GVContext);
// Expose as global. FIXME - need to check external flag.
ModuleCU->addGlobal(DI_GV.getName(), VariableDie);
DIType GTy = DI_GV.getType();
if (GTy.isCompositeType() && !GTy.getName().empty()) {
DIEEntry *Entry = ModuleCU->getDIEEntry(GTy.getNode());
assert (Entry && "Missing global type!");
ModuleCU->addGlobalType(GTy.getName(), Entry->getEntry());
}
return;
}
void DwarfDebug::constructSubprogramDIE(MDNode *N) {
DISubprogram SP(N);
// Check for pre-existence.
if (ModuleCU->getDIE(N))
return;
if (!SP.isDefinition())
// This is a method declaration which will be handled while constructing
// class type.
return;
DIE *SubprogramDie = createSubprogramDIE(SP);
// Add to map.
ModuleCU->insertDIE(N, SubprogramDie);
// Add to context owner.
addToContextOwner(SubprogramDie, SP.getContext());
// Expose as global.
ModuleCU->addGlobal(SP.getName(), SubprogramDie);
return;
}
/// beginModule - Emit all Dwarf sections that should come prior to the
/// content. Create global DIEs and emit initial debug info sections.
/// This is inovked by the target AsmPrinter.
void DwarfDebug::beginModule(Module *M, MachineModuleInfo *mmi) {
this->M = M;
if (TimePassesIsEnabled)
DebugTimer->startTimer();
if (!MAI->doesSupportDebugInformation())
return;
DebugInfoFinder DbgFinder;
DbgFinder.processModule(*M);
// Create all the compile unit DIEs.
for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
E = DbgFinder.compile_unit_end(); I != E; ++I)
constructCompileUnit(*I);
if (CompileUnits.empty()) {
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
return;
}
// If main compile unit for this module is not seen than randomly
// select first compile unit.
if (!ModuleCU)
ModuleCU = CompileUnits[0];
// Create DIEs for each subprogram.
for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
E = DbgFinder.subprogram_end(); I != E; ++I)
constructSubprogramDIE(*I);
// Create DIEs for each global variable.
for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
E = DbgFinder.global_variable_end(); I != E; ++I)
constructGlobalVariableDIE(*I);
MMI = mmi;
shouldEmit = true;
MMI->setDebugInfoAvailability(true);
// Prime section data.
SectionMap.insert(Asm->getObjFileLowering().getTextSection());
// Print out .file directives to specify files for .loc directives. These are
// printed out early so that they precede any .loc directives.
if (MAI->hasDotLocAndDotFile()) {
for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
// Remember source id starts at 1.
std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
// FIXME: don't use sys::path for this! This should not depend on the
// host.
sys::Path FullPath(getSourceDirectoryName(Id.first));
bool AppendOk =
FullPath.appendComponent(getSourceFileName(Id.second));
assert(AppendOk && "Could not append filename to directory!");
AppendOk = false;
Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
}
}
// Emit initial sections
emitInitial();
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
}
/// endModule - Emit all Dwarf sections that should come after the content.
///
void DwarfDebug::endModule() {
if (!ModuleCU)
return;
if (TimePassesIsEnabled)
DebugTimer->startTimer();
// Attach DW_AT_inline attribute with inlined subprogram DIEs.
for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
DIE *ISP = *AI;
addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
}
// Insert top level DIEs.
for (SmallVector<DIE *, 4>::iterator TI = TopLevelDIEsVector.begin(),
TE = TopLevelDIEsVector.end(); TI != TE; ++TI)
ModuleCU->getCUDie()->addChild(*TI);
for (DenseMap<DIE *, MDNode *>::iterator CI = ContainingTypeMap.begin(),
CE = ContainingTypeMap.end(); CI != CE; ++CI) {
DIE *SPDie = CI->first;
MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
if (!N) continue;
DIE *NDie = ModuleCU->getDIE(N);
if (!NDie) continue;
addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
// FIXME - This is not the correct approach.
// addDIEEntry(NDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
}
// Standard sections final addresses.
Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
EmitLabel("text_end", 0);
Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
EmitLabel("data_end", 0);
// End text sections.
for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
Asm->OutStreamer.SwitchSection(SectionMap[i]);
EmitLabel("section_end", i);
}
// Emit common frame information.
emitCommonDebugFrame();
// Emit function debug frame information
for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
E = DebugFrames.end(); I != E; ++I)
emitFunctionDebugFrame(*I);
// Compute DIE offsets and sizes.
computeSizeAndOffsets();
// Emit all the DIEs into a debug info section
emitDebugInfo();
// Corresponding abbreviations into a abbrev section.
emitAbbreviations();
// Emit source line correspondence into a debug line section.
emitDebugLines();
// Emit info into a debug pubnames section.
emitDebugPubNames();
// Emit info into a debug pubtypes section.
emitDebugPubTypes();
// Emit info into a debug str section.
emitDebugStr();
// Emit info into a debug loc section.
emitDebugLoc();
// Emit info into a debug aranges section.
EmitDebugARanges();
// Emit info into a debug ranges section.
emitDebugRanges();
// Emit info into a debug macinfo section.
emitDebugMacInfo();
// Emit inline info.
emitDebugInlineInfo();
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
}
/// findAbstractVariable - Find abstract variable, if any, associated with Var.
DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
unsigned FrameIdx,
DILocation &ScopeLoc) {
DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var.getNode());
if (AbsDbgVariable)
return AbsDbgVariable;
DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope().getNode());
if (!Scope)
return NULL;
AbsDbgVariable = new DbgVariable(Var, FrameIdx);
Scope->addVariable(AbsDbgVariable);
AbstractVariables[Var.getNode()] = AbsDbgVariable;
return AbsDbgVariable;
}
/// collectVariableInfo - Populate DbgScope entries with variables' info.
void DwarfDebug::collectVariableInfo() {
if (!MMI) return;
MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
VE = VMap.end(); VI != VE; ++VI) {
MDNode *Var = VI->first;
if (!Var) continue;
DIVariable DV (Var);
std::pair< unsigned, MDNode *> VP = VI->second;
DILocation ScopeLoc(VP.second);
DbgScope *Scope =
ConcreteScopes.lookup(ScopeLoc.getOrigLocation().getNode());
if (!Scope)
Scope = DbgScopeMap.lookup(ScopeLoc.getScope().getNode());
// If variable scope is not found then skip this variable.
if (!Scope)
continue;
DbgVariable *RegVar = new DbgVariable(DV, VP.first);
Scope->addVariable(RegVar);
if (DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first,
ScopeLoc))
RegVar->setAbstractVariable(AbsDbgVariable);
}
}
/// beginScope - Process beginning of a scope starting at Label.
void DwarfDebug::beginScope(const MachineInstr *MI, unsigned Label) {
InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
if (I == DbgScopeBeginMap.end())
return;
ScopeVector &SD = I->second;
for (ScopeVector::iterator SDI = SD.begin(), SDE = SD.end();
SDI != SDE; ++SDI)
(*SDI)->setStartLabelID(Label);
}
/// endScope - Process end of a scope.
void DwarfDebug::endScope(const MachineInstr *MI) {
InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
if (I == DbgScopeEndMap.end())
return;
unsigned Label = MMI->NextLabelID();
Asm->printLabel(Label);
O << '\n';
SmallVector<DbgScope *, 2> &SD = I->second;
for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
SDI != SDE; ++SDI)
(*SDI)->setEndLabelID(Label);
return;
}
/// createDbgScope - Create DbgScope for the scope.
void DwarfDebug::createDbgScope(MDNode *Scope, MDNode *InlinedAt) {
if (!InlinedAt) {
DbgScope *WScope = DbgScopeMap.lookup(Scope);
if (WScope)
return;
WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
DbgScopeMap.insert(std::make_pair(Scope, WScope));
if (DIDescriptor(Scope).isLexicalBlock())
createDbgScope(DILexicalBlock(Scope).getContext().getNode(), NULL);
return;
}
DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
if (WScope)
return;
WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
DILocation DL(InlinedAt);
createDbgScope(DL.getScope().getNode(), DL.getOrigLocation().getNode());
}
/// extractScopeInformation - Scan machine instructions in this function
/// and collect DbgScopes. Return true, if atleast one scope was found.
bool DwarfDebug::extractScopeInformation() {
// If scope information was extracted using .dbg intrinsics then there is not
// any need to extract these information by scanning each instruction.
if (!DbgScopeMap.empty())
return false;
DenseMap<const MachineInstr *, unsigned> MIIndexMap;
unsigned MIIndex = 0;
// Scan each instruction and create scopes. First build working set of scopes.
for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
I != E; ++I) {
for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
II != IE; ++II) {
const MachineInstr *MInsn = II;
MIIndexMap[MInsn] = MIIndex++;
DebugLoc DL = MInsn->getDebugLoc();
if (DL.isUnknown()) continue;
DILocation DLT = MF->getDILocation(DL);
DIScope DLTScope = DLT.getScope();
if (DLTScope.isNull()) continue;
// There is no need to create another DIE for compile unit. For all
// other scopes, create one DbgScope now. This will be translated
// into a scope DIE at the end.
if (DLTScope.isCompileUnit()) continue;
createDbgScope(DLTScope.getNode(), DLT.getOrigLocation().getNode());
}
}
// Build scope hierarchy using working set of scopes.
for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
I != E; ++I) {
for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
II != IE; ++II) {
const MachineInstr *MInsn = II;
DebugLoc DL = MInsn->getDebugLoc();
if (DL.isUnknown()) continue;
DILocation DLT = MF->getDILocation(DL);
DIScope DLTScope = DLT.getScope();
if (DLTScope.isNull()) continue;
// There is no need to create another DIE for compile unit. For all
// other scopes, create one DbgScope now. This will be translated
// into a scope DIE at the end.
if (DLTScope.isCompileUnit()) continue;
DbgScope *Scope = getUpdatedDbgScope(DLTScope.getNode(), MInsn,
DLT.getOrigLocation().getNode());
Scope->setLastInsn(MInsn);
}
}
if (!CurrentFnDbgScope)
return false;
CurrentFnDbgScope->fixInstructionMarkers(MIIndexMap);
// Each scope has first instruction and last instruction to mark beginning
// and end of a scope respectively. Create an inverse map that list scopes
// starts (and ends) with an instruction. One instruction may start (or end)
// multiple scopes. Ignore scopes that are not reachable.
SmallVector<DbgScope *, 4> WorkList;
WorkList.push_back(CurrentFnDbgScope);
while (!WorkList.empty()) {
DbgScope *S = WorkList.back(); WorkList.pop_back();
SmallVector<DbgScope *, 4> &Children = S->getScopes();
if (!Children.empty())
for (SmallVector<DbgScope *, 4>::iterator SI = Children.begin(),
SE = Children.end(); SI != SE; ++SI)
WorkList.push_back(*SI);
if (S->isAbstractScope())
continue;
const MachineInstr *MI = S->getFirstInsn();
assert (MI && "DbgScope does not have first instruction!");
InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
if (IDI != DbgScopeBeginMap.end())
IDI->second.push_back(S);
else
DbgScopeBeginMap[MI].push_back(S);
MI = S->getLastInsn();
assert (MI && "DbgScope does not have last instruction!");
IDI = DbgScopeEndMap.find(MI);
if (IDI != DbgScopeEndMap.end())
IDI->second.push_back(S);
else
DbgScopeEndMap[MI].push_back(S);
}
return !DbgScopeMap.empty();
}
/// beginFunction - Gather pre-function debug information. Assumes being
/// emitted immediately after the function entry point.
void DwarfDebug::beginFunction(const MachineFunction *MF) {
this->MF = MF;
if (!ShouldEmitDwarfDebug()) return;
if (TimePassesIsEnabled)
DebugTimer->startTimer();
if (!extractScopeInformation())
return;
collectVariableInfo();
// Assumes in correct section after the entry point.
EmitLabel("func_begin", ++SubprogramCount);
// Emit label for the implicitly defined dbg.stoppoint at the start of the
// function.
DebugLoc FDL = MF->getDefaultDebugLoc();
if (!FDL.isUnknown()) {
DILocation DLT = MF->getDILocation(FDL);
unsigned LabelID = 0;
DISubprogram SP = getDISubprogram(DLT.getScope().getNode());
if (!SP.isNull())
LabelID = recordSourceLine(SP.getLineNumber(), 0,
DLT.getScope().getNode());
else
LabelID = recordSourceLine(DLT.getLineNumber(),
DLT.getColumnNumber(),
DLT.getScope().getNode());
Asm->printLabel(LabelID);
O << '\n';
}
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
}
/// endFunction - Gather and emit post-function debug information.
///
void DwarfDebug::endFunction(const MachineFunction *MF) {
if (!ShouldEmitDwarfDebug()) return;
if (TimePassesIsEnabled)
DebugTimer->startTimer();
if (DbgScopeMap.empty())
return;
if (CurrentFnDbgScope) {
// Define end label for subprogram.
EmitLabel("func_end", SubprogramCount);
// Get function line info.
if (!Lines.empty()) {
// Get section line info.
unsigned ID = SectionMap.insert(Asm->getCurrentSection());
if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
// Append the function info to section info.
SectionLineInfos.insert(SectionLineInfos.end(),
Lines.begin(), Lines.end());
}
// Construct abstract scopes.
for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
AE = AbstractScopesList.end(); AI != AE; ++AI)
constructScopeDIE(*AI);
constructScopeDIE(CurrentFnDbgScope);
DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
MMI->getFrameMoves()));
}
// Clear debug info
CurrentFnDbgScope = NULL;
DbgScopeMap.clear();
DbgScopeBeginMap.clear();
DbgScopeEndMap.clear();
ConcreteScopes.clear();
AbstractScopesList.clear();
Lines.clear();
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
}
/// recordSourceLine - Records location information and associates it with a
/// label. Returns a unique label ID used to generate a label and provide
/// correspondence to the source line list.
unsigned DwarfDebug::recordSourceLine(unsigned Line, unsigned Col,
MDNode *S) {
if (!MMI)
return 0;
if (TimePassesIsEnabled)
DebugTimer->startTimer();
StringRef Dir;
StringRef Fn;
DIDescriptor Scope(S);
if (Scope.isCompileUnit()) {
DICompileUnit CU(S);
Dir = CU.getDirectory();
Fn = CU.getFilename();
} else if (Scope.isSubprogram()) {
DISubprogram SP(S);
Dir = SP.getDirectory();
Fn = SP.getFilename();
} else if (Scope.isLexicalBlock()) {
DILexicalBlock DB(S);
Dir = DB.getDirectory();
Fn = DB.getFilename();
} else
assert (0 && "Unexpected scope info");
unsigned Src = GetOrCreateSourceID(Dir, Fn);
unsigned ID = MMI->NextLabelID();
Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
return ID;
}
/// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
/// timed. Look up the source id with the given directory and source file
/// names. If none currently exists, create a new id and insert it in the
/// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
/// well.
unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
const std::string &FileName) {
if (TimePassesIsEnabled)
DebugTimer->startTimer();
unsigned SrcId = GetOrCreateSourceID(DirName.c_str(), FileName.c_str());
if (TimePassesIsEnabled)
DebugTimer->stopTimer();
return SrcId;
}
//===----------------------------------------------------------------------===//
// Emit Methods
//===----------------------------------------------------------------------===//
/// computeSizeAndOffset - Compute the size and offset of a DIE.
///
unsigned
DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
// Get the children.
const std::vector<DIE *> &Children = Die->getChildren();
// If not last sibling and has children then add sibling offset attribute.
if (!Last && !Children.empty()) Die->addSiblingOffset();
// Record the abbreviation.
assignAbbrevNumber(Die->getAbbrev());
// Get the abbreviation for this DIE.
unsigned AbbrevNumber = Die->getAbbrevNumber();
const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
// Set DIE offset
Die->setOffset(Offset);
// Start the size with the size of abbreviation code.
Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
const SmallVector<DIEValue*, 32> &Values = Die->getValues();
const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
// Size the DIE attribute values.
for (unsigned i = 0, N = Values.size(); i < N; ++i)
// Size attribute value.
Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
// Size the DIE children if any.
if (!Children.empty()) {
assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
"Children flag not set");
for (unsigned j = 0, M = Children.size(); j < M; ++j)
Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
// End of children marker.
Offset += sizeof(int8_t);
}
Die->setSize(Offset - Die->getOffset());
return Offset;
}
/// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
///
void DwarfDebug::computeSizeAndOffsets() {
// Compute size of compile unit header.
static unsigned Offset =
sizeof(int32_t) + // Length of Compilation Unit Info
sizeof(int16_t) + // DWARF version number
sizeof(int32_t) + // Offset Into Abbrev. Section
sizeof(int8_t); // Pointer Size (in bytes)
computeSizeAndOffset(ModuleCU->getCUDie(), Offset, true);
CompileUnitOffsets[ModuleCU] = 0;
}
/// emitInitial - Emit initial Dwarf declarations. This is necessary for cc
/// tools to recognize the object file contains Dwarf information.
void DwarfDebug::emitInitial() {
// Check to see if we already emitted intial headers.
if (didInitial) return;
didInitial = true;
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
// Dwarf sections base addresses.
if (MAI->doesDwarfRequireFrameSection()) {
Asm->OutStreamer.SwitchSection(TLOF.getDwarfFrameSection());
EmitLabel("section_debug_frame", 0);
}
Asm->OutStreamer.SwitchSection(TLOF.getDwarfInfoSection());
EmitLabel("section_info", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfAbbrevSection());
EmitLabel("section_abbrev", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfARangesSection());
EmitLabel("section_aranges", 0);
if (const MCSection *LineInfoDirective = TLOF.getDwarfMacroInfoSection()) {
Asm->OutStreamer.SwitchSection(LineInfoDirective);
EmitLabel("section_macinfo", 0);
}
Asm->OutStreamer.SwitchSection(TLOF.getDwarfLineSection());
EmitLabel("section_line", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfLocSection());
EmitLabel("section_loc", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubNamesSection());
EmitLabel("section_pubnames", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfPubTypesSection());
EmitLabel("section_pubtypes", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfStrSection());
EmitLabel("section_str", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDwarfRangesSection());
EmitLabel("section_ranges", 0);
Asm->OutStreamer.SwitchSection(TLOF.getTextSection());
EmitLabel("text_begin", 0);
Asm->OutStreamer.SwitchSection(TLOF.getDataSection());
EmitLabel("data_begin", 0);
}
/// emitDIE - Recusively Emits a debug information entry.
///
void DwarfDebug::emitDIE(DIE *Die) {
// Get the abbreviation for this DIE.
unsigned AbbrevNumber = Die->getAbbrevNumber();
const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
Asm->O << '\n';
// Emit the code (index) for the abbreviation.
if (Asm->VerboseAsm)
Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
Twine::utohexstr(Die->getOffset()) + ":0x" +
Twine::utohexstr(Die->getSize()) + " " +
dwarf::TagString(Abbrev->getTag()));
EmitULEB128(AbbrevNumber);
SmallVector<DIEValue*, 32> &Values = Die->getValues();
const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
// Emit the DIE attribute values.
for (unsigned i = 0, N = Values.size(); i < N; ++i) {
unsigned Attr = AbbrevData[i].getAttribute();
unsigned Form = AbbrevData[i].getForm();
assert(Form && "Too many attributes for DIE (check abbreviation)");
if (Asm->VerboseAsm)
Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
switch (Attr) {
case dwarf::DW_AT_sibling:
Asm->EmitInt32(Die->getSiblingOffset());
break;
case dwarf::DW_AT_abstract_origin: {
DIEEntry *E = cast<DIEEntry>(Values[i]);
DIE *Origin = E->getEntry();
unsigned Addr = Origin->getOffset();
Asm->EmitInt32(Addr);
break;
}
default:
// Emit an attribute using the defined form.
Values[i]->EmitValue(this, Form);
O << "\n"; // REMOVE This once all EmitValue impls emit their own newline.
break;
}
}
// Emit the DIE children if any.
if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
const std::vector<DIE *> &Children = Die->getChildren();
for (unsigned j = 0, M = Children.size(); j < M; ++j)
emitDIE(Children[j]);
Asm->EmitInt8(0); EOL("End Of Children Mark");
}
}
/// emitDebugInfo - Emit the debug info section.
///
void DwarfDebug::emitDebugInfo() {
// Start debug info section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfInfoSection());
DIE *Die = ModuleCU->getCUDie();
// Emit the compile units header.
EmitLabel("info_begin", ModuleCU->getID());
// Emit size of content not including length itself
unsigned ContentSize = Die->getSize() +
sizeof(int16_t) + // DWARF version number
sizeof(int32_t) + // Offset Into Abbrev. Section
sizeof(int8_t) + // Pointer Size (in bytes)
sizeof(int32_t); // FIXME - extra pad for gdb bug.
Asm->EmitInt32(ContentSize); EOL("Length of Compilation Unit Info");
Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("DWARF version number");
EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
EOL("Offset Into Abbrev. Section");
Asm->EmitInt8(TD->getPointerSize()); EOL("Address Size (in bytes)");
emitDIE(Die);
// FIXME - extra padding for gdb bug.
Asm->EmitInt8(0); EOL("Extra Pad For GDB");
Asm->EmitInt8(0); EOL("Extra Pad For GDB");
Asm->EmitInt8(0); EOL("Extra Pad For GDB");
Asm->EmitInt8(0); EOL("Extra Pad For GDB");
EmitLabel("info_end", ModuleCU->getID());
Asm->O << '\n';
}
/// emitAbbreviations - Emit the abbreviation section.
///
void DwarfDebug::emitAbbreviations() const {
// Check to see if it is worth the effort.
if (!Abbreviations.empty()) {
// Start the debug abbrev section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfAbbrevSection());
EmitLabel("abbrev_begin", 0);
// For each abbrevation.
for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
// Get abbreviation data
const DIEAbbrev *Abbrev = Abbreviations[i];
// Emit the abbrevations code (base 1 index.)
EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
// Emit the abbreviations data.
Abbrev->Emit(this);
Asm->O << '\n';
}
// Mark end of abbreviations.
EmitULEB128(0, "EOM(3)");
EmitLabel("abbrev_end", 0);
Asm->O << '\n';
}
}
/// emitEndOfLineMatrix - Emit the last address of the section and the end of
/// the line matrix.
///
void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
// Define last address of section.
Asm->EmitInt8(0); EOL("Extended Op");
Asm->EmitInt8(TD->getPointerSize() + 1); EOL("Op size");
Asm->EmitInt8(dwarf::DW_LNE_set_address); EOL("DW_LNE_set_address");
EmitReference("section_end", SectionEnd); EOL("Section end label");
// Mark end of matrix.
Asm->EmitInt8(0); EOL("DW_LNE_end_sequence");
Asm->EmitInt8(1);
Asm->EmitInt8(1);
}
/// emitDebugLines - Emit source line information.
///
void DwarfDebug::emitDebugLines() {
// If the target is using .loc/.file, the assembler will be emitting the
// .debug_line table automatically.
if (MAI->hasDotLocAndDotFile())
return;
// Minimum line delta, thus ranging from -10..(255-10).
const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
// Maximum line delta, thus ranging from -10..(255-10).
const int MaxLineDelta = 255 + MinLineDelta;
// Start the dwarf line section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfLineSection());
// Construct the section header.
EmitDifference("line_end", 0, "line_begin", 0, true);
EOL("Length of Source Line Info");
EmitLabel("line_begin", 0);
Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("DWARF version number");
EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
EOL("Prolog Length");
EmitLabel("line_prolog_begin", 0);
Asm->EmitInt8(1); EOL("Minimum Instruction Length");
Asm->EmitInt8(1); EOL("Default is_stmt_start flag");
Asm->EmitInt8(MinLineDelta); EOL("Line Base Value (Special Opcodes)");
Asm->EmitInt8(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
Asm->EmitInt8(-MinLineDelta); EOL("Special Opcode Base");
// Line number standard opcode encodings argument count
Asm->EmitInt8(0); EOL("DW_LNS_copy arg count");
Asm->EmitInt8(1); EOL("DW_LNS_advance_pc arg count");
Asm->EmitInt8(1); EOL("DW_LNS_advance_line arg count");
Asm->EmitInt8(1); EOL("DW_LNS_set_file arg count");
Asm->EmitInt8(1); EOL("DW_LNS_set_column arg count");
Asm->EmitInt8(0); EOL("DW_LNS_negate_stmt arg count");
Asm->EmitInt8(0); EOL("DW_LNS_set_basic_block arg count");
Asm->EmitInt8(0); EOL("DW_LNS_const_add_pc arg count");
Asm->EmitInt8(1); EOL("DW_LNS_fixed_advance_pc arg count");
// Emit directories.
for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
const std::string &Dir = getSourceDirectoryName(DI);
if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Directory");
Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
}
Asm->EmitInt8(0); EOL("End of directories");
// Emit files.
for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
// Remember source id starts at 1.
std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
const std::string &FN = getSourceFileName(Id.second);
if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("Source");
Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
EmitULEB128(Id.first, "Directory #");
EmitULEB128(0, "Mod date");
EmitULEB128(0, "File size");
}
Asm->EmitInt8(0); EOL("End of files");
EmitLabel("line_prolog_end", 0);
// A sequence for each text section.
unsigned SecSrcLinesSize = SectionSourceLines.size();
for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
// Isolate current sections line info.
const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
/*if (Asm->isVerbose()) {
const MCSection *S = SectionMap[j + 1];
O << '\t' << MAI->getCommentString() << " Section"
<< S->getName() << '\n';
}*/
Asm->O << '\n';
// Dwarf assumes we start with first line of first source file.
unsigned Source = 1;
unsigned Line = 1;
// Construct rows of the address, source, line, column matrix.
for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
const SrcLineInfo &LineInfo = LineInfos[i];
unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
if (!LabelID) continue;
if (LineInfo.getLine() == 0) continue;
if (!Asm->isVerbose())
Asm->O << '\n';
else {
std::pair<unsigned, unsigned> SourceID =
getSourceDirectoryAndFileIds(LineInfo.getSourceID());
O << '\t' << MAI->getCommentString() << ' '
<< getSourceDirectoryName(SourceID.first) << '/'
<< getSourceFileName(SourceID.second)
<< ':' << utostr_32(LineInfo.getLine()) << '\n';
}
// Define the line address.
Asm->EmitInt8(0); EOL("Extended Op");
Asm->EmitInt8(TD->getPointerSize() + 1); EOL("Op size");
Asm->EmitInt8(dwarf::DW_LNE_set_address); EOL("DW_LNE_set_address");
EmitReference("label", LabelID); EOL("Location label");
// If change of source, then switch to the new source.
if (Source != LineInfo.getSourceID()) {
Source = LineInfo.getSourceID();
Asm->EmitInt8(dwarf::DW_LNS_set_file); EOL("DW_LNS_set_file");
EmitULEB128(Source, "New Source");
}
// If change of line.
if (Line != LineInfo.getLine()) {
// Determine offset.
int Offset = LineInfo.getLine() - Line;
int Delta = Offset - MinLineDelta;
// Update line.
Line = LineInfo.getLine();
// If delta is small enough and in range...
if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
// ... then use fast opcode.
Asm->EmitInt8(Delta - MinLineDelta); EOL("Line Delta");
} else {
// ... otherwise use long hand.
Asm->EmitInt8(dwarf::DW_LNS_advance_line);
EOL("DW_LNS_advance_line");
EmitSLEB128(Offset, "Line Offset");
Asm->EmitInt8(dwarf::DW_LNS_copy); EOL("DW_LNS_copy");
}
} else {
// Copy the previous row (different address or source)
Asm->EmitInt8(dwarf::DW_LNS_copy); EOL("DW_LNS_copy");
}
}
emitEndOfLineMatrix(j + 1);
}
if (SecSrcLinesSize == 0)
// Because we're emitting a debug_line section, we still need a line
// table. The linker and friends expect it to exist. If there's nothing to
// put into it, emit an empty table.
emitEndOfLineMatrix(1);
EmitLabel("line_end", 0);
Asm->O << '\n';
}
/// emitCommonDebugFrame - Emit common frame info into a debug frame section.
///
void DwarfDebug::emitCommonDebugFrame() {
if (!MAI->doesDwarfRequireFrameSection())
return;
int stackGrowth =
Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
TargetFrameInfo::StackGrowsUp ?
TD->getPointerSize() : -TD->getPointerSize();
// Start the dwarf frame section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfFrameSection());
EmitLabel("debug_frame_common", 0);
EmitDifference("debug_frame_common_end", 0,
"debug_frame_common_begin", 0, true);
EOL("Length of Common Information Entry");
EmitLabel("debug_frame_common_begin", 0);
Asm->EmitInt32((int)dwarf::DW_CIE_ID);
EOL("CIE Identifier Tag");
Asm->EmitInt8(dwarf::DW_CIE_VERSION);
EOL("CIE Version");
Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
EOL("CIE Augmentation");
EmitULEB128(1, "CIE Code Alignment Factor");
EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
EOL("CIE RA Column");
std::vector<MachineMove> Moves;
RI->getInitialFrameState(Moves);
EmitFrameMoves(NULL, 0, Moves, false);
Asm->EmitAlignment(2, 0, 0, false);
EmitLabel("debug_frame_common_end", 0);
Asm->O << '\n';
}
/// emitFunctionDebugFrame - Emit per function frame info into a debug frame
/// section.
void
DwarfDebug::emitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
if (!MAI->doesDwarfRequireFrameSection())
return;
// Start the dwarf frame section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfFrameSection());
EmitDifference("debug_frame_end", DebugFrameInfo.Number,
"debug_frame_begin", DebugFrameInfo.Number, true);
EOL("Length of Frame Information Entry");
EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
EmitSectionOffset("debug_frame_common", "section_debug_frame",
0, 0, true, false);
EOL("FDE CIE offset");
EmitReference("func_begin", DebugFrameInfo.Number);
EOL("FDE initial location");
EmitDifference("func_end", DebugFrameInfo.Number,
"func_begin", DebugFrameInfo.Number);
EOL("FDE address range");
EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
false);
Asm->EmitAlignment(2, 0, 0, false);
EmitLabel("debug_frame_end", DebugFrameInfo.Number);
Asm->O << '\n';
}
/// emitDebugPubNames - Emit visible names into a debug pubnames section.
///
void DwarfDebug::emitDebugPubNames() {
// Start the dwarf pubnames section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfPubNamesSection());
EmitDifference("pubnames_end", ModuleCU->getID(),
"pubnames_begin", ModuleCU->getID(), true);
EOL("Length of Public Names Info");
EmitLabel("pubnames_begin", ModuleCU->getID());
Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("DWARF Version");
EmitSectionOffset("info_begin", "section_info",
ModuleCU->getID(), 0, true, false);
EOL("Offset of Compilation Unit Info");
EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
true);
EOL("Compilation Unit Length");
const StringMap<DIE*> &Globals = ModuleCU->getGlobals();
for (StringMap<DIE*>::const_iterator
GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
const char *Name = GI->getKeyData();
DIE * Entity = GI->second;
Asm->EmitInt32(Entity->getOffset()); EOL("DIE offset");
if (Asm->VerboseAsm)
Asm->OutStreamer.AddComment("External Name");
Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
}
Asm->EmitInt32(0); EOL("End Mark");
EmitLabel("pubnames_end", ModuleCU->getID());
Asm->O << '\n';
}
void DwarfDebug::emitDebugPubTypes() {
// Start the dwarf pubnames section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfPubTypesSection());
EmitDifference("pubtypes_end", ModuleCU->getID(),
"pubtypes_begin", ModuleCU->getID(), true);
EOL("Length of Public Types Info");
EmitLabel("pubtypes_begin", ModuleCU->getID());
if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DWARF Version");
Asm->EmitInt16(dwarf::DWARF_VERSION);
EmitSectionOffset("info_begin", "section_info",
ModuleCU->getID(), 0, true, false);
EOL("Offset of Compilation ModuleCU Info");
EmitDifference("info_end", ModuleCU->getID(), "info_begin", ModuleCU->getID(),
true);
EOL("Compilation ModuleCU Length");
const StringMap<DIE*> &Globals = ModuleCU->getGlobalTypes();
for (StringMap<DIE*>::const_iterator
GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
const char *Name = GI->getKeyData();
DIE * Entity = GI->second;
if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DIE offset");
Asm->EmitInt32(Entity->getOffset());
if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("External Name");
Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
}
Asm->EmitInt32(0); EOL("End Mark");
EmitLabel("pubtypes_end", ModuleCU->getID());
Asm->O << '\n';
}
/// emitDebugStr - Emit visible names into a debug str section.
///
void DwarfDebug::emitDebugStr() {
// Check to see if it is worth the effort.
if (!StringPool.empty()) {
// Start the dwarf str section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfStrSection());
// For each of strings in the string pool.
for (unsigned StringID = 1, N = StringPool.size();
StringID <= N; ++StringID) {
// Emit a label for reference from debug information entries.
EmitLabel("string", StringID);
// Emit the string itself.
const std::string &String = StringPool[StringID];
Asm->OutStreamer.EmitBytes(StringRef(String.c_str(), String.size()+1), 0);
}
Asm->O << '\n';
}
}
/// emitDebugLoc - Emit visible names into a debug loc section.
///
void DwarfDebug::emitDebugLoc() {
// Start the dwarf loc section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfLocSection());
}
/// EmitDebugARanges - Emit visible names into a debug aranges section.
///
void DwarfDebug::EmitDebugARanges() {
// Start the dwarf aranges section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfARangesSection());
// FIXME - Mock up
#if 0
CompileUnit *Unit = GetBaseCompileUnit();
// Don't include size of length
Asm->EmitInt32(0x1c); EOL("Length of Address Ranges Info");
Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("Dwarf Version");
EmitReference("info_begin", Unit->getID());
EOL("Offset of Compilation Unit Info");
Asm->EmitInt8(TD->getPointerSize()); EOL("Size of Address");
Asm->EmitInt8(0); EOL("Size of Segment Descriptor");
Asm->EmitInt16(0); EOL("Pad (1)");
Asm->EmitInt16(0); EOL("Pad (2)");
// Range 1
EmitReference("text_begin", 0); EOL("Address");
EmitDifference("text_end", 0, "text_begin", 0, true); EOL("Length");
Asm->EmitInt32(0); EOL("EOM (1)");
Asm->EmitInt32(0); EOL("EOM (2)");
#endif
}
/// emitDebugRanges - Emit visible names into a debug ranges section.
///
void DwarfDebug::emitDebugRanges() {
// Start the dwarf ranges section.
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfRangesSection());
}
/// emitDebugMacInfo - Emit visible names into a debug macinfo section.
///
void DwarfDebug::emitDebugMacInfo() {
if (const MCSection *LineInfo =
Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
// Start the dwarf macinfo section.
Asm->OutStreamer.SwitchSection(LineInfo);
}
}
/// emitDebugInlineInfo - Emit inline info using following format.
/// Section Header:
/// 1. length of section
/// 2. Dwarf version number
/// 3. address size.
///
/// Entries (one "entry" for each function that was inlined):
///
/// 1. offset into __debug_str section for MIPS linkage name, if exists;
/// otherwise offset into __debug_str for regular function name.
/// 2. offset into __debug_str section for regular function name.
/// 3. an unsigned LEB128 number indicating the number of distinct inlining
/// instances for the function.
///
/// The rest of the entry consists of a {die_offset, low_pc} pair for each
/// inlined instance; the die_offset points to the inlined_subroutine die in the
/// __debug_info section, and the low_pc is the starting address for the
/// inlining instance.
void DwarfDebug::emitDebugInlineInfo() {
if (!MAI->doesDwarfUsesInlineInfoSection())
return;
if (!ModuleCU)
return;
Asm->OutStreamer.SwitchSection(
Asm->getObjFileLowering().getDwarfDebugInlineSection());
EmitDifference("debug_inlined_end", 1,
"debug_inlined_begin", 1, true);
EOL("Length of Debug Inlined Information Entry");
EmitLabel("debug_inlined_begin", 1);
Asm->EmitInt16(dwarf::DWARF_VERSION); EOL("Dwarf Version");
Asm->EmitInt8(TD->getPointerSize()); EOL("Address Size (in bytes)");
for (SmallVector<MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
E = InlinedSPNodes.end(); I != E; ++I) {
MDNode *Node = *I;
DenseMap<MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
= InlineInfo.find(Node);
SmallVector<InlineInfoLabels, 4> &Labels = II->second;
DISubprogram SP(Node);
StringRef LName = SP.getLinkageName();
StringRef Name = SP.getName();
if (LName.empty()) {
Asm->OutStreamer.EmitBytes(Name, 0);
Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
} else
EmitSectionOffset("string", "section_str",
StringPool.idFor(getRealLinkageName(LName)), false, true);
EOL("MIPS linkage name");
EmitSectionOffset("string", "section_str",
StringPool.idFor(Name), false, true);
EOL("Function name");
EmitULEB128(Labels.size(), "Inline count");
for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
LE = Labels.end(); LI != LE; ++LI) {
DIE *SP = LI->second;
Asm->EmitInt32(SP->getOffset()); EOL("DIE offset");
if (TD->getPointerSize() == sizeof(int32_t))
O << MAI->getData32bitsDirective();
else
O << MAI->getData64bitsDirective();
PrintLabelName("label", LI->first); EOL("low_pc");
}
}
EmitLabel("debug_inlined_end", 1);
Asm->O << '\n';
}
| {
"content_hash": "4c230a04b96ca6781f8342b9ac76394f",
"timestamp": "",
"source": "github",
"line_count": 3024,
"max_line_length": 82,
"avg_line_length": 34.554232804232804,
"alnum_prop": 0.6598495578608888,
"repo_name": "wrmsr/lljvm",
"id": "5ad1e5ea050961bcaf2c31bcc6d6f7d56ac385ad",
"size": "104492",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "thirdparty/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4870"
},
{
"name": "C++",
"bytes": "91265"
},
{
"name": "Java",
"bytes": "149125"
},
{
"name": "Lua",
"bytes": "177"
},
{
"name": "Makefile",
"bytes": "21245"
},
{
"name": "Python",
"bytes": "8641"
},
{
"name": "Shell",
"bytes": "218"
}
],
"symlink_target": ""
} |
<!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_34) on Wed Oct 23 13:33:57 EDT 2013 -->
<TITLE>
Uses of Class org.hibernate.collection.internal.PersistentSortedMap (Hibernate JavaDocs)
</TITLE>
<META NAME="date" CONTENT="2013-10-23">
<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.hibernate.collection.internal.PersistentSortedMap (Hibernate JavaDocs)";
}
}
</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/hibernate/collection/internal/PersistentSortedMap.html" title="class in org.hibernate.collection.internal"><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="../../../../../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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</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/hibernate/collection/internal//class-usePersistentSortedMap.html" target="_top"><B>FRAMES</B></A>
<A HREF="PersistentSortedMap.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.hibernate.collection.internal.PersistentSortedMap</B></H2>
</CENTER>
No usage of org.hibernate.collection.internal.PersistentSortedMap
<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/hibernate/collection/internal/PersistentSortedMap.html" title="class in org.hibernate.collection.internal"><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="../../../../../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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</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/hibernate/collection/internal//class-usePersistentSortedMap.html" target="_top"><B>FRAMES</B></A>
<A HREF="PersistentSortedMap.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>
Copyright © 2001-2013 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "a374788a5b7722d0c7b7bbb7835577a6",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 243,
"avg_line_length": 43.166666666666664,
"alnum_prop": 0.624034749034749,
"repo_name": "HerrB92/obp",
"id": "2645504c9f19977225579ae728620bd6c9212fe6",
"size": "6216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/documentation/javadocs/org/hibernate/collection/internal/class-use/PersistentSortedMap.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "181658"
},
{
"name": "Groovy",
"bytes": "98685"
},
{
"name": "Java",
"bytes": "34621856"
},
{
"name": "JavaScript",
"bytes": "356255"
},
{
"name": "Shell",
"bytes": "194"
},
{
"name": "XSLT",
"bytes": "21372"
}
],
"symlink_target": ""
} |
@interface GYMExerciseListTableViewCellModel ()
@property (nonatomic, copy, readwrite) NSString *weight;
@property (nonatomic, copy, readwrite) NSString *numberOfRepetitions;
@property (nonatomic, copy, readwrite) NSString *numberOfSets;
@property (nonatomic, copy, readwrite) NSString *exerciseName;
@end
@implementation GYMExerciseListTableViewCellModel
- (id)init {
self = [super init];
if (!self) return nil;
[[RACObserve(self, exercise) ignore:nil] subscribeNext:^(GYMExercise *exercise1) {
self.exerciseName = exercise1.name;
self.numberOfRepetitions = [@(exercise1.numberOfRepetitions) stringValue];
self.numberOfSets = [@(exercise1.numberOfSets) stringValue];
self.weight = [@(exercise1.weight) stringValue];
}];
return self;
}
@end | {
"content_hash": "773304304131b06d24be14e4ab684961",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 83,
"avg_line_length": 32.95652173913044,
"alnum_prop": 0.7638522427440633,
"repo_name": "gymmy/gymmy-ios",
"id": "9b780c0730cfc6d7dffddf8e098415905a998897",
"size": "869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gymmy-ios/View Controllers/Exercise List VC/GYMExerciseListTableViewCellModel.m",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "61831"
},
{
"name": "C++",
"bytes": "118180"
},
{
"name": "D",
"bytes": "412"
},
{
"name": "Objective-C",
"bytes": "727198"
},
{
"name": "Ruby",
"bytes": "157"
},
{
"name": "Shell",
"bytes": "7104"
}
],
"symlink_target": ""
} |
package com.eeeya.fantuan.api.android.client.model;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
**/
@ApiModel(description = "")
public class ResultModelOfTableStatus {
private String message = null;
private Object ext = null;
private Integer status = null;
private Long time = null;
private TableStatus data = null;
/**
* 错误信息
**/
@ApiModelProperty(required = false, value = "错误信息")
@JsonProperty("message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* 其它信息
**/
@ApiModelProperty(required = false, value = "其它信息")
@JsonProperty("ext")
public Object getExt() {
return ext;
}
public void setExt(Object ext) {
this.ext = ext;
}
/**
* 请求状态, 0表示正常
**/
@ApiModelProperty(required = false, value = "请求状态, 0表示正常")
@JsonProperty("status")
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
/**
* 服务器时间
**/
@ApiModelProperty(required = false, value = "服务器时间")
@JsonProperty("time")
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
/**
* 请求的数据
**/
@ApiModelProperty(required = false, value = "请求的数据")
@JsonProperty("data")
public TableStatus getData() {
return data;
}
public void setData(TableStatus data) {
this.data = data;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ResultModelOfTableStatus {\n");
sb.append(" message: ").append(message).append("\n");
sb.append(" ext: ").append(ext).append("\n");
sb.append(" status: ").append(status).append("\n");
sb.append(" time: ").append(time).append("\n");
sb.append(" data: ").append(data).append("\n");
sb.append("}\n");
return sb.toString();
}
}
| {
"content_hash": "14f2dd08980e5fe3bf039747a6d0df64",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 60,
"avg_line_length": 20.071428571428573,
"alnum_prop": 0.6161667513980681,
"repo_name": "huizhong/fantuan",
"id": "1d15871710f25dc47692928c16a9a63f9edeb027",
"size": "2071",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "fantuan-api-android-client/src/main/java/com/eeeya/fantuan/api/android/client/model/ResultModelOfTableStatus.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "45753"
},
{
"name": "FreeMarker",
"bytes": "23054"
},
{
"name": "HTML",
"bytes": "4552"
},
{
"name": "Java",
"bytes": "818145"
},
{
"name": "JavaScript",
"bytes": "328354"
},
{
"name": "Shell",
"bytes": "5443"
}
],
"symlink_target": ""
} |
$(document).ready(function(){
var SlideMenu = function(selector) {
this.selector = selector;
this.element = function(){
return $(this.selector);
};
this.currentWidth = function() {
return this.element().width();
};
this.minWidth = this.element().width();
this.maxWidth = this.minWidth + 75;
this.toggle = function(){
if(this.currentWidth() == this.minWidth) {
this.element().animate({width: this.maxWidth}, function(){
$('.menu-label').fadeIn();
});
} else {
$('.menu-label').fadeOut(function(){
slideMenu.element().animate({width: slideMenu.minWidth});
});
}
return true;
};
this.element();
};
var slideMenu = new SlideMenu('.slide-menu');
var slideMenuIcons = new SlideMenu('.slide-menu');
document.logout = function(path){
$.ajax({
type: "DELETE",
url: path
}).done(function() {
window.location = '/';
});
};
document.toggleSlideMenu = function () {
slideMenu.toggle('.slide-menu');
slideMenuIcons.toggle('.slide-menu i');
};
});
| {
"content_hash": "b6236c2509574686bea14bc3f5db3fd8",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 66,
"avg_line_length": 25.295454545454547,
"alnum_prop": 0.5705300988319856,
"repo_name": "JLWolfe1990/blast",
"id": "d466145888047df41ea1a3b5d4acd2833f17bd90",
"size": "1113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/javascripts/navbar.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13864"
},
{
"name": "HTML",
"bytes": "8877"
},
{
"name": "JavaScript",
"bytes": "7939"
},
{
"name": "Ruby",
"bytes": "71571"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>subst: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.0 / subst - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
subst
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-21 08:17:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-21 08:17:32 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/subst"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Subst"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: lambda-sigma-lift-calculus" "keyword: explicit substitution" "keyword: Newman's lemma" "keyword: Yokouchi's lemma" "keyword: confluence" "keyword: rewriting" "category: Computer Science/Lambda Calculi" ]
authors: [ "Amokrane Saïbi" ]
bug-reports: "https://github.com/coq-contribs/subst/issues"
dev-repo: "git+https://github.com/coq-contribs/subst.git"
synopsis: "The confluence of Hardin-Lévy lambda-sigma-lift-calcul"
description: """
The confluence of Hardin-Lévy lambda-sigma-lift-calcul is
proven. By the way, several standard definition and results about
rewriting systems are proven (Newman's lemma, Yokouchi's lemma, ...)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/subst/archive/v8.6.0.tar.gz"
checksum: "md5=ec5d84b616435ee0e09716cd6fdbdc36"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-subst.8.6.0 coq.8.8.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0).
The following dependencies couldn't be met:
- coq-subst -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-subst.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "eaa10f700cd02fc28761457322f51b4c",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 299,
"avg_line_length": 42.696969696969695,
"alnum_prop": 0.5442157558552164,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "273f665800eff3201b255aab5a391eeb99312a65",
"size": "7073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.8.0/subst/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Trans. Br. mycol. Soc. 11: 190 (1926)
#### Original name
Cryptotheciaceae A.L. Sm.
### Remarks
null | {
"content_hash": "04fe31bf46a5591b2c9a2c400ec9d7a1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 37,
"avg_line_length": 12.538461538461538,
"alnum_prop": 0.6748466257668712,
"repo_name": "mdoering/backbone",
"id": "870088d289aa24b8a4854a3cd0af4c34c99a127c",
"size": "211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/incertae sedis/Cryptotheciaceae/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package pt.trycatch.javax.sound.midi;
import java.io.ByteArrayOutputStream;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
/**
* MIDI Input Device
* stop() method must be called when the application will be destroyed.
*
* @author K.Shoji
*/
public final class MidiInputDevice {
private final UsbDevice usbDevice;
final UsbDeviceConnection usbDeviceConnection;
private final UsbInterface usbInterface;
final UsbEndpoint inputEndpoint;
final OnMidiInputEventListener midiEventListener;
private final WaiterThread waiterThread;
/**
* constructor
*
* @param usbDevice
* @param usbDeviceConnection
* @param usbInterface
* @param midiEventListener
* @throws IllegalArgumentException endpoint not found.
*/
public MidiInputDevice(UsbDevice usbDevice, UsbDeviceConnection usbDeviceConnection, UsbInterface usbInterface, UsbEndpoint usbEndpoint, OnMidiInputEventListener midiEventListener) throws IllegalArgumentException {
this.usbDevice = usbDevice;
this.usbDeviceConnection = usbDeviceConnection;
this.usbInterface = usbInterface;
this.midiEventListener = midiEventListener;
waiterThread = new WaiterThread();
inputEndpoint = usbEndpoint;
if (inputEndpoint == null) {
throw new IllegalArgumentException("Input endpoint was not found.");
}
usbDeviceConnection.claimInterface(usbInterface, true);
waiterThread.setPriority(8);
waiterThread.start();
}
/**
* stops the watching thread
*/
public void stop() {
usbDeviceConnection.releaseInterface(usbInterface);
waiterThread.stopFlag = true;
// blocks while the thread will stop
while (waiterThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
}
}
/**
* @return the usbDevice
*/
public UsbDevice getUsbDevice() {
return usbDevice;
}
/**
* @return the usbInterface
*/
public UsbInterface getUsbInterface() {
return usbInterface;
}
/**
* @return the usbEndpoint
*/
public UsbEndpoint getUsbEndpoint() {
return inputEndpoint;
}
/**
* Polling thread for input data.
* Loops infinitely while stopFlag == false.
*
* @author K.Shoji
*/
final class WaiterThread extends Thread {
private static final int BUFFER_LENGTH = 64;
boolean stopFlag;
/**
* constructor
*/
WaiterThread() {
stopFlag = false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
final UsbDeviceConnection deviceConnection = usbDeviceConnection;
final UsbEndpoint usbEndpoint = inputEndpoint;
final MidiInputDevice sender = MidiInputDevice.this;
final OnMidiInputEventListener eventListener = midiEventListener;
// prepare buffer variables
final byte[] bulkReadBuffer = new byte[BUFFER_LENGTH];
byte[] readBuffer = new byte[BUFFER_LENGTH * 2]; // *2 for safety (BUFFER_LENGTH+4 would be enough)
int readBufferSize = 0;
byte[] read = new byte[BUFFER_LENGTH * 2];
ByteArrayOutputStream systemExclusive = null;
while (!stopFlag) {
int length = deviceConnection.bulkTransfer(usbEndpoint, bulkReadBuffer, BUFFER_LENGTH, 0);
if (length > 0) {
System.arraycopy(bulkReadBuffer, 0, readBuffer, readBufferSize, length);
readBufferSize += length;
if (readBufferSize < 4) {
// more data needed
continue;
}
// USB MIDI data stream: 4 bytes boundary
final int readSize = readBufferSize / 4 * 4;
System.arraycopy(readBuffer, 0, read, 0, readSize); // fill the read array
// keep unread bytes
int unreadSize = readBufferSize - readSize;
if (unreadSize > 0) {
System.arraycopy(readBuffer, readSize, readBuffer, 0, unreadSize);
readBufferSize = unreadSize;
} else {
readBufferSize = 0;
}
int cable;
int codeIndexNumber;
int byte1;
int byte2;
int byte3;
for (int i = 0; i < readSize; i += 4) {
cable = (read[i + 0] >> 4) & 0xf;
codeIndexNumber = read[i + 0] & 0xf;
byte1 = read[i + 1] & 0xff;
byte2 = read[i + 2] & 0xff;
byte3 = read[i + 3] & 0xff;
switch (codeIndexNumber) {
case 0:
eventListener.onMidiMiscellaneousFunctionCodes(sender, cable, byte1, byte2, byte3);
break;
case 1:
eventListener.onMidiCableEvents(sender, cable, byte1, byte2, byte3);
break;
case 2:
// system common message with 2 bytes
{
byte[] bytes = new byte[] { (byte) byte1, (byte) byte2 };
eventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 3:
// system common message with 3 bytes
{
byte[] bytes = new byte[] { (byte) byte1, (byte) byte2, (byte) byte3 };
eventListener.onMidiSystemCommonMessage(sender, cable, bytes);
}
break;
case 4:
// sysex starts, and has next
synchronized (this) {
if (systemExclusive == null) {
systemExclusive = new ByteArrayOutputStream();
}
}
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
}
break;
case 5:
// system common message with 1byte
// sysex end with 1 byte
if (systemExclusive == null) {
byte[] bytes = new byte[] { (byte) byte1 };
eventListener.onMidiSystemCommonMessage(sender, cable, bytes);
} else {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
eventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 6:
// sysex end with 2 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
eventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 7:
// sysex end with 3 bytes
if (systemExclusive != null) {
synchronized (systemExclusive) {
systemExclusive.write(byte1);
systemExclusive.write(byte2);
systemExclusive.write(byte3);
eventListener.onMidiSystemExclusive(sender, cable, systemExclusive.toByteArray());
}
synchronized (this) {
systemExclusive = null;
}
}
break;
case 8:
eventListener.onMidiNoteOff(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 9:
if (byte3 == 0x00) {
eventListener.onMidiNoteOff(sender, cable, byte1 & 0xf, byte2, byte3);
} else {
eventListener.onMidiNoteOn(sender, cable, byte1 & 0xf, byte2, byte3);
}
break;
case 10:
// poly key press
eventListener.onMidiPolyphonicAftertouch(sender, cable, byte1 & 0xf, byte2, byte3);
break;
case 11:
// control change
eventListener.onMidiControlChange(sender, cable, byte1 & 0xf, byte2, byte3);
processRpnMessages(cable, byte1, byte2, byte3, sender);
break;
case 12:
// program change
eventListener.onMidiProgramChange(sender, cable, byte1 & 0xf, byte2);
break;
case 13:
// channel pressure
eventListener.onMidiChannelAftertouch(sender, cable, byte1 & 0xf, byte2);
break;
case 14:
// pitch bend
eventListener.onMidiPitchWheel(sender, cable, byte1 & 0xf, byte2 | (byte3 << 7));
break;
case 15:
// single byte
eventListener.onMidiSingleByte(sender, cable, byte1);
break;
default:
// do nothing.
break;
}
}
}
}
}
private RPNStatus rpnStatus = RPNStatus.NONE;
private int rpnFunctionMSB = 0x7f;
private int rpnFunctionLSB = 0x7f;
private int nrpnFunctionMSB = 0x7f;
private int nrpnFunctionLSB = 0x7f;
private int rpnValueMSB;
/**
* RPN and NRPN messages
*
* @param cable
* @param byte1
* @param byte2
* @param byte3
*/
private void processRpnMessages(int cable, int byte1, int byte2, int byte3, MidiInputDevice sender) {
switch (byte2) {
case 6:
rpnValueMSB = byte3 & 0x7f;
if (rpnStatus == RPNStatus.RPN) {
midiEventListener.onMidiRPNReceived(sender, cable, byte1, ((rpnFunctionMSB & 0x7f) << 7) & (rpnFunctionLSB & 0x7f), rpnValueMSB, -1);
} else if (rpnStatus == RPNStatus.NRPN) {
midiEventListener.onMidiNRPNReceived(sender, cable, byte1, ((nrpnFunctionMSB & 0x7f) << 7) & (nrpnFunctionLSB & 0x7f), rpnValueMSB, -1);
}
break;
case 38:
if (rpnStatus == RPNStatus.RPN) {
midiEventListener.onMidiRPNReceived(sender, cable, byte1, ((rpnFunctionMSB & 0x7f) << 7) & (rpnFunctionLSB & 0x7f), rpnValueMSB, byte3 & 0x7f);
} else if (rpnStatus == RPNStatus.NRPN) {
midiEventListener.onMidiNRPNReceived(sender, cable, byte1, ((nrpnFunctionMSB & 0x7f) << 7) & (nrpnFunctionLSB & 0x7f), rpnValueMSB, byte3 & 0x7f);
}
break;
case 98:
nrpnFunctionLSB = byte3 & 0x7f;
rpnStatus = RPNStatus.NRPN;
break;
case 99:
nrpnFunctionMSB = byte3 & 0x7f;
rpnStatus = RPNStatus.NRPN;
break;
case 100:
rpnFunctionLSB = byte3 & 0x7f;
if (rpnFunctionMSB == 0x7f && rpnFunctionLSB == 0x7f) {
rpnStatus = RPNStatus.NONE;
} else {
rpnStatus = RPNStatus.RPN;
}
break;
case 101:
rpnFunctionMSB = byte3 & 0x7f;
if (rpnFunctionMSB == 0x7f && rpnFunctionLSB == 0x7f) {
rpnStatus = RPNStatus.NONE;
} else {
rpnStatus = RPNStatus.RPN;
}
break;
default:
break;
}
}
}
/**
* current RPN status
*
* @author K.Shoji
*/
enum RPNStatus {
RPN, NRPN, NONE
}
}
| {
"content_hash": "296556d212d77d89d152e1176c8196fa",
"timestamp": "",
"source": "github",
"line_count": 359,
"max_line_length": 215,
"avg_line_length": 27.899721448467968,
"alnum_prop": 0.6429712460063898,
"repo_name": "nmldiegues/jamify",
"id": "252269f36a81dd16b32786d10bf179e3b2040c3d",
"size": "10016",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/pt/trycatch/javax/sound/midi/MidiInputDevice.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "875753"
}
],
"symlink_target": ""
} |
Satoyama API official server
| {
"content_hash": "d6c55952feb844729cc0f046960a85bf",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 28,
"avg_line_length": 29,
"alnum_prop": 0.8620689655172413,
"repo_name": "DgFutureLab/satoyama-api",
"id": "100d0201393ca441efde8131ff4194e1746ca051",
"size": "29",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4011"
},
{
"name": "HTML",
"bytes": "396"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "92075"
},
{
"name": "Shell",
"bytes": "6928"
}
],
"symlink_target": ""
} |
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 2.1.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v2.1/admin/html/
*/var handleDataTableKeyTable=function(){"use strict";0!==$("#data-table").length&&$("#data-table").DataTable({scrollY:300,paging:!1,autoWidth:!0,keys:!0,responsive:!0})},TableManageKeyTable=function(){"use strict";return{init:function(){handleDataTableKeyTable()}}}(); | {
"content_hash": "196176062c1a1bb1536d6cf11c0bcffa",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 269,
"avg_line_length": 78.66666666666667,
"alnum_prop": 0.7415254237288136,
"repo_name": "geoffroygivry/CyclopsVFX-Polyphemus",
"id": "4c92d5c4211826cc6f9db427c8f978d5c3d60982",
"size": "472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/polyphemus/assets/js/table-manage-keytable.demo.min.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4238853"
},
{
"name": "CoffeeScript",
"bytes": "20287"
},
{
"name": "HTML",
"bytes": "2424188"
},
{
"name": "JavaScript",
"bytes": "10989241"
},
{
"name": "PHP",
"bytes": "20589"
},
{
"name": "Python",
"bytes": "73967"
},
{
"name": "Shell",
"bytes": "1781"
}
],
"symlink_target": ""
} |
<?php
class ElementTests extends Octopus_Html_TestCase {
function testTextEscapesProperly() {
$e = new Octopus_Html_Element('span');
$e->text(<<<END
'quotes should be intact, <> but "angle brackets" should be escaped'
END
);
$this->assertHtmlEquals(
<<<END
<span>'quotes should be intact, <> but "angle brackets" should be escaped'</span>
END
,
$e->render(true)
);
}
function testDontEscapeAttributesDeep() {
$el = new Octopus_Html_Element('span');
$el->title = '>';
$child = new Octopus_Html_Element('span');
$child->title = '<';
$el->append($child);
$this->assertHtmlEquals(
<<<END
<span title=">"><span title="<" /></span>
END
,
$el->render(true, Octopus_Html_Element::DONT_ESCAPE_ATTRIBUTES)
);
}
function testByDefaultEscapeAttributes() {
$el = new Octopus_Html_Element('span');
$el->title = "<'this is a test'>";
$this->assertHtmlEquals(
<<<END
<span title="<'this is a test'>" />
END
,
$el->render(true)
);
}
function testOptionallyDontEscapeAttributes() {
$el = new Octopus_Html_Element('span');
$el->title = "<This is a test>";
$this->assertHtmlEquals(
<<<END
<span title="<This is a test>" />
END
,
$el->render(true, Octopus_Html_Element::DONT_ESCAPE_ATTRIBUTES)
);
}
function testAppendTo() {
$parent = new Octopus_Html_Element('div');
$span = new Octopus_Html_Element('span');
$this->assertSame($span, $span->text('test')->appendTo($parent));
$this->assertHtmlEquals(
<<<END
<div><span>test</span></div>
END
,
$parent->render(true)
);
}
function testPrependTo() {
$parent = new Octopus_Html_Element('div');
$child1 = new Octopus_Html_Element('span');
$child2 = new Octopus_Html_Element('span');
$child2->text('child 2')->appendTo($parent);
$this->assertSame($child1, $child1->text('child 1')->prependTo($parent));
$this->assertHtmlEquals(
<<<END
<div><span>child 1</span><span>child 2</span></div>
END
,
$parent->render(true)
);
}
function testInsertBefore() {
$parent = new Octopus_Html_Element('div');
$child1 = new Octopus_Html_Element('span', array(), 'foo');
$parent->append($child1);
$child2 = new Octopus_Html_Element('span', array(), 'bar');
$child2->insertBefore($child1);
$this->assertHtmlEquals(
<<<END
<div>
<span>bar</span><span>foo</span>
</div>
END
,
$parent->render(true)
);
}
function testInsertAfter() {
$parent = new Octopus_Html_Element('div');
$child1 = new Octopus_Html_Element('span', array(), 'foo');
$parent->append($child1);
$child2 = new Octopus_Html_Element('span', array(), 'bar');
$child2->insertAfter($child1);
$child3 = new Octopus_Html_Element('span', array(), 'baz');
$child3->insertAfter($child1);
$this->assertHtmlEquals(
<<<END
<div>
<span>foo</span><span>baz</span><span>bar</span>
</div>
END
,
$parent->render(true)
);
}
function testIsTag() {
$e = new Octopus_Html_Element('blockquote');
$this->assertTrue($e->is('blockquote'));
$this->assertFalse($e->is('div'));
}
function testSingleTagRender() {
$e = new Octopus_Html_Element('img', array('src' => 'test.png', 'alt' => 'Alt Text'));
$this->assertHtmlEquals(
'<img src="test.png" alt="Alt Text" />',
$e->render(true)
);
}
function testAttrMethod() {
$e = new Octopus_Html_Element('span', 'content');
$e->attr('id', 'foo');
$this->assertEquals('<span id="foo">content</span>', trim($e->render(true)));
$this->assertEquals('foo', $e->attr('id'));
$e->attr(array(
'class' => 'testClass',
'title' => 'test title'
));
$this->assertEquals('<span id="foo" class="testClass" title="test title">content</span>', trim($e->render(true)));
}
function testAttributes() {
$e = new Octopus_Html_Element('span');
$e->class = 'testClass';
$e->setAttribute('lang', 'en-us');
$e->css('font-weight', 'bold');
$this->assertHtmlEquals(
"<span class=\"testClass\" style=\"font-weight: bold;\" lang=\"en-us\" />",
$e->render(true)
);
unset($e->class);
$this->assertHtmlEquals(
"<span style=\"font-weight: bold;\" lang=\"en-us\" />",
$e->render(true)
);
$e->removeAttribute('style');
$this->assertHtmlEquals(
"<span lang=\"en-us\" />",
$e->render(true)
);
$e->setAttribute('lang', null);
$this->assertHtmlEquals(
"<span />",
$e->render(true)
);
$e->data('id', 42);
$this->assertHtmlEquals(
"<span data-id=\"42\" />",
$e->render(true)
);
$e->removeAttribute('data-id');
$this->assertHtmlEquals('<span />', $e->render(true));
$e->css(array('color' => 'red', 'font-weight' => 'bold'));
$this->assertHtmlEquals('<span style="color: red; font-weight: bold;" />', $e->render(true));
unset($e->style);
$this->assertHtmlEquals('<span />', $e->render(true));
$e->data(array('id' => 42, 'foo' => 'bar'));
$this->assertHtmlEquals('<span data-foo="bar" data-id="42" />', $e->render(true));
$e->removeAttribute('data-id');
$this->assertHtmlEquals('<span data-foo="bar" />', $e->render(true));
}
function testAddAndRemoveClass() {
$e = new Octopus_Html_Element('span');
$e->addClass('foo');
$this->assertHtmlEquals('<span class="foo" />', $e->render(true));
$e->removeClass('foo');
$this->assertHtmlEquals('<span />', $e->render(true));
$e->addClass('foo bar');
$this->assertHtmlEquals('<span class="foo bar" />', $e->render(true));
$e->addClass(array('baz', 'bat'));
$this->assertHtmlEquals('<span class="foo bar baz bat" />', $e->render(true));
$e->removeClass(array('foo', 'baz'));
$this->assertHtmlEquals('<span class="bar bat" />', $e->render(true));
$e->removeClass('bar bat');
$this->assertHtmlEquals('<span />', $e->render(true));
$e->toggleClass('toggle');
$this->assertHtmlEquals('<span class="toggle" />', $e->render(true));
$e->addClass(' foo bar');
$this->assertHtmlEquals('<span class="toggle foo bar" />', $e->render(true));
$e->toggleClass('toggle');
$this->assertHtmlEquals('<span class="foo bar" />', $e->render(true));
}
function testAddRemoveClassWithDashes() {
$e = new Octopus_Html_Element('span');
$e->addClass('my-span');
$this->assertEquals('my-span', $e->class);
$e->addClass('span', 'my');
$this->assertEquals('my-span span my', $e->class);
$e->removeClass('span');
$this->assertEquals('my-span my', $e->class);
$e->removeClass('my');
$this->assertEquals('my-span', $e->class);
$e->removeClass('my-span');
$this->assertEquals('', $e->class);
}
function testInnerText() {
$e = new Octopus_Html_Element('span');
$e->text('<escape> & <test>');
$this->assertHtmlEquals(
'<span><escape> & <test></span>',
$e->render(true)
);
$e->text('foo and bar');
$this->assertEquals('foo and bar', $e->text());
$child1 = new Octopus_Html_Element('span');
$child2 = new Octopus_Html_Element('span');
$child1->text('foo');
$child2->text('bar');
$e->clear();
$e->append($child1);
$e->append($child2);
$this->assertEquals('foo bar', $e->text());
}
function testSetInnerHtml() {
$e = new Octopus_Html_Element('span');
$result = $e->html('<b>bold!</b>');
$this->assertHtmlEquals('<span><b>bold!</b></span>', $e->render(true));
$this->assertEquals($e, $result);
}
}
?>
| {
"content_hash": "8c0f33ed9e484c3fce01659f58c9ae39",
"timestamp": "",
"source": "github",
"line_count": 340,
"max_line_length": 122,
"avg_line_length": 25.33823529411765,
"alnum_prop": 0.5145676146256529,
"repo_name": "codestruck/octopus",
"id": "861fdeead1b7ce24c2019c9b96fe934afc1e8976",
"size": "8750",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/classes/Html/ElementTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "161788"
},
{
"name": "PHP",
"bytes": "3569117"
},
{
"name": "Perl",
"bytes": "3325"
},
{
"name": "Shell",
"bytes": "857"
}
],
"symlink_target": ""
} |
from google.cloud import aiplatform_v1
def sample_update_tensorboard():
# Create a client
client = aiplatform_v1.TensorboardServiceClient()
# Initialize request argument(s)
tensorboard = aiplatform_v1.Tensorboard()
tensorboard.display_name = "display_name_value"
request = aiplatform_v1.UpdateTensorboardRequest(
tensorboard=tensorboard,
)
# Make the request
operation = client.update_tensorboard(request=request)
print("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response)
# [END aiplatform_v1_generated_TensorboardService_UpdateTensorboard_sync]
| {
"content_hash": "11d8eedbd4a8eb36dcb1ca10ebf85bb5",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 73,
"avg_line_length": 25.807692307692307,
"alnum_prop": 0.7257824143070045,
"repo_name": "googleapis/python-aiplatform",
"id": "5718f09a87d4e61cc5a35bfcb423dc51a10b9b96",
"size": "2075",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/generated_samples/aiplatform_v1_generated_tensorboard_service_update_tensorboard_sync.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "23977004"
},
{
"name": "Shell",
"bytes": "30668"
}
],
"symlink_target": ""
} |
package org.apache.spark.sql.catalyst.expressions.aggregate
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.types._
/**
* Compute the covariance between two expressions.
* When applied on empty data (i.e., count is zero), it returns NULL.
*/
abstract class Covariance(x: Expression, y: Expression)
extends DeclarativeAggregate with ImplicitCastInputTypes {
override def children: Seq[Expression] = Seq(x, y)
override def nullable: Boolean = true
override def dataType: DataType = DoubleType
override def inputTypes: Seq[AbstractDataType] = Seq(DoubleType, DoubleType)
protected val n = AttributeReference("n", DoubleType, nullable = false)()
protected val xAvg = AttributeReference("xAvg", DoubleType, nullable = false)()
protected val yAvg = AttributeReference("yAvg", DoubleType, nullable = false)()
protected val ck = AttributeReference("ck", DoubleType, nullable = false)()
override val aggBufferAttributes: Seq[AttributeReference] = Seq(n, xAvg, yAvg, ck)
override val initialValues: Seq[Expression] = Array.fill(4)(Literal(0.0))
override lazy val updateExpressions: Seq[Expression] = {
val newN = n + Literal(1.0)
val dx = x - xAvg
val dy = y - yAvg
val dyN = dy / newN
val newXAvg = xAvg + dx / newN
val newYAvg = yAvg + dyN
val newCk = ck + dx * (y - newYAvg)
val isNull = IsNull(x) || IsNull(y)
Seq(
If(isNull, n, newN),
If(isNull, xAvg, newXAvg),
If(isNull, yAvg, newYAvg),
If(isNull, ck, newCk)
)
}
override val mergeExpressions: Seq[Expression] = {
val n1 = n.left
val n2 = n.right
val newN = n1 + n2
val dx = xAvg.right - xAvg.left
val dxN = If(newN === Literal(0.0), Literal(0.0), dx / newN)
val dy = yAvg.right - yAvg.left
val dyN = If(newN === Literal(0.0), Literal(0.0), dy / newN)
val newXAvg = xAvg.left + dxN * n2
val newYAvg = yAvg.left + dyN * n2
val newCk = ck.left + ck.right + dx * dyN * n1 * n2
Seq(newN, newXAvg, newYAvg, newCk)
}
}
@ExpressionDescription(
usage = "_FUNC_(expr1, expr2) - Returns the population covariance of a set of number pairs.")
case class CovPopulation(left: Expression, right: Expression) extends Covariance(left, right) {
override val evaluateExpression: Expression = {
If(n === Literal(0.0), Literal.create(null, DoubleType),
ck / n)
}
override def prettyName: String = "covar_pop"
}
@ExpressionDescription(
usage = "_FUNC_(expr1, expr2) - Returns the sample covariance of a set of number pairs.")
case class CovSample(left: Expression, right: Expression) extends Covariance(left, right) {
override val evaluateExpression: Expression = {
If(n === Literal(0.0), Literal.create(null, DoubleType),
If(n === Literal(1.0), Literal(Double.NaN),
ck / (n - Literal(1.0))))
}
override def prettyName: String = "covar_samp"
}
| {
"content_hash": "d428977fdab1115018a44984d14a4ebc",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 95,
"avg_line_length": 35.77647058823529,
"alnum_prop": 0.6586649128576126,
"repo_name": "wangyixiaohuihui/spark2-annotation",
"id": "9bcd6281cedebd120056ebac313b29ab8f315553",
"size": "3856",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Covariance.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "33815"
},
{
"name": "Batchfile",
"bytes": "24294"
},
{
"name": "C",
"bytes": "1542"
},
{
"name": "CSS",
"bytes": "23957"
},
{
"name": "HTML",
"bytes": "10012"
},
{
"name": "HiveQL",
"bytes": "1828674"
},
{
"name": "Java",
"bytes": "3737029"
},
{
"name": "JavaScript",
"bytes": "143063"
},
{
"name": "Makefile",
"bytes": "7980"
},
{
"name": "PLpgSQL",
"bytes": "9666"
},
{
"name": "PowerShell",
"bytes": "3751"
},
{
"name": "Python",
"bytes": "2248750"
},
{
"name": "R",
"bytes": "1027534"
},
{
"name": "Roff",
"bytes": "14420"
},
{
"name": "SQLPL",
"bytes": "3603"
},
{
"name": "Scala",
"bytes": "22897473"
},
{
"name": "Shell",
"bytes": "156941"
},
{
"name": "Thrift",
"bytes": "33665"
},
{
"name": "q",
"bytes": "147332"
}
],
"symlink_target": ""
} |
/* imalloc.h -- internal malloc definitions shared by source files. */
/* Copyright (C) 2001 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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 2, or (at your option) any later
version.
Bash 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 Bash; see the file COPYING. If not, write to the Free Software
Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
/* Must be included *after* config.h */
#ifndef _IMALLOC_H_
#define _IMALLOC_H
#ifdef MALLOC_DEBUG
#define MALLOC_STATS
#define MALLOC_TRACE
#define MALLOC_REGISTER
#endif
/* Generic pointer type. */
#ifndef PTR_T
# if defined (__STDC__)
# define PTR_T void *
# else
# define PTR_T char *
# endif
#endif
#if !defined (NULL)
# define NULL 0
#endif
#if !defined (__STRING)
# if defined (HAVE_STRINGIZE)
# define __STRING(x) #x
# else
# define __STRING(x) "x"
# endif /* !HAVE_STRINGIZE */
#endif /* !__STRING */
#if __GNUC__ > 1
# define FASTCOPY(s, d, n) __builtin_memcpy (d, s, n)
#else /* !__GNUC__ */
# if !defined (HAVE_BCOPY)
# if !defined (HAVE_MEMMOVE)
# define FASTCOPY(s, d, n) memcpy (d, s, n)
# else
# define FASTCOPY(s, d, n) memmove (d, s, n)
# endif /* !HAVE_MEMMOVE */
# else /* HAVE_BCOPY */
# define FASTCOPY(s, d, n) bcopy (s, d, n)
# endif /* HAVE_BCOPY */
#endif /* !__GNUC__ */
#endif
| {
"content_hash": "b82d8440a9849d38606937b73112d97c",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 74,
"avg_line_length": 27.328358208955223,
"alnum_prop": 0.6619333697433096,
"repo_name": "easion/os_sdk",
"id": "ef0886814c5a17470b355f64884c2e28422a7453",
"size": "1831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bash-2.05/lib/malloc/imalloc.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "980392"
},
{
"name": "Awk",
"bytes": "1743"
},
{
"name": "Bison",
"bytes": "113274"
},
{
"name": "C",
"bytes": "60384056"
},
{
"name": "C++",
"bytes": "6888586"
},
{
"name": "CSS",
"bytes": "3092"
},
{
"name": "Component Pascal",
"bytes": "295471"
},
{
"name": "D",
"bytes": "275403"
},
{
"name": "Erlang",
"bytes": "130334"
},
{
"name": "Groovy",
"bytes": "15362"
},
{
"name": "JavaScript",
"bytes": "437486"
},
{
"name": "Logos",
"bytes": "6575"
},
{
"name": "Makefile",
"bytes": "145054"
},
{
"name": "Max",
"bytes": "4350"
},
{
"name": "Nu",
"bytes": "1315315"
},
{
"name": "Objective-C",
"bytes": "209666"
},
{
"name": "PHP",
"bytes": "246706"
},
{
"name": "Perl",
"bytes": "1767429"
},
{
"name": "Prolog",
"bytes": "1387207"
},
{
"name": "Python",
"bytes": "14909"
},
{
"name": "R",
"bytes": "46561"
},
{
"name": "Ruby",
"bytes": "290155"
},
{
"name": "Scala",
"bytes": "184297"
},
{
"name": "Shell",
"bytes": "5748626"
},
{
"name": "TeX",
"bytes": "346362"
},
{
"name": "XC",
"bytes": "6266"
}
],
"symlink_target": ""
} |
FROM balenalib/artik10-alpine:3.12-build
ENV NODE_VERSION 17.6.0
ENV YARN_VERSION 1.22.4
# Install dependencies
RUN apk add --no-cache libgcc libstdc++ libuv \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \
&& echo "2af933c590e00bedee53c57e3956c273cfdcbb233dcdb3ec355f9e3a1f2e65c6 node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-alpine-armv7hf.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/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
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 v7 \nOS: Alpine Linux 3.12 \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/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 | {
"content_hash": "52fd6ccb3c292694b1888b45238a8cab",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 698,
"avg_line_length": 65,
"alnum_prop": 0.7111111111111111,
"repo_name": "resin-io-library/base-images",
"id": "9e450a276967c01b0a5e3920b886e52f2a0bc6b1",
"size": "2946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/artik10/alpine/3.12/17.6.0/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
package dev.jinkim.snappollandroid.ui.widget.slidingtab;
import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
class SlidingTabStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 4;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFFFFFF;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
final int themeForegroundColor = outValue.data;
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
void setSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
void onViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {@code color} to be the given {@code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {@code color1} and {@code color2} using the given ratio.
*
* @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
* 0.0 will return {@code color2}.
*/
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
private int[] mIndicatorColors;
@Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
} | {
"content_hash": "3ef932420c2d80cb1340dd7cb7ac3ebb",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 100,
"avg_line_length": 37.74025974025974,
"alnum_prop": 0.6672401927047488,
"repo_name": "jinkim608/SnapPoll",
"id": "23f2272b5b9681ea21faba29bff883faf66fa8b9",
"size": "6428",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SnapPollAndroidClient/app/src/main/java/dev/jinkim/snappollandroid/ui/widget/slidingtab/SlidingTabStrip.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1768138"
}
],
"symlink_target": ""
} |
module StringHelpers
# Convert a string to ASCII hex string
# (Adapted from the Ruby Black Bag [http://github.com/emonti/rbkb/])
def hexify()
out=Array.new
hexchars = [("0".."9").to_a, ("a".."f").to_a].flatten
self.each_byte do |c|
hc = (hexchars[(c >> 4)] + hexchars[(c & 0xf )])
out << (hc)
end
out.join("")
end
# Convert ASCII hex string to raw.
# (Adapted from the Ruby Black Bag [http://github.com/emonti/rbkb/])
# @param [Regex] d (Optional) 'delimiter' between hex bytes (zero+ spaces by default)
def unhexify(d=/\s*/)
self.strip.gsub(/([A-Fa-f0-9]{1,2})#{d}?/) { $1.hex.chr }
end
def base64_decode
return self.unpack("m").first
end
# Makes the string a given length by trimming excess bytes from the endi, or
# padding with the given padding byte.
# @param [Integer] final_length
# @pad_byte [String] pad_byte (Optional) A single-byte string (default is 0x36)
def pad_or_trim!( final_length, pad_byte="\x36" )
self.slice!(final_length..-1)
self << pad_byte * (final_length - self.length)
return self
end
end
class String
include StringHelpers
end
| {
"content_hash": "2529593476c0e5e85783cb0178af59d9",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 87,
"avg_line_length": 28.725,
"alnum_prop": 0.6344647519582245,
"repo_name": "woodbusy/ooxml_decrypt",
"id": "60873dd6fb692f6d20b338dc1a0b5ba7c44ef9f2",
"size": "1149",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/ooxml_decrypt/string_helpers.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "15206"
}
],
"symlink_target": ""
} |
package com.maddyhome.idea.copyright.language.psi;
import com.intellij.lang.Language;
import com.intellij.psi.tree.IElementType;
import com.maddyhome.idea.copyright.language.SimpleLanguage;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Created by mike on 9/6/15.
*/
public class SimpleTokenType extends IElementType {
public SimpleTokenType(@NotNull @NonNls String debugName) {
super(debugName, SimpleLanguage.INSTANCE);
}
@Override
public String toString() {
return "SimpleTokenType." + super.toString();
}
}
| {
"content_hash": "f71a174f79da9f17225b80ef43e66d4c",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 61,
"avg_line_length": 25.875,
"alnum_prop": 0.7729468599033816,
"repo_name": "mikedamay/trinkets",
"id": "36d3e4f63b151ac424d271e30aa0d9c6e3386c12",
"size": "1221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "copyright/src/com/maddyhome/idea/copyright/language/psi/SimpleTokenType.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "567"
},
{
"name": "C#",
"bytes": "126745"
},
{
"name": "CSS",
"bytes": "18494"
},
{
"name": "Elm",
"bytes": "35071"
},
{
"name": "HTML",
"bytes": "578927"
},
{
"name": "Java",
"bytes": "427921"
},
{
"name": "JavaScript",
"bytes": "523622"
},
{
"name": "Lex",
"bytes": "16172"
},
{
"name": "Shell",
"bytes": "989"
},
{
"name": "XSLT",
"bytes": "17904"
}
],
"symlink_target": ""
} |
package org.opensaml.xml.security.credential;
import java.util.Map;
import org.opensaml.xml.security.CriteriaSet;
//TODO amend docs (and impl) for symmetric key storage and retrieval
/**
* A {@link CredentialResolver} that pulls credential information from the file system.
*
* This credential resolver attempts to retrieve credential information from the file system. Specifically it will
* attempt to find key, cert, and crl information from files within the given directory. The filename must start with
* the entity ID and be followed by one of the follow extensions:
*
* <ul>
* <li>.name - for key names. File must contain a carriage return seperated list of key names</li>
* <li>.priv - for private key. File must contain one PEM or DER encoded private key</li>
* <li>.pub - for public keys. File must contain one or more PEM or DER encoded private key</li>
* <li>.crt - for public certificates. File must contain one or more PEM or DER encoded X.509 certificates</li>
* <li>.crl - for certificate revocation lists. File must contain one or more CRLs</li>
* </ul>
*/
public class FilesystemCredentialResolver extends AbstractCriteriaFilteringCredentialResolver {
/**
* Constructor.
*
* @param credentialDirectory directory credential information can be found in
* @param passwords passwords for encrypted private keys, key is the entity ID, value is the password
*/
public FilesystemCredentialResolver(String credentialDirectory, Map<String, String> passwords) {
super();
// TODO
}
/** {@inheritDoc} */
protected Iterable<Credential> resolveFromSource(CriteriaSet criteriaSet) {
// TODO Auto-generated method stub
return null;
}
} | {
"content_hash": "05d522214c8ca771296430e40b3596da",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 117,
"avg_line_length": 38.733333333333334,
"alnum_prop": 0.7257601835915088,
"repo_name": "duck1123/java-xmltooling",
"id": "935e9698cf5eba6bbc5d9faaa0231812ebea7d05",
"size": "2388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/opensaml/xml/security/credential/FilesystemCredentialResolver.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2401232"
}
],
"symlink_target": ""
} |
'use strict';
require('./api_extractor.es6.js');
const ObjectGraph = require('object-graph-js').BrowserObjectGraph;
foam.CLASS({
package: 'org.chromium.apis.web',
name: 'ApiExtractorService',
imports: [
'container',
'info',
],
properties: [
// TODO(markdittmer): This should be unnecessary. Limitations imposed during
// deserialization should not persist after deserialized components are
// instantiated.
{
name: 'localCtx',
documentation: `Local context that escapes any whitelisted deserialization
context service may have been created in.`,
transient: true,
factory: function() {
return this.container.ctx || this.container;
},
},
{
name: 'fs',
transient: true,
factory: function() {
return require('fs');
},
},
{
name: 'path',
transient: true,
factory: function() {
return require('path');
},
},
],
methods: [
{
name: 'extractWebCatalog',
returns: 'Promise',
code: function(objectGraphFilePath) {
try {
const ApiExtractor =
this.localCtx.lookup('org.chromium.apis.web.ApiExtractor');
this.info(`Loading ${objectGraphFilePath}`);
let graphJSON;
try {
graphJSON = JSON.parse(this.fs.readFileSync(
objectGraphFilePath));
} catch (error) {
return Promise.reject(error);
}
let releaseInfo;
try {
releaseInfo = this.getReleaseInfo(objectGraphFilePath, graphJSON);
} catch (error) {
return Promise.reject(error);
}
const apiExtractor = ApiExtractor.create({
objectGraph: ObjectGraph.fromJSON(graphJSON),
});
this.info(`Extracting web catalog for ${objectGraphFilePath}`);
const catalog = apiExtractor.extractWebCatalog();
this.info(`Web catalog extracted for ${objectGraphFilePath}`);
return Promise.resolve({
releaseInfo,
catalog,
});
} catch (error) {
return Promise.reject(error);
}
},
},
function getReleaseInfo(path, json) {
if (json.environment && json.environment.browser &&
json.environment.browser.name && json.environment.browser.version &&
json.environment.platform && json.environment.platform.name &&
json.environment.platform.version) {
return json.environment;
} else {
return this.getReleaseInfoFromPath_(path);
}
},
function getReleaseInfoFromPath_(path) {
const filename = this.path.basename(path);
const ret = {browser: {}, platform: {}};
// Drop slice(0, -5): ".json".
if (!filename.endsWith('.json')) {
throw new Error('Object graph JSON file must end with ".json"');
}
const releaseInfo = filename.slice(0, -5).split('_');
if (releaseInfo.length !== 5) {
throw new Error('Object graph JSON file name expected to be of the form ' +
'window_[browser-name]_[browser-version]_[platform-name][platform-version].json');
}
ret.browser.name = releaseInfo[1];
ret.browser.version = releaseInfo[2];
ret.platform.name = releaseInfo[3];
ret.platform.version = releaseInfo[4];
return ret;
},
],
});
| {
"content_hash": "9d0bbcccc1178d64590864cb97b6cd1e",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 106,
"avg_line_length": 29.637931034482758,
"alnum_prop": 0.5796974985456661,
"repo_name": "GoogleChromeLabs/confluence",
"id": "5d6cf73a59eafae1be97c40bb6b4b9c3f8a6f092",
"size": "3603",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/web_catalog/api_extractor_service.es6.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "22235"
},
{
"name": "JavaScript",
"bytes": "445323"
},
{
"name": "Shell",
"bytes": "4995"
}
],
"symlink_target": ""
} |
<!-- #docregion -->
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>Angular Tour of Heroes</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfills for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
| {
"content_hash": "65a9cba773553dea2155c0d7f94ac1df",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 72,
"avg_line_length": 26.692307692307693,
"alnum_prop": 0.622478386167147,
"repo_name": "Urigo/angular.io",
"id": "c32df50c6f73af0600ef3892fb1c0acefd51b3a7",
"size": "694",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/docs/_examples/toh-6/ts/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "130282"
},
{
"name": "Dart",
"bytes": "3505"
},
{
"name": "HTML",
"bytes": "1630329"
},
{
"name": "JavaScript",
"bytes": "184345"
},
{
"name": "Shell",
"bytes": "6663"
},
{
"name": "TypeScript",
"bytes": "767162"
}
],
"symlink_target": ""
} |
package integration
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"sort"
"strings"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
knet "k8s.io/apimachinery/pkg/util/net"
kapi "k8s.io/kubernetes/pkg/api"
build "github.com/openshift/origin/pkg/build/api"
buildv1 "github.com/openshift/origin/pkg/build/api/v1"
testutil "github.com/openshift/origin/test/util"
testserver "github.com/openshift/origin/test/util/server"
)
// expectedIndex contains the routes expected at the api root /. Keep them sorted.
var expectedIndex = []string{
"/api",
"/api/v1",
"/apis",
"/apis/apps",
"/apis/apps.openshift.io",
"/apis/apps.openshift.io/v1",
"/apis/apps/v1beta1",
"/apis/authentication.k8s.io",
"/apis/authentication.k8s.io/v1",
"/apis/authentication.k8s.io/v1beta1",
"/apis/authorization.k8s.io",
"/apis/authorization.k8s.io/v1",
"/apis/authorization.k8s.io/v1beta1",
"/apis/authorization.openshift.io",
"/apis/authorization.openshift.io/v1",
"/apis/autoscaling",
"/apis/autoscaling/v1",
"/apis/autoscaling/v2alpha1",
"/apis/batch",
"/apis/batch/v1",
"/apis/batch/v2alpha1",
"/apis/build.openshift.io",
"/apis/build.openshift.io/v1",
"/apis/certificates.k8s.io",
"/apis/certificates.k8s.io/v1beta1",
"/apis/extensions",
"/apis/extensions/v1beta1",
"/apis/image.openshift.io",
"/apis/image.openshift.io/v1",
"/apis/network.openshift.io",
"/apis/network.openshift.io/v1",
"/apis/oauth.openshift.io",
"/apis/oauth.openshift.io/v1",
"/apis/policy",
"/apis/policy/v1beta1",
"/apis/project.openshift.io",
"/apis/project.openshift.io/v1",
"/apis/quota.openshift.io",
"/apis/quota.openshift.io/v1",
"/apis/rbac.authorization.k8s.io",
"/apis/rbac.authorization.k8s.io/v1beta1",
"/apis/route.openshift.io",
"/apis/route.openshift.io/v1",
"/apis/security.openshift.io",
"/apis/security.openshift.io/v1",
"/apis/settings.k8s.io",
"/apis/settings.k8s.io/v1alpha1",
"/apis/storage.k8s.io",
"/apis/storage.k8s.io/v1",
"/apis/storage.k8s.io/v1beta1",
"/apis/template.openshift.io",
"/apis/template.openshift.io/v1",
"/apis/user.openshift.io",
"/apis/user.openshift.io/v1",
"/controllers",
"/healthz",
"/healthz/ping",
"/healthz/poststarthook/bootstrap-controller",
"/healthz/poststarthook/ca-registration",
"/healthz/poststarthook/extensions/third-party-resources",
"/healthz/ready",
"/metrics",
"/oapi",
"/oapi/v1",
"/osapi",
"/swaggerapi/",
"/version",
"/version/openshift",
}
func TestRootRedirect(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterConfig, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
transport, err := anonymousHttpTransport(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
req, err := http.NewRequest("GET", masterConfig.AssetConfig.MasterPublicURL, nil)
req.Header.Set("Accept", "*/*")
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Expected %d, got %d", http.StatusOK, resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "application/json" {
t.Fatalf("Expected %s, got %s", "application/json", resp.Header.Get("Content-Type"))
}
type result struct {
Paths []string
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error reading the body: %v", err)
}
var got result
json.Unmarshal(body, &got)
sort.Strings(got.Paths)
if !reflect.DeepEqual(got.Paths, expectedIndex) {
t.Fatalf("Unexpected index: \ngot=%v,\n\n expected=%v", got, expectedIndex)
}
req, err = http.NewRequest("GET", masterConfig.AssetConfig.MasterPublicURL, nil)
req.Header.Set("Accept", "text/html")
resp, err = transport.RoundTrip(req)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if resp.StatusCode != http.StatusFound {
t.Errorf("Expected %d, got %d", http.StatusFound, resp.StatusCode)
}
if resp.Header.Get("Location") != masterConfig.AssetConfig.PublicURL {
t.Errorf("Expected %s, got %s", masterConfig.AssetConfig.PublicURL, resp.Header.Get("Location"))
}
// TODO add a test for when asset config is nil, the redirect should not occur in this case even when
// accept header contains text/html
}
func TestWellKnownOAuth(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterConfig, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
transport, err := anonymousHttpTransport(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
req, err := http.NewRequest("GET", masterConfig.AssetConfig.MasterPublicURL+"/.well-known/oauth-authorization-server", nil)
req.Header.Set("Accept", "*/*")
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Expected %d, got %d", http.StatusOK, resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error reading the body: %v", err)
}
if !strings.Contains(string(body), "authorization_endpoint") {
t.Fatal("Expected \"authorization_endpoint\" in the body.")
}
}
func TestWellKnownOAuthOff(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterConfig, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterConfig.OAuthConfig = nil
clusterAdminKubeConfig, err := testserver.StartConfiguredMasterAPI(masterConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
transport, err := anonymousHttpTransport(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
req, err := http.NewRequest("GET", masterConfig.AssetConfig.MasterPublicURL+"/.well-known/oauth-authorization-server", nil)
req.Header.Set("Accept", "*/*")
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("Expected %d, got %d", http.StatusNotFound, resp.StatusCode)
}
}
func TestApiGroups(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterConfig, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterConfig.OAuthConfig = nil
clusterAdminKubeConfig, err := testserver.StartConfiguredMasterAPI(masterConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
kclientset, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
t.Logf("Looking for build api group in server group discovery")
groups, err := kclientset.Discovery().ServerGroups()
if err != nil {
t.Fatalf("unexpected group discovery error: %v", err)
}
found := false
for _, g := range groups.Groups {
if g.Name == buildv1.GroupName {
found = true
}
}
if !found {
t.Errorf("Expected to find api group %q in discovery, got: %+v", buildv1.GroupName, groups)
}
t.Logf("Looking for builds resource in resource discovery")
resources, err := kclientset.Discovery().ServerResourcesForGroupVersion(buildv1.SchemeGroupVersion.String())
if err != nil {
t.Fatalf("unexpected resource discovery error: %v", err)
}
found = false
got := []string{}
for _, r := range resources.APIResources {
got = append(got, r.Name)
}
sort.Strings(got)
expected := []string{
"buildconfigs",
"buildconfigs/instantiate",
"buildconfigs/instantiatebinary",
"buildconfigs/webhooks",
"builds",
"builds/clone",
"builds/details",
"builds/log",
}
if !reflect.DeepEqual(expected, got) {
t.Errorf("Expected different build resources: got=%v, expect=%v", got, expected)
}
ns := testutil.RandomNamespace("testapigroup")
t.Logf("Creating test namespace %q", ns)
err = testutil.CreateNamespace(clusterAdminKubeConfig, ns)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer kclientset.Core().Namespaces().Delete(ns, &metav1.DeleteOptions{})
t.Logf("GETting builds")
req, err := http.NewRequest("GET", masterConfig.AssetConfig.MasterPublicURL+fmt.Sprintf("/apis/%s/%s", buildv1.GroupName, buildv1.SchemeGroupVersion.Version), nil)
req.Header.Set("Accept", "*/*")
resp, err := client.Client.Transport.RoundTrip(req)
if err != nil {
t.Fatalf("Unexpected GET error: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Expected %d, got %d", http.StatusOK, resp.StatusCode)
}
t.Logf("Creating a Build")
originalBuild := testBuild()
_, err = client.Builds(ns).Create(originalBuild)
if err != nil {
t.Fatalf("Unexpected BuildConfig create error: %v", err)
}
t.Logf("GETting builds again")
req, err = http.NewRequest("GET", masterConfig.AssetConfig.MasterPublicURL+fmt.Sprintf("/apis/%s/%s/namespaces/%s/builds/%s", buildv1.GroupName, buildv1.SchemeGroupVersion.Version, ns, originalBuild.Name), nil)
req.Header.Set("Accept", "*/*")
resp, err = client.Client.Transport.RoundTrip(req)
if err != nil {
t.Fatalf("Unexpected GET error: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Expected %d, got %d", http.StatusOK, resp.StatusCode)
}
body, _ := ioutil.ReadAll(resp.Body)
codec := kapi.Codecs.LegacyCodec(buildv1.SchemeGroupVersion)
respBuild := &buildv1.Build{}
gvk := buildv1.SchemeGroupVersion.WithKind("Build")
respObj, _, err := codec.Decode(body, &gvk, respBuild)
if err != nil {
t.Fatalf("Unexpected conversion error, body=%q: %v", string(body), err)
}
respBuild, ok := respObj.(*buildv1.Build)
if !ok {
t.Fatalf("Unexpected type %T, expected buildv1.Build", respObj)
}
if got, expected := respBuild.APIVersion, buildv1.SchemeGroupVersion.String(); got != expected {
t.Fatalf("Unexpected APIVersion: got=%q, expected=%q", got, expected)
}
if got, expected := respBuild.Name, originalBuild.Name; got != expected {
t.Fatalf("Unexpected name: got=%q, expected=%q", got, expected)
}
}
func anonymousHttpTransport(clusterAdminKubeConfig string) (*http.Transport, error) {
restConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
if ok := pool.AppendCertsFromPEM(restConfig.TLSClientConfig.CAData); !ok {
return nil, errors.New("failed to add server CA certificates to client pool")
}
return knet.SetTransportDefaults(&http.Transport{
TLSClientConfig: &tls.Config{
// only use RootCAs from client config, especially no client certs
RootCAs: pool,
},
}), nil
}
func testBuild() *build.Build {
return &build.Build{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: build.BuildSpec{
CommonSpec: build.CommonSpec{
Source: build.BuildSource{
Git: &build.GitBuildSource{
URI: "git://github.com/openshift/ruby-hello-world.git",
},
ContextDir: "contextimage",
},
Strategy: build.BuildStrategy{
DockerStrategy: &build.DockerBuildStrategy{},
},
Output: build.BuildOutput{
To: &kapi.ObjectReference{
Kind: "ImageStreamTag",
Name: "test-image-trigger-repo:outputtag",
},
},
},
},
}
}
| {
"content_hash": "f481f4306abc9ff5b46718d91af47e0f",
"timestamp": "",
"source": "github",
"line_count": 374,
"max_line_length": 211,
"avg_line_length": 30.505347593582886,
"alnum_prop": 0.7022526075904987,
"repo_name": "chlunde/origin",
"id": "3a330b194ff27d76d3d8503055534d9494110d25",
"size": "11409",
"binary": false,
"copies": "1",
"ref": "refs/heads/pod-drain-v2",
"path": "test/integration/master_routes_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "16754516"
},
{
"name": "Makefile",
"bytes": "7930"
},
{
"name": "Protocol Buffer",
"bytes": "629926"
},
{
"name": "Python",
"bytes": "7821"
},
{
"name": "Roff",
"bytes": "2049"
},
{
"name": "Ruby",
"bytes": "484"
},
{
"name": "Shell",
"bytes": "1551023"
}
],
"symlink_target": ""
} |
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet.h"
#include <QFont>
#include <QColor>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry
{
enum Type {
Sending,
Receiving
};
Type type;
QString label;
QString address;
QString dividendAddress;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString &label, const QString &address, const QString ÷ndAddress = ""):
type(type), label(label), address(address), dividendAddress(dividendAddress) {}
};
// Private implementation
class AddressTablePriv
{
public:
CWallet *wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTablePriv(CWallet *wallet):
wallet(wallet) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, std::string)& item, wallet->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const std::string& strName = item.second;
bool fMine = wallet->HaveKey(address);
const CPeercoinAddress& dividendAddress(address);
cachedAddressTable.append(AddressTableEntry(fMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending,
QString::fromStdString(strName),
QString::fromStdString(address.ToString()),
QString::fromStdString(dividendAddress.ToString())));
}
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedAddressTable.size())
{
return &cachedAddressTable[idx];
}
else
{
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) :
QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0)
{
columns << tr("Label") << tr("Address")/* << tr("Dividend address")*/;
priv = new AddressTablePriv(wallet);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Label:
if(rec->label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->label;
}
case Address:
return rec->address;
case DividendAddress:
return rec->dividendAddress;
}
}
else if (role == Qt::FontRole)
{
QFont font;
if(index.column() == Address or index.column() == DividendAddress)
{
font = GUIUtil::bitcoinAddressFont();
}
return font;
}
else if (role == TypeRole)
{
switch(rec->type)
{
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default: break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if(!index.isValid())
return false;
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
editStatus = OK;
if(role == Qt::EditRole)
{
switch(index.column())
{
case Label:
wallet->SetAddressBookName(rec->address.toStdString(), value.toString().toStdString());
rec->label = value.toString();
break;
case Address:
// Refuse to set invalid address, set error status and return false
if(!walletModel->validateAddress(value.toString()))
{
editStatus = INVALID_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
if(rec->type == AddressTableEntry::Sending)
{
{
LOCK(wallet->cs_wallet);
// Remove old entry
wallet->DelAddressBookName(rec->address.toStdString());
// Add new entry with new address
wallet->SetAddressBookName(value.toString().toStdString(), rec->label.toStdString());
}
rec->address = value.toString();
}
break;
case DividendAddress:
// Refuse to change dividend address
editStatus = INVALID_ADDRESS;
return false;
}
emit dataChanged(index, index);
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole)
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex & index) const
{
if(!index.isValid())
return 0;
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if(rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column()==Label))
{
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex & parent) const
{
Q_UNUSED(parent);
AddressTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void AddressTableModel::update()
{
// Update address book model from Bitcoin core
beginResetModel();
priv->refreshAddressTable();
endResetModel();
}
QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if(type == Send)
{
if(!walletModel->validateAddress(address))
{
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if(wallet->mapAddressBook.count(strAddress))
{
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
}
else if(type == Receive)
{
// Generate a new address to associate with given label
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
std::vector<unsigned char> newKey;
if(!wallet->GetKeyFromPool(newKey, true))
{
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
strAddress = CBitcoinAddress(newKey).ToString();
}
else
{
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBookName(strAddress, strLabel);
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex & parent)
{
Q_UNUSED(parent);
AddressTableEntry *rec = priv->index(row);
if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving)
{
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBookName(rec->address.toStdString());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CBitcoinAddress, std::string>::iterator mi = wallet->mapAddressBook.find(address_parsed);
if (mi != wallet->mapAddressBook.end())
{
return QString::fromStdString(mi->second);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString &address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if(lst.isEmpty())
{
return -1;
}
else
{
return lst.at(0).row();
}
}
| {
"content_hash": "0bacae1fde641a6080c06eedb8ed6ea0",
"timestamp": "",
"source": "github",
"line_count": 352,
"max_line_length": 126,
"avg_line_length": 27.261363636363637,
"alnum_prop": 0.5845143809920801,
"repo_name": "ybchain/ybcoin",
"id": "d2f9743426c5955f8f462ede38125e700e1abd7e",
"size": "9596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/addresstablemodel.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5841"
},
{
"name": "C++",
"bytes": "1656090"
},
{
"name": "Groff",
"bytes": "12841"
},
{
"name": "Makefile",
"bytes": "4489"
},
{
"name": "NSIS",
"bytes": "6180"
},
{
"name": "Objective-C",
"bytes": "754"
},
{
"name": "Objective-C++",
"bytes": "4791"
},
{
"name": "Python",
"bytes": "50536"
},
{
"name": "QMake",
"bytes": "39102"
},
{
"name": "Shell",
"bytes": "1983"
}
],
"symlink_target": ""
} |
package controle.modelos;
import java.math.BigDecimal;
import java.util.Date;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Property;
import org.mongodb.morphia.annotations.Reference;
@Entity("ajusteMateriaPrima")
public class AjusteEstoqueMateriaPrima {
@Id
private ObjectId codigo;
@Reference(lazy=false)
private MateriaPrima materiaPrima;
@Property("quantidade")
private BigDecimal quantidade;
private Date dataHora;
private boolean entrada;
public ObjectId getCodigo() {
return codigo;
}
public void setCodigo(ObjectId codigo) {
this.codigo = codigo;
}
public MateriaPrima getMateriaPrima() {
return materiaPrima;
}
public void setMateriaPrima(MateriaPrima materiaPrima) {
this.materiaPrima = materiaPrima;
}
public BigDecimal getQuantidade() {
return quantidade;
}
public void setQuantidade(BigDecimal quantidade) {
this.quantidade = quantidade;
}
public Date getDataHora() {
return dataHora;
}
public void setDataHora(Date dataHora) {
this.dataHora = dataHora;
}
public boolean isEntrada() {
return entrada;
}
public void setEntrada(boolean entrada) {
this.entrada = entrada;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
result = prime * result + ((dataHora == null) ? 0 : dataHora.hashCode());
result = prime * result + (entrada ? 1231 : 1237);
result = prime * result + ((materiaPrima == null) ? 0 : materiaPrima.hashCode());
result = prime * result + ((quantidade == null) ? 0 : quantidade.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AjusteEstoqueMateriaPrima other = (AjusteEstoqueMateriaPrima) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
if (dataHora == null) {
if (other.dataHora != null)
return false;
} else if (!dataHora.equals(other.dataHora))
return false;
if (entrada != other.entrada)
return false;
if (materiaPrima == null) {
if (other.materiaPrima != null)
return false;
} else if (!materiaPrima.equals(other.materiaPrima))
return false;
if (quantidade == null) {
if (other.quantidade != null)
return false;
} else if (!quantidade.equals(other.quantidade))
return false;
return true;
}
@Override
public String toString() {
return "AjusteEstoqueMateriaPrima [codigo=" + codigo + ", materiaPrima=" + materiaPrima + ", quantidade=" + quantidade + ", dataHora=" + dataHora + ", entrada=" + entrada + "]";
}
}
| {
"content_hash": "adab66d3881d0b3969f20fb8dc3687a5",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 179,
"avg_line_length": 24.842105263157894,
"alnum_prop": 0.696680790960452,
"repo_name": "jpsacheti/manufatura-controle",
"id": "c64bd300e4b1e71835ae8de80b3c59cd9fccb5ed",
"size": "2832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/controle/modelos/AjusteEstoqueMateriaPrima.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "95614"
}
],
"symlink_target": ""
} |
#ifndef LATENCY_H
#define LATENCY_H
/*
Hanoh Haim
Ido Barnea
Cisco Systems, Inc.
*/
/*
Copyright (c) 2015-2015 Cisco Systems, 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.
*/
#include <bp_sim.h>
#define L_PKT_SUBMODE_NO_REPLY 1
#define L_PKT_SUBMODE_REPLY 2
#define L_PKT_SUBMODE_0_SEQ 3
class CLatencyPktInfo {
public:
void Create(class CLatencyPktMode *m_l_pkt_info);
void Delete();
void set_ip(uint32_t src,
uint32_t dst,
uint32_t dual_port_mask);
rte_mbuf_t * generate_pkt(int port_id,uint32_t extern_ip=0);
CGenNode * getNode(){
return (&m_dummy_node);
}
uint16_t get_payload_offset(void){
return ( m_pkt_indication.getFastPayloadOffset());
}
uint16_t get_l4_offset(void){
return ( m_pkt_indication.getFastTcpOffset());
}
uint16_t get_pkt_size(void){
return ( m_packet->pkt_len );
}
private:
ipaddr_t m_client_ip;
ipaddr_t m_server_ip;
uint32_t m_dual_port_mask;
CGenNode m_dummy_node;
CFlowPktInfo m_pkt_info;
CPacketIndication m_pkt_indication;
CCapPktRaw * m_packet;
};
#define LATENCY_MAGIC 0x12345600
struct latency_header {
uint64_t time_stamp;
uint32_t magic;
uint32_t seq;
uint8_t get_id(){
return( magic & 0xff);
}
};
class CSimplePacketParser {
public:
CSimplePacketParser(rte_mbuf_t * m){
m_m=m;
}
bool Parse();
uint8_t getTTl();
uint16_t getPktSize();
inline bool IsLatencyPkt(uint8_t *p) {
latency_header * h=(latency_header *)(p);
if ( (h->magic & 0xffffff00) != LATENCY_MAGIC ){
return (false);
}
return true;
}
public:
IPHeader * m_ipv4;
IPv6Header * m_ipv6;
uint8_t m_protocol;
uint16_t m_vlan_offset;
uint16_t m_option_offset;
uint8_t * m_l4;
private:
rte_mbuf_t * m_m ;
};
class CLatencyManager ;
// per port
class CCPortLatency {
public:
bool Create(CLatencyManager * parent,
uint8_t id,
uint16_t offset,
uint16_t l4_offset,
uint16_t pkt_size,
CCPortLatency * rx_port
);
void Delete();
void reset();
bool can_send_packet(int direction){
// in icmp_reply mode, can send response from server, only after we got the relevant request
// if we got request, we are sure to have NAT translation in place already.
if ((CGlobalInfo::m_options.m_l_pkt_mode == L_PKT_SUBMODE_REPLY) && (direction == 1)) {
if (m_icmp_tx_seq <= m_icmp_rx_seq)
return(true);
else
return(false);
}
if ( !CGlobalInfo::is_learn_mode() ) {
return(true);
}
return ( m_nat_can_send );
}
uint32_t external_nat_ip(){
return (m_nat_external_ip);
}
void update_packet(rte_mbuf_t * m, int port_id);
bool do_learn(uint32_t external_ip);
bool check_packet(rte_mbuf_t * m,
CRx_check_header * & rx_p);
bool check_rx_check(rte_mbuf_t * m);
bool dump_packet(rte_mbuf_t * m);
void DumpCounters(FILE *fd);
void dump_counters_json(std::string & json );
void DumpShort(FILE *fd);
void dump_json(std::string & json );
void dump_json_v2(std::string & json );
uint32_t get_jitter_usec(void){
return ((uint32_t)(m_jitter.get_jitter()*1000000.0));
}
static void DumpShortHeader(FILE *fd);
bool is_any_err(){
if ( (m_tx_pkt_ok == m_rx_port->m_pkt_ok ) &&
((m_unsup_prot+
m_no_magic+
m_no_id+
m_seq_error+
m_length_error+m_no_ipv4_option+m_tx_pkt_err)==0) ) {
return (false);
}
return (true);
}
uint16_t get_icmp_tx_seq() {return m_icmp_tx_seq;}
uint16_t get_icmp_rx_seq() {return m_icmp_rx_seq;}
private:
std::string get_field(std::string name,float f);
private:
CLatencyManager * m_parent;
CCPortLatency * m_rx_port; /* corespond rx port */
bool m_nat_learn;
bool m_nat_can_send;
uint32_t m_nat_external_ip;
uint32_t m_tx_seq;
uint32_t m_rx_seq;
uint8_t m_pad;
uint8_t m_id;
uint16_t m_payload_offset;
uint16_t m_l4_offset;
uint16_t m_pkt_size;
// following two variables are for the latency ICMP reply mode.
// if we want to pass through firewall, we want to send reply only after we got request with same seq num
// ICMP seq num of next packet we will transmit
uint16_t m_icmp_tx_seq;
// ICMP seq num of last request we got
uint16_t m_icmp_rx_seq;
uint16_t pad1[1];
public:
uint64_t m_tx_pkt_ok;
uint64_t m_tx_pkt_err;
uint64_t m_pkt_ok;
uint64_t m_unsup_prot;
uint64_t m_no_magic;
uint64_t m_no_id;
uint64_t m_seq_error;
uint64_t m_rx_check;
uint64_t m_no_ipv4_option;
uint64_t m_length_error;
CTimeHistogram m_hist; /* all window */
CJitter m_jitter;
};
class CPortLatencyHWBase {
public:
virtual int tx(rte_mbuf_t * m)=0;
virtual rte_mbuf_t * rx()=0;
virtual uint16_t rx_burst(struct rte_mbuf **rx_pkts,
uint16_t nb_pkts){
return(0);
}
};
class CLatencyManagerCfg {
public:
CLatencyManagerCfg (){
m_max_ports=0;
m_cps=0.0;
m_client_ip.v4=0x10000000;
m_server_ip.v4=0x20000000;
m_dual_port_mask=0x01000000;
}
uint32_t m_max_ports;
double m_cps;// CPS
CPortLatencyHWBase * m_ports[MAX_LATENCY_PORTS];
ipaddr_t m_client_ip;
ipaddr_t m_server_ip;
uint32_t m_dual_port_mask;
};
class CLatencyManagerPerPort {
public:
CCPortLatency m_port;
CPortLatencyHWBase * m_io;
uint32_t m_flag;
};
class CLatencyPktMode {
public:
uint8_t m_submode;
CLatencyPktMode(uint8_t submode) {m_submode = submode;}
virtual uint8_t getPacketLen() = 0;
virtual const uint8_t *getPacketData() = 0;
virtual void rcv_debug_print(uint8_t *pkt) = 0;
virtual void send_debug_print(uint8_t *pkt) = 0;
virtual void update_pkt(uint8_t *pkt, bool is_client_to_server, uint16_t l4_len, uint16_t *tx_seq) = 0;
virtual bool IsLatencyPkt(IPHeader *ip) = 0;
uint8_t l4_header_len() {return 8;}
virtual void update_recv(uint8_t *pkt, uint16_t *r_seq, uint16_t *t_seq) = 0;
virtual uint8_t getProtocol() = 0;
virtual ~CLatencyPktMode() {}
};
class CLatencyPktModeICMP: public CLatencyPktMode {
public:
CLatencyPktModeICMP(uint8_t submode) : CLatencyPktMode(submode) {}
uint8_t getPacketLen();
const uint8_t *getPacketData();
void rcv_debug_print(uint8_t *);
void send_debug_print(uint8_t *);
void update_pkt(uint8_t *pkt, bool is_client_to_server, uint16_t l4_len, uint16_t *tx_seq);
bool IsLatencyPkt(IPHeader *ip);
void update_recv(uint8_t *pkt, uint16_t *r_seq, uint16_t *t_seq);
uint8_t getProtocol() {return 0x1;}
};
class CLatencyPktModeSCTP: public CLatencyPktMode {
public:
CLatencyPktModeSCTP(uint8_t submode) : CLatencyPktMode(submode) {}
uint8_t getPacketLen();
const uint8_t *getPacketData();
void rcv_debug_print(uint8_t *);
void send_debug_print(uint8_t *);
void update_pkt(uint8_t *pkt, bool is_client_to_server, uint16_t l4_len, uint16_t *tx_seq);
bool IsLatencyPkt(IPHeader *ip);
void update_recv(uint8_t *pkt, uint16_t *r_seq, uint16_t *t_seq);
uint8_t getProtocol() {return 0x84;}
};
class CLatencyManager {
public:
bool Create(CLatencyManagerCfg * cfg);
void Delete();
void reset();
void start(int iter);
void stop();
bool is_active();
void set_ip(uint32_t client_ip,
uint32_t server_ip,
uint32_t mask_dual_port){
m_pkt_gen.set_ip(client_ip,server_ip,mask_dual_port);
}
void Dump(FILE *fd); // dump all
void DumpShort(FILE *fd); // dump short histogram of latency
void DumpRxCheck(FILE *fd); // dump all
void DumpShortRxCheck(FILE *fd); // dump short histogram of latency
void rx_check_dump_json(std::string & json);
uint16_t get_latency_header_offset(){
return ( m_pkt_gen.get_payload_offset() );
}
void update();
void dump_json(std::string & json ); // dump to json
void dump_json_v2(std::string & json );
void DumpRxCheckVerification(FILE *fd,uint64_t total_tx_rx_check);
void set_mask(uint32_t mask){
m_port_mask=mask;
}
double get_max_latency(void);
double get_avr_latency(void);
bool is_any_error();
uint64_t get_total_pkt();
uint64_t get_total_bytes();
CNatRxManager * get_nat_manager(){
return ( &m_nat_check_manager );
}
CLatencyPktMode *c_l_pkt_mode;
private:
void send_pkt_all_ports();
void try_rx();
void try_rx_queues();
void run_rx_queue_msgs(uint8_t thread_id,
CNodeRing * r);
void wait_for_rx_dump();
void handle_rx_pkt(CLatencyManagerPerPort * lp,
rte_mbuf_t * m);
/* messages handlers */
void handle_latency_pkt_msg(uint8_t thread_id,
CGenNodeLatencyPktInfo * msg);
pqueue_t m_p_queue; /* priorty queue */
bool m_is_active;
CLatencyPktInfo m_pkt_gen;
CLatencyManagerPerPort m_ports[MAX_LATENCY_PORTS];
uint64_t m_d_time; // calc tick betwen sending
double m_cps;
double m_delta_sec;
uint64_t m_start_time; // calc tick betwen sending
uint32_t m_port_mask;
uint32_t m_max_ports;
RxCheckManager m_rx_check_manager;
CNatRxManager m_nat_check_manager;
CCpuUtlDp m_cpu_dp_u;
CCpuUtlCp m_cpu_cp_u;
volatile bool m_do_stop ODP_ALIGNED_CACHE ;
};
#endif
| {
"content_hash": "0a5096b3acaa65ade2da1228a532edff",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 110,
"avg_line_length": 27.935233160621763,
"alnum_prop": 0.5851803765185941,
"repo_name": "dproc/trex_odp_porting_integration",
"id": "2351eee8b31df13ae0c0096bb78045d04583cecf",
"size": "10783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/latency.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9616073"
},
{
"name": "C++",
"bytes": "3147123"
},
{
"name": "CMake",
"bytes": "8882"
},
{
"name": "HTML",
"bytes": "4523"
},
{
"name": "JavaScript",
"bytes": "1234"
},
{
"name": "Makefile",
"bytes": "129776"
},
{
"name": "Python",
"bytes": "2740100"
},
{
"name": "Shell",
"bytes": "3026"
}
],
"symlink_target": ""
} |
package org.apache.calcite.test.concurrent;
import org.apache.calcite.jdbc.SqlTimeoutException;
import org.apache.calcite.util.Unsafe;
import org.apache.calcite.util.Util;
import org.slf4j.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ConcurrentTestCommandScript creates instances of
* {@link ConcurrentTestCommand} that perform specific actions in a specific
* order and within the context of a test thread
* ({@link ConcurrentTestCommandExecutor}).
*
* <p>Actions are loaded from a script (see package javadoc for script format).
*
* <p>A single ConcurrentTestCommandScript creates commands
* for multiple threads. Each thread is represented by an integer "thread ID"
* and, optionally, a String thread name. Thread IDs may take on any positive
* integer value and may be a sparse set (e.g. 1, 2, 5). Thread names may be any
* String.
*
* <p>When each command is created, it is associated with a thread and given an
* execution order. Execution order values are positive integers, must be unique
* within a thread, and may be a sparse set.
* See {@link ConcurrentTestCommandGenerator#synchronizeCommandSets} for other
* considerations.
*/
public class ConcurrentTestCommandScript
extends ConcurrentTestCommandGenerator {
private static final String PRE_SETUP_STATE = "pre-setup";
private static final String SETUP_STATE = "setup";
private static final String POST_SETUP_STATE = "post-setup";
private static final String CLEANUP_STATE = "cleanup";
private static final String POST_CLEANUP_STATE = "post-cleanup";
private static final String THREAD_STATE = "thread";
private static final String REPEAT_STATE = "repeat";
private static final String SQL_STATE = "sql";
private static final String POST_THREAD_STATE = "post-thread";
private static final String EOF_STATE = "eof";
private static final String VAR = "@var";
private static final String LOCKSTEP = "@lockstep";
private static final String NOLOCKSTEP = "@nolockstep";
private static final String ENABLED = "@enabled";
private static final String DISABLED = "@disabled";
private static final String SETUP = "@setup";
private static final String CLEANUP = "@cleanup";
private static final String END = "@end";
private static final String THREAD = "@thread";
private static final String REPEAT = "@repeat";
private static final String SYNC = "@sync";
private static final String TIMEOUT = "@timeout";
private static final String ROWLIMIT = "@rowlimit";
private static final String PREPARE = "@prepare";
private static final String PRINT = "@print";
private static final String FETCH = "@fetch";
private static final String CLOSE = "@close";
private static final String SLEEP = "@sleep";
private static final String ERR = "@err";
private static final String ECHO = "@echo";
private static final String INCLUDE = "@include";
private static final String SHELL = "@shell";
private static final String PLUGIN = "@plugin";
private static final String SQL = "";
private static final String EOF = null;
private static final StateAction[] STATE_TABLE = {
new StateAction(
PRE_SETUP_STATE,
new StateDatum[]{
new StateDatum(VAR, PRE_SETUP_STATE),
new StateDatum(LOCKSTEP, PRE_SETUP_STATE),
new StateDatum(NOLOCKSTEP, PRE_SETUP_STATE),
new StateDatum(ENABLED, PRE_SETUP_STATE),
new StateDatum(DISABLED, PRE_SETUP_STATE),
new StateDatum(PLUGIN, PRE_SETUP_STATE),
new StateDatum(SETUP, SETUP_STATE),
new StateDatum(CLEANUP, CLEANUP_STATE),
new StateDatum(THREAD, THREAD_STATE)
}),
new StateAction(
SETUP_STATE,
new StateDatum[]{
new StateDatum(END, POST_SETUP_STATE),
new StateDatum(SQL, SETUP_STATE),
new StateDatum(INCLUDE, SETUP_STATE),
}),
new StateAction(
POST_SETUP_STATE,
new StateDatum[]{
new StateDatum(CLEANUP, CLEANUP_STATE),
new StateDatum(THREAD, THREAD_STATE)
}),
new StateAction(
CLEANUP_STATE,
new StateDatum[]{
new StateDatum(END, POST_CLEANUP_STATE),
new StateDatum(SQL, CLEANUP_STATE),
new StateDatum(INCLUDE, CLEANUP_STATE),
}),
new StateAction(
POST_CLEANUP_STATE,
new StateDatum[]{
new StateDatum(THREAD, THREAD_STATE)
}),
new StateAction(
THREAD_STATE,
new StateDatum[]{
new StateDatum(REPEAT, REPEAT_STATE),
new StateDatum(SYNC, THREAD_STATE),
new StateDatum(TIMEOUT, THREAD_STATE),
new StateDatum(ROWLIMIT, THREAD_STATE),
new StateDatum(PREPARE, THREAD_STATE),
new StateDatum(PRINT, THREAD_STATE),
new StateDatum(FETCH, THREAD_STATE),
new StateDatum(CLOSE, THREAD_STATE),
new StateDatum(SLEEP, THREAD_STATE),
new StateDatum(SQL, THREAD_STATE),
new StateDatum(ECHO, THREAD_STATE),
new StateDatum(ERR, THREAD_STATE),
new StateDatum(SHELL, THREAD_STATE),
new StateDatum(END, POST_THREAD_STATE)
}),
new StateAction(
REPEAT_STATE,
new StateDatum[]{
new StateDatum(SYNC, REPEAT_STATE),
new StateDatum(TIMEOUT, REPEAT_STATE),
new StateDatum(ROWLIMIT, REPEAT_STATE),
new StateDatum(PREPARE, REPEAT_STATE),
new StateDatum(PRINT, REPEAT_STATE),
new StateDatum(FETCH, REPEAT_STATE),
new StateDatum(CLOSE, REPEAT_STATE),
new StateDatum(SLEEP, REPEAT_STATE),
new StateDatum(SQL, REPEAT_STATE),
new StateDatum(ECHO, REPEAT_STATE),
new StateDatum(ERR, REPEAT_STATE),
new StateDatum(SHELL, REPEAT_STATE),
new StateDatum(END, THREAD_STATE)
}),
new StateAction(
POST_THREAD_STATE,
new StateDatum[]{
new StateDatum(THREAD, THREAD_STATE),
new StateDatum(EOF, EOF_STATE)
})
};
private static final int FETCH_LEN = FETCH.length();
private static final int PREPARE_LEN = PREPARE.length();
private static final int PRINT_LEN = PRINT.length();
private static final int REPEAT_LEN = REPEAT.length();
private static final int SLEEP_LEN = SLEEP.length();
private static final int THREAD_LEN = THREAD.length();
private static final int TIMEOUT_LEN = TIMEOUT.length();
private static final int ROWLIMIT_LEN = ROWLIMIT.length();
private static final int ERR_LEN = ERR.length();
private static final int ECHO_LEN = ECHO.length();
private static final int SHELL_LEN = SHELL.length();
private static final int PLUGIN_LEN = PLUGIN.length();
private static final int INCLUDE_LEN = INCLUDE.length();
private static final int VAR_LEN = VAR.length();
private static final int BUF_SIZE = 1024;
private static final int REPEAT_READ_AHEAD_LIMIT = 65536;
private static final char[] SPACES = fill(new char[BUF_SIZE], ' ');
private static final char[] DASHES = fill(new char[BUF_SIZE], '-');
// Special "thread ids" for setup & cleanup sections; actually setup &
// cleanup SQL is executed by the main thread, and neither are in the the
// thread map.
private static final Integer SETUP_THREAD_ID = -1;
private static final Integer CLEANUP_THREAD_ID = -2;
//~ Instance fields (representing a single script):
private boolean quiet = false;
private boolean verbose = false;
private Boolean lockstep;
private Boolean disabled;
private VariableTable vars = new VariableTable();
private File scriptDirectory;
private long scriptStartTime = 0;
private final List<ConcurrentTestPlugin> plugins = new ArrayList<>();
private final Map<String, ConcurrentTestPlugin> pluginForCommand =
new HashMap<>();
private final Map<String, ConcurrentTestPlugin> preSetupPluginForCommand =
new HashMap<>();
private final List<String> setupCommands = new ArrayList<>();
private final List<String> cleanupCommands = new ArrayList<>();
private final Map<Integer, BufferedWriter> threadBufferedWriters =
new HashMap<>();
private final Map<Integer, StringWriter> threadStringWriters = new HashMap<>();
private final Map<Integer, ResultsReader> threadResultsReaders =
new HashMap<>();
public ConcurrentTestCommandScript() throws IOException {
super();
}
/**
* Constructs and prepares a new ConcurrentTestCommandScript.
*/
public ConcurrentTestCommandScript(String filename) throws IOException {
this();
prepare(filename, null);
}
//~ Methods ----------------------------------------------------------------
private static char[] fill(char[] chars, char c) {
Arrays.fill(chars, c);
return chars;
}
/**
* Runs an external application process.
*
* @param pb ProcessBuilder for the application
* @param logger if not null, command and exit status will be logged here
* @param appInput if not null, data will be copied to application's stdin
* @param appOutput if not null, data will be captured from application's
* stdout and stderr
* @return application process exit value
*/
static int runAppProcess(
ProcessBuilder pb,
Logger logger,
Reader appInput,
Writer appOutput) throws IOException, InterruptedException {
pb.redirectErrorStream(true);
if (logger != null) {
logger.info("start process: " + pb.command());
}
Process p = pb.start();
// Setup the input/output streams to the subprocess.
// The buffering here is arbitrary. Javadocs strongly encourage
// buffering, but the size needed is very dependent on the
// specific application being run, the size of the input
// provided by the caller, and the amount of output expected.
// Since this method is currently used only by unit tests,
// large-ish fixed buffer sizes have been chosen. If this
// method becomes used for something in production, it might
// be better to have the caller provide them as arguments.
if (appInput != null) {
OutputStream out =
new BufferedOutputStream(
p.getOutputStream(),
100 * 1024);
int c;
while ((c = appInput.read()) != -1) {
out.write(c);
}
out.flush();
}
if (appOutput != null) {
InputStream in =
new BufferedInputStream(
p.getInputStream(),
100 * 1024);
int c;
while ((c = in.read()) != -1) {
appOutput.write(c);
}
appOutput.flush();
in.close();
}
p.waitFor();
int status = p.exitValue();
if (logger != null) {
logger.info("exit status=" + status + " from " + pb.command());
}
return status;
}
/**
* Gets ready to execute: loads script FILENAME applying external variable
* BINDINGS
*/
private void prepare(String filename, List<String> bindings)
throws IOException {
vars = new VariableTable();
CommandParser parser = new CommandParser();
parser.rememberVariableRebindings(bindings);
parser.load(filename);
for (Integer threadId : getThreadIds()) {
addThreadWriters(threadId);
}
// Backwards compatible: printed results always has a setup section, but
// cleanup section is optional:
setThreadName(SETUP_THREAD_ID, "setup");
addThreadWriters(SETUP_THREAD_ID);
if (!cleanupCommands.isEmpty()) {
setThreadName(CLEANUP_THREAD_ID, "cleanup");
addThreadWriters(CLEANUP_THREAD_ID);
}
}
/**
* Executes the script
*/
public void execute() throws Exception {
scriptStartTime = System.currentTimeMillis();
executeSetup();
ConcurrentTestCommandExecutor[] threads = innerExecute();
executeCleanup();
postExecute(threads);
}
private void addThreadWriters(Integer threadId) {
StringWriter w = new StringWriter();
BufferedWriter bw = new BufferedWriter(w);
threadStringWriters.put(threadId, w);
threadBufferedWriters.put(threadId, bw);
threadResultsReaders.put(threadId, new ResultsReader(bw));
}
public void setQuiet(boolean val) {
quiet = val;
}
public void setVerbose(boolean val) {
verbose = val;
}
public boolean useLockstep() {
return lockstep != null && lockstep;
}
public boolean isDisabled() {
for (ConcurrentTestPlugin plugin : plugins) {
if (plugin.isTestDisabled()) {
return true;
}
}
return disabled != null && disabled;
}
public void executeSetup() throws Exception {
executeCommands(SETUP_THREAD_ID, setupCommands);
}
public void executeCleanup() throws Exception {
executeCommands(CLEANUP_THREAD_ID, cleanupCommands);
}
protected void executeCommands(int threadId, List<String> commands)
throws Exception {
if (commands == null || commands.size() == 0) {
return;
}
Connection connection = DriverManager.getConnection(jdbcURL, jdbcProps);
if (connection.getMetaData().supportsTransactions()) {
connection.setAutoCommit(false);
}
boolean forced = false; // flag, keep going after an error
try {
for (String command : commands) {
String sql = command.trim();
storeSql(threadId, sql);
if (isComment(sql)) {
continue;
}
// handle sqlline-type directives:
if (sql.startsWith("!set")) {
String[] tokens = sql.split(" +");
// handle only SET FORCE
if ((tokens.length > 2)
&& tokens[1].equalsIgnoreCase("force")) {
forced = asBoolValue(tokens[2]);
}
continue; // else ignore
} else if (sql.startsWith("!")) {
continue; // else ignore
}
if (sql.endsWith(";")) {
sql = sql.substring(0, sql.length() - 1);
}
if (isSelect(sql)) {
try (Statement stmt = connection.createStatement()) {
ResultSet rset = stmt.executeQuery(sql);
storeResults(threadId, rset, -1);
}
} else if (sql.equalsIgnoreCase("commit")) {
connection.commit();
} else if (sql.equalsIgnoreCase("rollback")) {
connection.rollback();
} else {
try (Statement stmt = connection.createStatement()) {
int rows = stmt.executeUpdate(sql);
if (rows != 1) {
storeMessage(
threadId, String.valueOf(rows) + " rows affected.");
} else {
storeMessage(threadId, "1 row affected.");
}
} catch (SQLException ex) {
if (forced) {
storeMessage(threadId, ex.getMessage()); // swallow
} else {
throw ex;
}
}
}
}
} finally {
if (connection.getMetaData().supportsTransactions()) {
connection.rollback();
}
connection.close();
}
}
// timeout < 0 means no timeout
private void storeResults(Integer threadId, ResultSet rset, long timeout)
throws SQLException {
ResultsReader r = threadResultsReaders.get(threadId);
r.read(rset, timeout);
}
/**
* Identifies the start of a comment line; same rules as sqlline
*/
private boolean isComment(String line) {
return line.startsWith("--") || line.startsWith("#");
}
/**
* translates argument of !set force etc.
*/
private boolean asBoolValue(String s) {
return s.equalsIgnoreCase("true")
|| s.equalsIgnoreCase("yes")
|| s.equalsIgnoreCase("on");
}
/**
* Determines whether a block of SQL is a SELECT statement.
*/
private boolean isSelect(String sql) {
BufferedReader rdr = new BufferedReader(new StringReader(sql));
try {
String line;
while ((line = rdr.readLine()) != null) {
line = line.trim().toLowerCase(Locale.ROOT);
if (isComment(line)) {
continue;
}
return line.startsWith("select")
|| line.startsWith("values")
|| line.startsWith("explain");
}
} catch (IOException e) {
assert false : "IOException via StringReader";
} finally {
try {
rdr.close();
} catch (IOException e) {
assert false : "IOException via StringReader";
}
}
return false;
}
/**
* Builds a map of thread ids to result data for the thread. Each result
* datum is an <code>String[2]</code> containing the thread name and the
* thread's output.
*
* @return the map.
*/
private Map<Integer, String[]> collectResults() {
final TreeMap<Integer, String[]> results = new TreeMap<>();
// get all normal threads
final TreeSet<Integer> threadIds = new TreeSet<>(getThreadIds());
// add the "special threads"
threadIds.add(SETUP_THREAD_ID);
threadIds.add(CLEANUP_THREAD_ID);
for (Integer threadId : threadIds) {
try {
BufferedWriter bout = threadBufferedWriters.get(threadId);
if (bout != null) {
bout.flush();
}
} catch (IOException e) {
assert false : "IOException via StringWriter";
}
String threadName = getFormattedThreadName(threadId);
StringWriter out = threadStringWriters.get(threadId);
if (out == null) {
continue;
}
results.put(
threadId,
new String[]{threadName, out.toString()});
}
return results;
}
// solely for backwards-compatible output
private String getFormattedThreadName(Integer id) {
if (id < 0) { // special thread
return getThreadName(id);
} else { // normal thread
return "thread " + getThreadName(id);
}
}
public void printResults(PrintWriter out) throws IOException {
final Map<Integer, String[]> results = collectResults();
if (verbose) {
out.write(
String.format(Locale.ROOT,
"script execution started at %tc (%d)%n",
new Timestamp(scriptStartTime), scriptStartTime));
}
printThreadResults(out, results.get(SETUP_THREAD_ID));
for (Integer id : results.keySet()) {
if (id < 0) {
continue; // special thread
}
printThreadResults(out, results.get(id)); // normal thread
}
printThreadResults(out, results.get(CLEANUP_THREAD_ID));
}
private void printThreadResults(PrintWriter out, String[] threadResult)
throws IOException {
if (threadResult == null) {
return;
}
String threadName = threadResult[0];
out.write("-- " + threadName);
out.println();
out.write(threadResult[1]);
out.write("-- end of " + threadName);
out.println();
out.println();
out.flush();
}
/**
* Causes errors to be send here for custom handling. See
* {@link #customErrorHandler(ConcurrentTestCommandExecutor)}.
*/
boolean requiresCustomErrorHandling() {
return true;
}
void customErrorHandler(
ConcurrentTestCommandExecutor executor) {
StringBuilder message = new StringBuilder();
Throwable cause = executor.getFailureCause();
ConcurrentTestCommand command = executor.getFailureCommand();
if ((command == null) || !command.isFailureExpected()) {
message.append(cause.getMessage());
StackTraceElement[] trace = cause.getStackTrace();
for (StackTraceElement aTrace : trace) {
message.append("\n\t").append(aTrace.toString());
}
} else {
message.append(cause.getClass().getName())
.append(": ")
.append(cause.getMessage());
}
storeMessage(
executor.getThreadId(),
message.toString());
}
/**
* Retrieves the output stream for the given thread id.
*
* @return a BufferedWriter on a StringWriter for the thread.
*/
private BufferedWriter getThreadWriter(Integer threadId) {
assert threadBufferedWriters.containsKey(threadId);
return threadBufferedWriters.get(threadId);
}
/**
* Saves a SQL command to be printed with the thread's output.
*/
private void storeSql(Integer threadId, String sql) {
StringBuilder message = new StringBuilder();
BufferedReader rdr = new BufferedReader(new StringReader(sql));
try {
String line;
while ((line = rdr.readLine()) != null) {
line = line.trim();
if (message.length() > 0) {
message.append('\n');
}
message.append("> ").append(line);
}
} catch (IOException e) {
assert false : "IOException via StringReader";
} finally {
try {
rdr.close();
} catch (IOException e) {
assert false : "IOException via StringReader";
}
}
storeMessage(
threadId,
message.toString());
}
/**
* Saves a message to be printed with the thread's output.
*/
private void storeMessage(Integer threadId, String message) {
BufferedWriter out = getThreadWriter(threadId);
try {
if (verbose) {
long t = System.currentTimeMillis() - scriptStartTime;
out.write("at " + t + ": ");
}
out.write(message);
out.newLine();
} catch (IOException e) {
assert false : "IOException on StringWriter";
}
}
//~ Inner Classes ----------------------------------------------------------
/** State action. */
private static class StateAction {
final String state;
final StateDatum[] stateData;
StateAction(String state, StateDatum[] stateData) {
this.state = state;
this.stateData = stateData;
}
}
/** State datum. */
private static class StateDatum {
final String x;
final String y;
StateDatum(String x, String y) {
this.x = x;
this.y = y;
}
}
/** Symbol table of script variables. */
private class VariableTable {
private final Map<String, String> map;
// matches $$, $var, ${var}
private final Pattern symbolPattern =
Pattern.compile("\\$((\\$)|([A-Za-z]\\w*)|\\{([A-Za-z]\\w*)\\})");
VariableTable() {
map = new HashMap<>();
}
/** Exception. */
public class Excn extends IllegalArgumentException {
Excn(String msg) {
super(msg);
}
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean isDefined(String sym) {
return map.containsKey(sym);
}
// a symbol must be explicitly defined before it can be set or read.
public void define(String sym, String val) {
if (isDefined(sym)) {
throw new Excn("second declaration of variable " + sym);
}
// convert a null val to a null string
map.put(sym, val == null ? "" : val);
}
// returns null is SYM is not defined
public String get(String sym) {
if (isDefined(sym)) {
return map.get(sym);
} else {
return null;
}
}
public void set(String sym, String val) {
if (isDefined(sym)) {
map.put(sym, val);
return;
}
throw new Excn("undeclared variable " + sym);
}
public String expand(String in) {
if (in.contains("$")) {
StringBuilder out = new StringBuilder();
Matcher matcher = symbolPattern.matcher(in);
int lastEnd = 0;
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
String val;
if (null != matcher.group(2)) {
val = "$"; // matched $$
} else {
String var = matcher.group(3); // matched $var
if (var == null) {
var = matcher.group(4); // matched ${var}
}
if (map.containsKey(var)) {
val = map.get(var);
val = expand(val);
} else {
// not our var, so can't expand
val = matcher.group(0);
}
}
out.append(in.substring(lastEnd, start));
out.append(val);
lastEnd = end;
}
out.append(in.substring(lastEnd));
return out.toString();
} else {
return in;
}
}
}
/** Command parser. */
private class CommandParser {
final Pattern splitWords = Pattern.compile("\\s+");
final Pattern splitBinding = Pattern.compile("=");
final Pattern matchesVarDefn =
Pattern.compile("([A-Za-z]\\w*) *=(.*)$");
// \1 is VAR, \2 is VAL
// parser state
private String state;
private int threadId;
private int nextThreadId;
private int order;
private int repeatCount;
private boolean scriptHasVars;
private final Deque<File> currentDirectory = new ArrayDeque<>();
/** Binding of a value to a variable. */
private class Binding {
public final String var;
public final String val;
Binding(String var, String val) {
this.var = var;
this.val = val;
}
// @param phrase has form VAR=VAL
Binding(String phrase) {
String[] parts = splitBinding.split(phrase);
assert parts.length == 2;
this.var = parts[0];
this.val = parts[1];
}
}
// A list of Bindings that must be applied immediately after parsing
// last @var.
private final List<Binding> deferredBindings = new ArrayList<>();
CommandParser() {
state = PRE_SETUP_STATE;
threadId = nextThreadId = 1;
order = 1;
repeatCount = 0;
scriptHasVars = false;
currentDirectory.push(null);
}
// Parses a set of VAR=VAL pairs from the command line, and saves it for
// later application.
public void rememberVariableRebindings(List<String> pairs) {
if (pairs == null) {
return;
}
for (String pair : pairs) {
deferredBindings.add(new Binding(pair));
}
}
// to call after all @var commands but before any SQL.
private void applyVariableRebindings() {
for (Binding binding : deferredBindings) {
vars.set(binding.var, binding.val);
}
}
// trace loading of a script
private void trace(String prefix, Object message) {
if (verbose && !quiet) {
if (prefix != null) {
System.out.print(prefix + ": ");
}
System.out.println(message);
}
}
private void trace(String message) {
trace(null, message);
}
/**
* Parses a multi-threaded script and converts it into test commands.
*/
private void load(String scriptFileName) throws IOException {
File scriptFile = new File(currentDirectory.peek(), scriptFileName);
currentDirectory.push(scriptDirectory = scriptFile.getParentFile());
try (BufferedReader in = Util.reader(scriptFile)) {
String line;
while ((line = in.readLine()) != null) {
line = line.trim();
Map<String, String> commandStateMap = lookupState(state);
final String command;
boolean isSql = false;
if (line.equals("") || line.startsWith("--")) {
continue;
} else if (line.startsWith("@")) {
command = firstWord(line);
} else {
isSql = true;
command = SQL;
}
if (!commandStateMap.containsKey(command)) {
throw new IllegalStateException(
command + " not allowed in state " + state);
}
boolean changeState;
if (isSql) {
String sql = readSql(line, in);
loadSql(sql);
changeState = true;
} else {
changeState = loadCommand(command, line, in);
}
if (changeState) {
String nextState = commandStateMap.get(command);
assert nextState != null;
if (!nextState.equals(state)) {
doEndOfState(state);
}
state = nextState;
}
}
// at EOF
currentDirectory.pop();
if (currentDirectory.size() == 1) {
// at top EOF
if (!lookupState(state).containsKey(EOF)) {
throw new IllegalStateException(
"Premature end of file in '" + state + "' state");
}
}
}
}
private void loadSql(String sql) {
if (SETUP_STATE.equals(state)) {
trace("@setup", sql);
setupCommands.add(sql);
} else if (CLEANUP_STATE.equals(state)) {
trace("@cleanup", sql);
cleanupCommands.add(sql);
} else if (
THREAD_STATE.equals(state) || REPEAT_STATE.equals(state)) {
boolean isSelect = isSelect(sql);
trace(sql);
for (int i = threadId; i < nextThreadId; i++) {
CommandWithTimeout cmd =
isSelect ? new SelectCommand(sql) : new SqlCommand(sql);
addCommand(i, order, cmd);
}
order++;
} else {
assert false;
}
}
// returns TRUE when load-state should advance, FALSE when it must not.
private boolean loadCommand(
String command, String line, BufferedReader in) throws IOException {
if (VAR.equals(command)) {
String args = line.substring(VAR_LEN).trim();
scriptHasVars = true;
trace("@var", args);
defineVariables(args);
} else if (LOCKSTEP.equals(command)) {
assert lockstep == null
: LOCKSTEP + " and " + NOLOCKSTEP + " may only appear once";
lockstep = Boolean.TRUE;
trace("lockstep");
} else if (NOLOCKSTEP.equals(command)) {
assert lockstep == null
: LOCKSTEP + " and " + NOLOCKSTEP + " may only appear once";
lockstep = Boolean.FALSE;
trace("no lockstep");
} else if (DISABLED.equals(command)) {
assert disabled == null
: DISABLED + " and " + ENABLED + " may only appear once";
disabled = Boolean.TRUE;
trace("disabled");
} else if (ENABLED.equals(command)) {
assert disabled == null
: DISABLED + " and " + ENABLED + " may only appear once";
disabled = Boolean.FALSE;
trace("enabled");
} else if (SETUP.equals(command)) {
trace("@setup");
} else if (CLEANUP.equals(command)) {
trace("@cleanup");
} else if (INCLUDE.equals(command)) {
String includedFile =
vars.expand(line.substring(INCLUDE_LEN).trim());
trace("@include", includedFile);
load(includedFile);
trace("end @include", includedFile);
} else if (THREAD.equals(command)) {
String threadNamesStr = line.substring(THREAD_LEN).trim();
trace("@thread", threadNamesStr);
StringTokenizer threadNamesTok =
new StringTokenizer(threadNamesStr, ",");
while (threadNamesTok.hasMoreTokens()) {
setThreadName(
nextThreadId++,
threadNamesTok.nextToken());
}
} else if (REPEAT.equals(command)) {
String arg = line.substring(REPEAT_LEN).trim();
repeatCount = Integer.parseInt(vars.expand(arg));
trace("start @repeat block", repeatCount);
assert repeatCount > 0 : "Repeat count must be > 0";
in.mark(REPEAT_READ_AHEAD_LIMIT);
} else if (END.equals(command)) {
if (SETUP_STATE.equals(state)) {
trace("end @setup");
} else if (CLEANUP_STATE.equals(state)) {
trace("end @cleanup");
} else if (THREAD_STATE.equals(state)) {
threadId = nextThreadId;
} else if (REPEAT_STATE.equals(state)) {
trace("repeating");
repeatCount--;
if (repeatCount > 0) {
try {
in.reset();
} catch (IOException e) {
throw new IllegalStateException(
"Unable to reset reader -- repeat "
+ "contents must be less than "
+ REPEAT_READ_AHEAD_LIMIT + " bytes");
}
trace("end @repeat block");
return false; // don't change the state
}
} else {
assert false;
}
} else if (SYNC.equals(command)) {
trace("@sync");
for (int i = threadId; i < nextThreadId; i++) {
addSynchronizationCommand(i, order);
}
order++;
} else if (TIMEOUT.equals(command)) {
String args = line.substring(TIMEOUT_LEN).trim();
String millisStr = vars.expand(firstWord(args));
long millis = Long.parseLong(millisStr);
assert millis >= 0L : "Timeout must be >= 0";
String sql = readSql(skipFirstWord(args).trim(), in);
trace("@timeout", sql);
boolean isSelect = isSelect(sql);
for (int i = threadId; i < nextThreadId; i++) {
CommandWithTimeout cmd =
isSelect ? new SelectCommand(sql, millis)
: new SqlCommand(sql, millis);
addCommand(i, order, cmd);
}
order++;
} else if (ROWLIMIT.equals(command)) {
String args = line.substring(ROWLIMIT_LEN).trim();
String limitStr = vars.expand(firstWord(args));
int limit = Integer.parseInt(limitStr);
assert limit >= 0 : "Rowlimit must be >= 0";
String sql = readSql(skipFirstWord(args).trim(), in);
trace("@rowlimit ", sql);
boolean isSelect = isSelect(sql);
if (!isSelect) {
throw new IllegalStateException(
"Only select can be used with rowlimit");
}
for (int i = threadId; i < nextThreadId; i++) {
addCommand(i, order, new SelectCommand(sql, 0, limit));
}
order++;
} else if (PRINT.equals(command)) {
String spec = vars.expand(line.substring(PRINT_LEN).trim());
trace("@print", spec);
for (int i = threadId; i < nextThreadId; i++) {
addCommand(i, order, new PrintCommand(spec));
}
order++;
} else if (PREPARE.equals(command)) {
String startOfSql =
line.substring(PREPARE_LEN).trim();
String sql = readSql(startOfSql, in);
trace("@prepare", sql);
for (int i = threadId; i < nextThreadId; i++) {
addCommand(i, order, new PrepareCommand(sql));
}
order++;
} else if (PLUGIN.equals(command)) {
String cmd = line.substring(PLUGIN_LEN).trim();
String pluginName = readLine(cmd, in).trim();
trace("@plugin", pluginName);
plugin(pluginName);
} else if (pluginForCommand.containsKey(command)) {
String cmd = line.substring(command.length())
.trim();
cmd = readLine(cmd, in);
trace("@" + command, cmd);
for (int i = threadId; i < nextThreadId; i++) {
addCommand(
i,
order,
new PluginCommand(
command, cmd));
}
order++;
} else if (preSetupPluginForCommand.containsKey(command)) {
String cmd = line.substring(command.length()).trim();
cmd = readLine(cmd, in);
trace("@" + command, cmd);
ConcurrentTestPlugin plugin =
preSetupPluginForCommand.get(command);
plugin.preSetupFor(command, cmd);
} else if (SHELL.equals(command)) {
String cmd = line.substring(SHELL_LEN).trim();
cmd = readLine(cmd, in);
trace("@shell", cmd);
for (int i = threadId; i < nextThreadId; i++) {
addCommand(i, order, new ShellCommand(cmd));
}
order++;
} else if (ECHO.equals(command)) {
String msg = line.substring(ECHO_LEN).trim();
msg = readLine(msg, in);
trace("@echo", msg);
for (int i = threadId; i < nextThreadId; i++) {
addCommand(i, order, new EchoCommand(msg));
}
order++;
} else if (ERR.equals(command)) {
String startOfSql =
line.substring(ERR_LEN).trim();
String sql = readSql(startOfSql, in);
trace("@err ", sql);
boolean isSelect = isSelect(sql);
for (int i = threadId; i < nextThreadId; i++) {
CommandWithTimeout cmd =
isSelect ? new SelectCommand(sql, true)
: new SqlCommand(sql, true);
addCommand(i, order, cmd);
}
order++;
} else if (FETCH.equals(command)) {
String arg = vars.expand(line.substring(FETCH_LEN).trim());
trace("@fetch", arg);
long millis = 0L;
if (arg.length() > 0) {
millis = Long.parseLong(arg);
assert millis >= 0L : "Fetch timeout must be >= 0";
}
for (int i = threadId; i < nextThreadId; i++) {
addCommand(
i,
order,
new FetchAndPrintCommand(millis));
}
order++;
} else if (CLOSE.equals(command)) {
trace("@close");
for (int i = threadId; i < nextThreadId; i++) {
addCloseCommand(i, order);
}
order++;
} else if (SLEEP.equals(command)) {
String arg = vars.expand(line.substring(SLEEP_LEN).trim());
trace("@sleep", arg);
long millis = Long.parseLong(arg);
assert millis >= 0L : "Sleep timeout must be >= 0";
for (int i = threadId; i < nextThreadId; i++) {
addSleepCommand(i, order, millis);
}
order++;
} else {
assert false : "Unknown command " + command;
}
return true; // normally, advance the state
}
private void doEndOfState(String state) {
if (state.equals(PRE_SETUP_STATE)) {
applyVariableRebindings();
}
}
private void defineVariables(String line) {
// two forms: "VAR VAR*" and "VAR=VAL$"
Matcher varDefn = matchesVarDefn.matcher(line);
if (varDefn.lookingAt()) {
String var = varDefn.group(1);
String val = varDefn.group(2);
vars.define(var, val);
} else {
String[] words = splitWords.split(line);
for (String var : words) {
String value = System.getenv(var);
vars.define(var, value);
}
}
}
private void plugin(String pluginName) throws IOException {
try {
@SuppressWarnings("unchecked")
Class<ConcurrentTestPlugin> pluginClass =
(Class<ConcurrentTestPlugin>) Class.forName(pluginName);
final Constructor<ConcurrentTestPlugin> constructor =
pluginClass.getConstructor();
final ConcurrentTestPlugin plugin = constructor.newInstance();
plugins.add(plugin);
addExtraCommands(plugin.getSupportedThreadCommands(), THREAD_STATE);
addExtraCommands(plugin.getSupportedThreadCommands(), REPEAT_STATE);
for (String commandName : plugin.getSupportedThreadCommands()) {
pluginForCommand.put(commandName, plugin);
}
addExtraCommands(
plugin.getSupportedPreSetupCommands(), PRE_SETUP_STATE);
for (String commandName : plugin.getSupportedPreSetupCommands()) {
preSetupPluginForCommand.put(commandName, plugin);
}
} catch (Exception e) {
throw new IOException(e.toString());
}
}
private void addExtraCommands(Iterable<String> commands, String state) {
assert state != null;
for (int i = 0, n = STATE_TABLE.length; i < n; i++) {
if (state.equals(STATE_TABLE[i].state)) {
StateDatum[] stateData = STATE_TABLE[i].stateData;
final List<StateDatum> stateDataList =
new ArrayList<>(Arrays.asList(stateData));
for (String cmd : commands) {
stateDataList.add(new StateDatum(cmd, state));
}
STATE_TABLE[i] =
new StateAction(
state, stateDataList.toArray(stateData));
}
}
}
/**
* Manages state transitions.
* Converts a state name into a map. Map keys are the names of available
* commands (e.g. @sync), and map values are the state to switch to open
* seeing the command.
*/
private Map<String, String> lookupState(String state) {
assert state != null;
for (StateAction a : STATE_TABLE) {
if (state.equals(a.state)) {
StateDatum[] stateData = a.stateData;
Map<String, String> result = new HashMap<String, String>();
for (StateDatum datum : stateData) {
result.put(datum.x, datum.y);
}
return result;
}
}
throw new IllegalArgumentException();
}
/**
* Returns the first word of the given line, assuming the line is
* trimmed. Returns the characters up the first non-whitespace
* character in the line.
*/
private String firstWord(String trimmedLine) {
return trimmedLine.replaceFirst("\\s.*", "");
}
/**
* Returns everything but the first word of the given line, assuming the
* line is trimmed. Returns the characters following the first series of
* consecutive whitespace characters in the line.
*/
private String skipFirstWord(String trimmedLine) {
return trimmedLine.replaceFirst("^\\S+\\s+", "");
}
/**
* Returns an input line, possible extended by the continuation
* character (\). Scans the script until it finds an un-escaped
* newline.
*/
private String readLine(String line, BufferedReader in) throws IOException {
line = line.trim();
boolean more = line.endsWith("\\");
if (more) {
line = line.substring(0, line.lastIndexOf('\\')); // snip
StringBuilder buf = new StringBuilder(line); // save
while (more) {
line = in.readLine();
if (line == null) {
break;
}
line = line.trim();
more = line.endsWith("\\");
if (more) {
line = line.substring(0, line.lastIndexOf('\\'));
}
buf.append(' ').append(line);
}
line = buf.toString().trim();
}
if (scriptHasVars && line.contains("$")) {
line = vars.expand(line);
}
return line;
}
/**
* Returns a block of SQL, starting with the given String. Returns
* <code> startOfSql</code> concatenated with each line from
* <code>in</code> until a line ending with a semicolon is found.
*/
private String readSql(String startOfSql, BufferedReader in)
throws IOException {
StringBuilder sql = new StringBuilder(startOfSql);
sql.append('\n');
String line;
if (!startOfSql.trim().endsWith(";")) {
while ((line = in.readLine()) != null) {
sql.append(line).append('\n');
if (line.trim().endsWith(";")) {
break;
}
}
}
line = sql.toString().trim();
if (scriptHasVars && line.contains("$")) {
line = vars.expand(line);
}
return line;
}
}
/** Print command.
*
* <p>When executed, a @print command defines how any following @fetch
* or @select commands will handle their resuult rows. MTSQL can print all
* rows, no rows, or every nth row. A printed row can be prefixed by a
* sequence nuber and/or the time it was received (a different notion than
* its rowtime, which often tells when it was inserted).
*/
private class PrintCommand extends AbstractCommand {
// print every nth row: 1 means all rows, 0 means no rows.
private final int nth;
private final boolean count; // print a sequence number
private final boolean time; // print the time row was fetched
// print total row count and elapsed fetch time:
private final boolean total;
// TODO: more control of formats
PrintCommand(String spec) {
int nth = 0;
boolean count = false;
boolean time = false;
boolean total = false;
StringTokenizer tokenizer = new StringTokenizer(spec);
if (tokenizer.countTokens() == 0) {
// a bare "@print" means "@print all"
nth = 1;
} else {
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equalsIgnoreCase("none")) {
nth = 0;
} else if (token.equalsIgnoreCase("all")) {
nth = 1;
} else if (token.equalsIgnoreCase("total")) {
total = true;
} else if (token.equalsIgnoreCase("count")) {
count = true;
} else if (token.equalsIgnoreCase("time")) {
time = true;
} else if (token.equalsIgnoreCase("every")) {
nth = 1;
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
nth = Integer.parseInt(token);
}
}
}
}
this.nth = nth;
this.count = count;
this.time = time;
this.total = total;
}
protected void doExecute(ConcurrentTestCommandExecutor executor)
throws SQLException {
Integer threadId = executor.getThreadId();
BufferedWriter out = threadBufferedWriters.get(threadId);
threadResultsReaders.put(
threadId, new ResultsReader(out, nth, count, time, total));
}
}
/** Echo command. */
private class EchoCommand extends AbstractCommand {
private final String msg;
private EchoCommand(String msg) {
this.msg = msg;
}
protected void doExecute(ConcurrentTestCommandExecutor executor)
throws SQLException {
storeMessage(executor.getThreadId(), msg);
}
}
/** Plugin command. */
private class PluginCommand extends AbstractCommand {
private final ConcurrentTestPluginCommand pluginCommand;
private PluginCommand(
String command,
String params) throws IOException {
ConcurrentTestPlugin plugin = pluginForCommand.get(command);
pluginCommand = plugin.getCommandFor(command, params);
}
protected void doExecute(final ConcurrentTestCommandExecutor exec)
throws Exception {
ConcurrentTestPluginCommand.TestContext context =
new ConcurrentTestPluginCommand.TestContext() {
public void storeMessage(String message) {
ConcurrentTestCommandScript.this.storeMessage(
exec.getThreadId(), message);
}
public Connection getConnection() {
return exec.getConnection();
}
public Statement getCurrentStatement() {
return exec.getStatement();
}
};
pluginCommand.execute(context);
}
}
// Matches shell wilcards and other special characters: when a command
// contains some of these, it needs a shell to run it.
private final Pattern shellWildcardPattern = Pattern.compile("[*?$|<>&]");
// REVIEW mb 2/24/09 (Mardi Gras) Should this have a timeout?
/** Shell command. */
private class ShellCommand extends AbstractCommand {
private final String command;
private List<String> argv; // the command, parsed and massaged
private ShellCommand(String command) {
this.command = command;
boolean needShell = hasWildcard(command);
if (needShell) {
argv = new ArrayList<>();
argv.add("/bin/sh");
argv.add("-c");
argv.add(command);
} else {
argv = tokenize(command);
}
}
private boolean hasWildcard(String command) {
return shellWildcardPattern.matcher(command).find();
}
private List<String> tokenize(String s) {
List<String> result = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(s);
while (tokenizer.hasMoreTokens()) {
result.add(tokenizer.nextToken());
}
return result;
}
protected void doExecute(ConcurrentTestCommandExecutor executor) {
Integer threadId = executor.getThreadId();
storeMessage(threadId, command);
// argv[0] is found on $PATH. Working directory is the script's home
// directory.
//
// WARNING: ProcessBuilder is security-sensitive. Its use is currently
// safe because this code is under "core/test". Developers must not move
// this code into "core/main".
ProcessBuilder pb = new ProcessBuilder(argv);
pb.directory(scriptDirectory);
try {
// direct stdout & stderr to the the threadWriter
int status = runAppProcess(pb, null, null, getThreadWriter(threadId));
if (status != 0) {
storeMessage(threadId,
"command " + command + ": exited with status " + status);
}
} catch (Exception e) {
storeMessage(threadId,
"command " + command + ": failed with exception " + e.getMessage());
}
}
}
/** Command that has a timeout. */
// TODO: replace by super.CommmandWithTimeout
private abstract static class CommandWithTimeout extends AbstractCommand {
private long timeout;
private CommandWithTimeout(long timeout) {
this.timeout = timeout;
}
// returns the timeout as set (-1 means no timeout)
protected long setTimeout(Statement stmt) throws SQLException {
assert timeout >= 0;
if (timeout > 0) {
// FIX: call setQueryTimeoutMillis() when available.
assert timeout >= 1000 : "timeout too short";
int t = (int) (timeout / 1000);
stmt.setQueryTimeout(t);
return t;
}
return -1;
}
}
/** Command with timeout and row limit. */
private abstract static class CommandWithTimeoutAndRowLimit
extends CommandWithTimeout {
private int rowLimit;
private CommandWithTimeoutAndRowLimit(long timeout) {
this(timeout, 0);
}
private CommandWithTimeoutAndRowLimit(long timeout, int rowLimit) {
super(timeout);
this.rowLimit = rowLimit;
}
protected void setRowLimit(Statement stmt) throws SQLException {
assert rowLimit >= 0;
if (rowLimit > 0) {
stmt.setMaxRows(rowLimit);
}
}
}
/**
* SelectCommand creates and executes a SQL select statement, with optional
* timeout and row limit.
*/
private class SelectCommand extends CommandWithTimeoutAndRowLimit {
private String sql;
private SelectCommand(String sql) {
this(sql, 0, 0);
}
private SelectCommand(String sql, boolean errorExpected) {
this(sql, 0, 0);
if (errorExpected) {
this.markToFail();
}
}
private SelectCommand(String sql, long timeout) {
this(sql, timeout, 0);
}
private SelectCommand(String sql, long timeout, int rowLimit) {
super(timeout, rowLimit);
this.sql = sql;
}
protected void doExecute(ConcurrentTestCommandExecutor executor)
throws SQLException {
// TODO: trim and chop in constructor; stash sql in base class;
// execute() calls storeSql.
String properSql = sql.trim();
storeSql(
executor.getThreadId(),
properSql);
if (properSql.endsWith(";")) {
properSql = properSql.substring(0, properSql.length() - 1);
}
PreparedStatement stmt =
executor.getConnection().prepareStatement(properSql);
long timeout = setTimeout(stmt);
setRowLimit(stmt);
try {
storeResults(
executor.getThreadId(),
stmt.executeQuery(),
timeout);
} finally {
stmt.close();
}
}
}
/**
* SelectCommand creates and executes a SQL select statement, with optional
* timeout.
*/
private class SqlCommand extends CommandWithTimeout {
private String sql;
private SqlCommand(String sql) {
super(0);
this.sql = sql;
}
private SqlCommand(String sql, boolean errorExpected) {
super(0);
this.sql = sql;
if (errorExpected) {
this.markToFail();
}
}
private SqlCommand(String sql, long timeout) {
super(timeout);
this.sql = sql;
}
protected void doExecute(ConcurrentTestCommandExecutor executor)
throws SQLException {
String properSql = sql.trim();
storeSql(
executor.getThreadId(),
properSql);
if (properSql.endsWith(";")) {
properSql = properSql.substring(0, properSql.length() - 1);
}
if (properSql.equalsIgnoreCase("commit")) {
executor.getConnection().commit();
return;
} else if (properSql.equalsIgnoreCase("rollback")) {
executor.getConnection().rollback();
return;
}
PreparedStatement stmt =
executor.getConnection().prepareStatement(properSql);
long timeout = setTimeout(stmt);
boolean timeoutSet = timeout >= 0;
try {
boolean haveResults = stmt.execute();
if (haveResults) {
// Farrago rewrites "call" statements as selects.
storeMessage(
executor.getThreadId(),
"0 rows affected.");
// is there anything interesting in the ResultSet?
} else {
int rows = stmt.getUpdateCount();
if (rows != 1) {
storeMessage(
executor.getThreadId(),
String.valueOf(rows) + " rows affected.");
} else {
storeMessage(
executor.getThreadId(),
"1 row affected.");
}
}
} catch (SqlTimeoutException e) {
if (!timeoutSet) {
throw e;
}
Util.swallow(e, null);
storeMessage(
executor.getThreadId(),
"Timeout");
} finally {
stmt.close();
}
}
}
/**
* PrepareCommand creates a {@link PreparedStatement}, which is saved as the
* current statement of its test thread. For a preparted query (a SELECT or
* a CALL with results), a subsequent FetchAndPrintCommand executes the
* statement and fetches its reults, until end-of-data or a timeout. A
* PrintCommand attaches a listener, called for each rows, that selects rows
* to save and print, and sets the format. By default, if no PrintCommand
* appears before a FetchAndPrintCommand, all rows are printed. A
* CloseCommand closes and discards the prepared statement.
*/
private class PrepareCommand extends AbstractCommand {
private String sql;
private PrepareCommand(String sql) {
this.sql = sql;
}
protected void doExecute(ConcurrentTestCommandExecutor executor)
throws SQLException {
String properSql = sql.trim();
storeSql(
executor.getThreadId(),
properSql);
if (properSql.endsWith(";")) {
properSql = properSql.substring(0, properSql.length() - 1);
}
PreparedStatement stmt =
executor.getConnection().prepareStatement(properSql);
executor.setStatement(stmt);
}
}
/**
* FetchAndPrintCommand executes a previously prepared statement stored
* inthe ConcurrentTestCommandExecutor and then outputs the returned
* rows.
*/
private class FetchAndPrintCommand extends CommandWithTimeout {
private FetchAndPrintCommand(long timeout) {
super(timeout);
}
protected void doExecute(ConcurrentTestCommandExecutor executor)
throws SQLException {
PreparedStatement stmt =
(PreparedStatement) executor.getStatement();
long timeout = setTimeout(stmt);
storeResults(
executor.getThreadId(),
stmt.executeQuery(),
timeout);
}
}
/** Result reader. */
private class ResultsReader {
private final PrintWriter out;
// print every Nth row. 1 means all rows, 0 means none.
private final int nth;
// prefix printed row with its sequence number
private final boolean counted;
// prefix printed row with time it was fetched
private final boolean timestamped;
// print final summary, rows & elapsed time.
private final boolean totaled;
private long baseTime = 0;
private int rowCount = 0;
private int ncols = 0;
private int[] widths;
private String[] labels;
ResultsReader(BufferedWriter out) {
this(out, 1, false, false, false);
}
ResultsReader(
BufferedWriter out,
int nth, boolean counted, boolean timestamped, boolean totaled) {
this.out = new PrintWriter(out);
this.nth = nth;
this.counted = counted;
this.timestamped = timestamped;
this.totaled = totaled;
this.baseTime = scriptStartTime;
}
void prepareFormat(ResultSet rset) throws SQLException {
ResultSetMetaData meta = rset.getMetaData();
ncols = meta.getColumnCount();
widths = new int[ncols];
labels = new String[ncols];
for (int i = 0; i < ncols; i++) {
labels[i] = meta.getColumnLabel(i + 1);
int displaySize = meta.getColumnDisplaySize(i + 1);
// NOTE jvs 13-June-2006: I put this in to cap EXPLAIN PLAN,
// which now returns a very large worst-case display size.
if (displaySize > 4096) {
displaySize = 0;
}
widths[i] = Math.max(labels[i].length(), displaySize);
}
}
private void printHeaders() {
printSeparator();
indent();
printRow(labels);
printSeparator();
}
void read(ResultSet rset, long timeout) throws SQLException {
boolean withTimeout = timeout >= 0;
boolean timedOut = false;
long startTime = 0;
long endTime = 0;
try {
prepareFormat(rset);
String[] values = new String[ncols];
int printedRowCount = 0;
if (nth > 0) {
printHeaders();
}
startTime = System.currentTimeMillis();
for (rowCount = 0; rset.next(); rowCount++) {
if (nth == 0) {
continue;
}
if (nth == 1 || rowCount % nth == 0) {
long time = System.currentTimeMillis();
if (printedRowCount > 0
&& (printedRowCount % 100 == 0)) {
printHeaders();
}
for (int i = 0; i < ncols; i++) {
values[i] = rset.getString(i + 1);
}
if (counted) {
printRowCount(rowCount);
}
if (timestamped) {
printTimestamp(time);
}
printRow(values);
printedRowCount++;
}
}
} catch (SqlTimeoutException e) {
endTime = System.currentTimeMillis();
timedOut = true;
if (!withTimeout) {
throw e;
}
Util.swallow(e, null);
} catch (SQLException e) {
endTime = System.currentTimeMillis();
timedOut = true;
// 2007-10-23 hersker: hack to ignore timeout exceptions
// from other Farrago projects without being able to
// import/reference the actual exceptions
final String eClassName = e.getClass().getName();
if (eClassName.endsWith("TimeoutException")) {
if (!withTimeout) {
throw e;
}
Util.swallow(e, null);
} else {
Util.swallow(e, null);
out.println(e.getMessage());
}
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
} finally {
if (endTime == 0) {
endTime = System.currentTimeMillis();
}
rset.close();
if (nth > 0) {
printSeparator();
out.println();
}
if (verbose) {
out.printf(Locale.ROOT, "fetch started at %tc %d, %s at %tc %d%n",
startTime, startTime,
timedOut ? "timeout" : "eos",
endTime, endTime);
}
if (totaled) {
long dt = endTime - startTime;
if (withTimeout) {
dt -= timeout;
}
assert dt >= 0;
out.printf(Locale.ROOT, "fetched %d rows in %d msecs %s%n",
rowCount, dt, timedOut ? "(timeout)" : "(end)");
}
}
}
private void printRowCount(int count) {
out.printf(Locale.ROOT, "(%06d) ", count);
}
private void printTimestamp(long time) {
time -= baseTime;
out.printf(Locale.ROOT, "(% 4d.%03d) ", time / 1000, time % 1000);
}
// indent a heading or separator line to match a row-values line
private void indent() {
if (counted) {
out.print(" ");
}
if (timestamped) {
out.print(" ");
}
}
/**
* Prints an output table separator. Something like <code>
* "+----+--------+"</code>.
*/
private void printSeparator() {
indent();
for (int i = 0; i < widths.length; i++) {
if (i > 0) {
out.write("-+-");
} else {
out.write("+-");
}
int numDashes = widths[i];
while (numDashes > 0) {
out.write(
DASHES,
0,
Math.min(numDashes, BUF_SIZE));
numDashes -= Math.min(numDashes, BUF_SIZE);
}
}
out.println("-+");
}
/**
* Prints an output table row. Something like <code>"| COL1 | COL2
* |"</code>.
*/
private void printRow(String[] values) {
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value == null) {
value = "";
}
if (i > 0) {
out.write(" | ");
} else {
out.write("| ");
}
out.write(value);
int excess = widths[i] - value.length();
while (excess > 0) {
out.write(
SPACES,
0,
Math.min(excess, BUF_SIZE));
excess -= Math.min(excess, BUF_SIZE);
}
}
out.println(" |");
}
}
/** Standalone client test tool. */
private static class Tool {
boolean quiet = false; // -q
boolean verbose = false; // -v
boolean debug = false; // -g
String server; // -u
String driver; // -d
String user; // -n
String password; // -p
List<String> bindings; // VAR=VAL
List<String> files; // FILE
Tool() {
bindings = new ArrayList<>();
files = new ArrayList<>();
}
// returns 0 on success, 1 on error, 2 on bad invocation.
public int run(String[] args) {
try (PrintWriter w = Util.printWriter(System.out)) {
if (!parseCommand(args)) {
usage();
return 2;
}
Class z = Class.forName(driver); // load driver
Properties jdbcProps = new Properties();
if (user != null) {
jdbcProps.setProperty("user", user);
}
if (password != null) {
jdbcProps.setProperty("password", password);
}
for (String file : files) {
ConcurrentTestCommandScript script =
new ConcurrentTestCommandScript();
try {
script.setQuiet(quiet);
script.setVerbose(verbose);
script.setDebug(debug);
script.prepare(file, bindings);
script.setDataSource(server, jdbcProps);
script.execute();
} finally {
if (!quiet) {
script.printResults(w);
}
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
return 1;
}
return 0;
}
static void usage() {
System.err.println(
"Usage: mtsql [-vg] -u SERVER -d DRIVER "
+ "[-n USER][-p PASSWORD] SCRIPT [SCRIPT]...");
}
boolean parseCommand(String[] args) {
try {
// very permissive as to order
for (int i = 0; i < args.length;) {
String arg = args[i++];
if (arg.charAt(0) == '-') {
switch (arg.charAt(1)) {
case 'v':
verbose = true;
break;
case 'q':
quiet = true;
break;
case 'g':
debug = true;
break;
case 'u':
this.server = args[i++];
break;
case 'd':
this.driver = args[i++];
break;
case 'n':
this.user = args[i++];
break;
case 'p':
this.password = args[i++];
break;
default:
return false;
}
} else if (arg.contains("=")) {
if (Character.isJavaIdentifierStart(arg.charAt(0))) {
bindings.add(arg);
} else {
return false;
}
} else {
files.add(arg);
}
}
if (server == null || driver == null) {
return false;
}
} catch (Throwable th) {
return false;
}
return true;
}
}
/**
* Client tool that connects via jdbc and runs one or more mtsql on that
* connection.
*
* <p>Usage: mtsql [-vgq] -u SERVER -d DRIVER [-n USER][-p PASSWORD]
* [VAR=VAL]... SCRIPT [SCRIPT]...
*/
public static void main(String[] args) {
int status = new Tool().run(args);
Unsafe.systemExit(status);
}
}
| {
"content_hash": "b251569c9ab900cc6f8d8afffd6843a5",
"timestamp": "",
"source": "github",
"line_count": 2164,
"max_line_length": 81,
"avg_line_length": 30.805452865064694,
"alnum_prop": 0.5812369680332419,
"repo_name": "googleinterns/calcite",
"id": "c684ad78c4ebf2a2d41aeac872c5e7a0c6e86769",
"size": "67460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/org/apache/calcite/test/concurrent/ConcurrentTestCommandScript.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3674"
},
{
"name": "CSS",
"bytes": "36583"
},
{
"name": "FreeMarker",
"bytes": "359111"
},
{
"name": "HTML",
"bytes": "28321"
},
{
"name": "Java",
"bytes": "19344166"
},
{
"name": "Kotlin",
"bytes": "150911"
},
{
"name": "PigLatin",
"bytes": "1419"
},
{
"name": "Python",
"bytes": "1610"
},
{
"name": "Ruby",
"bytes": "1807"
},
{
"name": "Shell",
"bytes": "7078"
},
{
"name": "TSQL",
"bytes": "1761"
}
],
"symlink_target": ""
} |