text stringlengths 2 1.04M | meta dict |
|---|---|
/* eslint-env node, mocha */
import { assert } from 'chai';
import Joi from 'joi';
import EnumType from '../../src/datatypes/Enum';
describe('Enum datatype', () => {
it('asserts string value until values prop is defined', () => {
const dt = new EnumType();
const schema = dt.toJoi();
assert.doesNotThrow(() => Joi.assert('abc', schema));
assert.throws(() => Joi.assert(123, schema));
assert.throws(() => Joi.assert(1.1, schema));
assert.throws(() => Joi.assert(null, schema));
assert.throws(() => Joi.assert(true, schema));
assert.throws(() => Joi.assert({}, schema));
assert.throws(() => Joi.assert(new Date(), schema));
});
it('respects values property', () => {
const dt = new EnumType();
dt.values('a', 'b', 'c');
const schema = dt.toJoi();
assert.doesNotThrow(() => Joi.assert('a', schema));
assert.doesNotThrow(() => Joi.assert('b', schema));
assert.doesNotThrow(() => Joi.assert('c', schema));
assert.throws(() => Joi.assert('d', schema));
});
it('respects nullable property', () => {
const dt = new EnumType();
dt.nullable(true);
dt.values(['a', 'b', 'c']);
const schema = dt.toJoi();
assert.doesNotThrow(() => Joi.assert(null, schema));
assert.doesNotThrow(() => Joi.assert(undefined, schema));
});
it('respects default property', () => {
const dt = new EnumType();
dt.default('a');
dt.values(['a', 'b', 'c']);
const schema = dt.toJoi();
assert.strictEqual(Joi.attempt(undefined, schema), 'a');
});
describe('#values', () => {
it('accepts Array<string> or multiple string arguments', () => {
assert.doesNotThrow(() => new EnumType().values('a'));
assert.doesNotThrow(() => new EnumType().values('a', 'b', 'c'));
assert.doesNotThrow(() => new EnumType().values(['a', 'b', 'c']));
assert.throws(() => new EnumType().values(false));
assert.throws(() => new EnumType().values(123));
assert.throws(() => new EnumType().values(null));
assert.throws(() => new EnumType().values({}));
assert.throws(() => new EnumType().values());
});
});
describe('#nullable', () => {
it('accepts boolean value', () => {
assert.doesNotThrow(() => new EnumType().nullable(true));
assert.doesNotThrow(() => new EnumType().nullable(false));
assert.throws(() => new EnumType().nullable('abc'));
assert.throws(() => new EnumType().nullable(123));
assert.throws(() => new EnumType().nullable(null));
assert.throws(() => new EnumType().nullable({}));
assert.throws(() => new EnumType().nullable());
});
});
});
| {
"content_hash": "c3817c4765b7fba618d2f794aa9669c8",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 72,
"avg_line_length": 35.17333333333333,
"alnum_prop": 0.5727824109173616,
"repo_name": "jmike/naomi",
"id": "c63766816934d012bf2196759d5d4c9656079cf1",
"size": "2638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/datatypes/enum.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "257032"
}
],
"symlink_target": ""
} |
drop table if exists ctas_src;
drop table if exists ctas_dst;
create table ctas_src (domain integer, class integer, attr text, value integer) distributed by (domain);
insert into ctas_src values(1, 1, 'A', 1);
insert into ctas_src values(2, 1, 'A', 0);
insert into ctas_src values(3, 0, 'B', 1);
-- MPP-2859
create table ctas_dst as
SELECT attr, class, (select count(distinct class) from ctas_src) as dclass FROM ctas_src GROUP BY attr, class distributed by (attr);
drop table ctas_dst;
create table ctas_dst as
SELECT attr, class, (select max(class) from ctas_src) as maxclass FROM ctas_src GROUP BY attr, class distributed by (attr);
drop table ctas_dst;
create table ctas_dst as
SELECT attr, class, (select count(distinct class) from ctas_src) as dclass, (select max(class) from ctas_src) as maxclass, (select min(class) from ctas_src) as minclass FROM ctas_src GROUP BY attr, class distributed by (attr);
-- MPP-4298: "unknown" datatypes.
drop table if exists ctas_foo;
drop table if exists ctas_bar;
drop table if exists ctas_baz;
create table ctas_foo as select * from generate_series(1, 100);
create table ctas_bar as select a.generate_series as a, b.generate_series as b from ctas_foo a, ctas_foo b;
create table ctas_baz as select 'delete me' as action, * from ctas_bar;
-- "action" has no type.
\d ctas_baz
select action, b from ctas_baz order by 1,2 limit 5;
select action, b from ctas_baz order by 2 limit 5;
select action::text, b from ctas_baz order by 1,2 limit 5;
alter table ctas_baz alter column action type text;
\d ctas_baz
select action, b from ctas_baz order by 1,2 limit 5;
select action, b from ctas_baz order by 2 limit 5;
select action::text, b from ctas_baz order by 1,2 limit 5;
| {
"content_hash": "215ada8e7c1e4d216be999cd7a68eb5c",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 226,
"avg_line_length": 40.02325581395349,
"alnum_prop": 0.737361998837885,
"repo_name": "CraigHarris/gpdb",
"id": "fc07fa9c279f9924fc44c0a9f6254596b57e5b86",
"size": "1762",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/test/tinc/tincrepo/mpp/gpdb/tests/security/kerberos/sql/gpctas.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5196"
},
{
"name": "Batchfile",
"bytes": "11028"
},
{
"name": "C",
"bytes": "35172475"
},
{
"name": "C++",
"bytes": "8253554"
},
{
"name": "CMake",
"bytes": "47394"
},
{
"name": "CSS",
"bytes": "7068"
},
{
"name": "Csound Score",
"bytes": "179"
},
{
"name": "DTrace",
"bytes": "1160"
},
{
"name": "Fortran",
"bytes": "14777"
},
{
"name": "GDB",
"bytes": "576"
},
{
"name": "Gherkin",
"bytes": "928387"
},
{
"name": "HTML",
"bytes": "218703"
},
{
"name": "Java",
"bytes": "1011277"
},
{
"name": "Lex",
"bytes": "210708"
},
{
"name": "M4",
"bytes": "106028"
},
{
"name": "Makefile",
"bytes": "497812"
},
{
"name": "Objective-C",
"bytes": "7799"
},
{
"name": "PLSQL",
"bytes": "236252"
},
{
"name": "PLpgSQL",
"bytes": "53471803"
},
{
"name": "Perl",
"bytes": "4082990"
},
{
"name": "Perl6",
"bytes": "14219"
},
{
"name": "Python",
"bytes": "9788722"
},
{
"name": "Roff",
"bytes": "703079"
},
{
"name": "Ruby",
"bytes": "4910"
},
{
"name": "SQLPL",
"bytes": "3870842"
},
{
"name": "Shell",
"bytes": "504133"
},
{
"name": "XS",
"bytes": "8309"
},
{
"name": "XSLT",
"bytes": "5779"
},
{
"name": "Yacc",
"bytes": "485235"
}
],
"symlink_target": ""
} |
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use codemap::{BytePos, CharPos, CodeMap, Pos};
use diagnostic;
use parse::lexer::{is_whitespace, with_str_from, reader};
use parse::lexer::{StringReader, bump, is_eof, nextch, TokenAndSpan};
use parse::lexer::{is_line_non_doc_comment, is_block_non_doc_comment};
use parse::lexer;
use parse::token;
use parse::token::{get_ident_interner};
use std::io;
use std::str;
use std::uint;
#[deriving(Clone, Eq)]
pub enum cmnt_style {
isolated, // No code on either side of each line of the comment
trailing, // Code exists to the left of the comment
mixed, // Code before /* foo */ and after the comment
blank_line, // Just a manual blank line "\n\n", for layout
}
#[deriving(Clone)]
pub struct cmnt {
style: cmnt_style,
lines: ~[~str],
pos: BytePos
}
pub fn is_doc_comment(s: &str) -> bool {
(s.starts_with("///") && !is_line_non_doc_comment(s)) ||
s.starts_with("//!") ||
(s.starts_with("/**") && !is_block_non_doc_comment(s)) ||
s.starts_with("/*!")
}
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> ~str {
/// remove whitespace-only lines from the start/end of lines
fn vertical_trim(lines: ~[~str]) -> ~[~str] {
let mut i = 0u;
let mut j = lines.len();
// first line of all-stars should be omitted
if lines.len() > 0 && lines[0].chars().all(|c| c == '*') {
i += 1;
}
while i < j && lines[i].trim().is_empty() {
i += 1;
}
// like the first, a last line of all stars should be omitted
if j > i && lines[j - 1].chars().skip(1).all(|c| c == '*') {
j -= 1;
}
while j > i && lines[j - 1].trim().is_empty() {
j -= 1;
}
return lines.slice(i, j).to_owned();
}
/// remove a "[ \t]*\*" block from each line, if possible
fn horizontal_trim(lines: ~[~str]) -> ~[~str] {
let mut i = uint::max_value;
let mut can_trim = true;
let mut first = true;
for line in lines.iter() {
for (j, c) in line.chars().enumerate() {
if j > i || !"* \t".contains_char(c) {
can_trim = false;
break;
}
if c == '*' {
if first {
i = j;
first = false;
} else if i != j {
can_trim = false;
}
break;
}
}
if i > line.len() {
can_trim = false;
}
if !can_trim {
break;
}
}
if can_trim {
lines.map(|line| line.slice(i + 1, line.len()).to_owned())
} else {
lines
}
}
// one-line comments lose their prefix
static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
for prefix in ONLINERS.iter() {
if comment.starts_with(*prefix) {
return comment.slice_from(prefix.len()).to_owned();
}
}
if comment.starts_with("/*") {
let lines = comment.slice(3u, comment.len() - 2u)
.lines_any()
.map(|s| s.to_owned())
.collect::<~[~str]>();
let lines = vertical_trim(lines);
let lines = horizontal_trim(lines);
return lines.connect("\n");
}
fail!("not a doc-comment: {}", comment);
}
fn read_to_eol(rdr: @mut StringReader) -> ~str {
let mut val = ~"";
while rdr.curr != '\n' && !is_eof(rdr) {
val.push_char(rdr.curr);
bump(rdr);
}
if rdr.curr == '\n' { bump(rdr); }
return val;
}
fn read_one_line_comment(rdr: @mut StringReader) -> ~str {
let val = read_to_eol(rdr);
assert!((val[0] == '/' as u8 && val[1] == '/' as u8) ||
(val[0] == '#' as u8 && val[1] == '!' as u8));
return val;
}
fn consume_non_eol_whitespace(rdr: @mut StringReader) {
while is_whitespace(rdr.curr) && rdr.curr != '\n' && !is_eof(rdr) {
bump(rdr);
}
}
fn push_blank_line_comment(rdr: @mut StringReader, comments: &mut ~[cmnt]) {
debug!(">>> blank-line comment");
let v: ~[~str] = ~[];
comments.push(cmnt {style: blank_line, lines: v, pos: rdr.last_pos});
}
fn consume_whitespace_counting_blank_lines(rdr: @mut StringReader,
comments: &mut ~[cmnt]) {
while is_whitespace(rdr.curr) && !is_eof(rdr) {
if rdr.col == CharPos(0u) && rdr.curr == '\n' {
push_blank_line_comment(rdr, &mut *comments);
}
bump(rdr);
}
}
fn read_shebang_comment(rdr: @mut StringReader, code_to_the_left: bool,
comments: &mut ~[cmnt]) {
debug!(">>> shebang comment");
let p = rdr.last_pos;
debug!("<<< shebang comment");
comments.push(cmnt {
style: if code_to_the_left { trailing } else { isolated },
lines: ~[read_one_line_comment(rdr)],
pos: p
});
}
fn read_line_comments(rdr: @mut StringReader, code_to_the_left: bool,
comments: &mut ~[cmnt]) {
debug!(">>> line comments");
let p = rdr.last_pos;
let mut lines: ~[~str] = ~[];
while rdr.curr == '/' && nextch(rdr) == '/' {
let line = read_one_line_comment(rdr);
debug!("{}", line);
if is_doc_comment(line) { // doc-comments are not put in comments
break;
}
lines.push(line);
consume_non_eol_whitespace(rdr);
}
debug!("<<< line comments");
if !lines.is_empty() {
comments.push(cmnt {
style: if code_to_the_left { trailing } else { isolated },
lines: lines,
pos: p
});
}
}
// Returns None if the first col chars of s contain a non-whitespace char.
// Otherwise returns Some(k) where k is first char offset after that leading
// whitespace. Note k may be outside bounds of s.
fn all_whitespace(s: &str, col: CharPos) -> Option<uint> {
let len = s.len();
let mut col = col.to_uint();
let mut cursor: uint = 0;
while col > 0 && cursor < len {
let r: str::CharRange = s.char_range_at(cursor);
if !r.ch.is_whitespace() {
return None;
}
cursor = r.next;
col -= 1;
}
return Some(cursor);
}
fn trim_whitespace_prefix_and_push_line(lines: &mut ~[~str],
s: ~str, col: CharPos) {
let len = s.len();
let s1 = match all_whitespace(s, col) {
Some(col) => {
if col < len {
s.slice(col, len).to_owned()
} else { ~"" }
}
None => s,
};
debug!("pushing line: {}", s1);
lines.push(s1);
}
fn read_block_comment(rdr: @mut StringReader,
code_to_the_left: bool,
comments: &mut ~[cmnt]) {
debug!(">>> block comment");
let p = rdr.last_pos;
let mut lines: ~[~str] = ~[];
let col: CharPos = rdr.col;
bump(rdr);
bump(rdr);
let mut curr_line = ~"/*";
// doc-comments are not really comments, they are attributes
if rdr.curr == '*' || rdr.curr == '!' {
while !(rdr.curr == '*' && nextch(rdr) == '/') && !is_eof(rdr) {
curr_line.push_char(rdr.curr);
bump(rdr);
}
if !is_eof(rdr) {
curr_line.push_str("*/");
bump(rdr);
bump(rdr);
}
if !is_block_non_doc_comment(curr_line) { return; }
assert!(!curr_line.contains_char('\n'));
lines.push(curr_line);
} else {
let mut level: int = 1;
while level > 0 {
debug!("=== block comment level {}", level);
if is_eof(rdr) {
(rdr as @mut reader).fatal(~"unterminated block comment");
}
if rdr.curr == '\n' {
trim_whitespace_prefix_and_push_line(&mut lines, curr_line,
col);
curr_line = ~"";
bump(rdr);
} else {
curr_line.push_char(rdr.curr);
if rdr.curr == '/' && nextch(rdr) == '*' {
bump(rdr);
bump(rdr);
curr_line.push_char('*');
level += 1;
} else {
if rdr.curr == '*' && nextch(rdr) == '/' {
bump(rdr);
bump(rdr);
curr_line.push_char('/');
level -= 1;
} else { bump(rdr); }
}
}
}
if curr_line.len() != 0 {
trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col);
}
}
let mut style = if code_to_the_left { trailing } else { isolated };
consume_non_eol_whitespace(rdr);
if !is_eof(rdr) && rdr.curr != '\n' && lines.len() == 1u {
style = mixed;
}
debug!("<<< block comment");
comments.push(cmnt {style: style, lines: lines, pos: p});
}
fn peeking_at_comment(rdr: @mut StringReader) -> bool {
return ((rdr.curr == '/' && nextch(rdr) == '/') ||
(rdr.curr == '/' && nextch(rdr) == '*')) ||
(rdr.curr == '#' && nextch(rdr) == '!');
}
fn consume_comment(rdr: @mut StringReader,
code_to_the_left: bool,
comments: &mut ~[cmnt]) {
debug!(">>> consume comment");
if rdr.curr == '/' && nextch(rdr) == '/' {
read_line_comments(rdr, code_to_the_left, comments);
} else if rdr.curr == '/' && nextch(rdr) == '*' {
read_block_comment(rdr, code_to_the_left, comments);
} else if rdr.curr == '#' && nextch(rdr) == '!' {
read_shebang_comment(rdr, code_to_the_left, comments);
} else { fail!(); }
debug!("<<< consume comment");
}
#[deriving(Clone)]
pub struct lit {
lit: ~str,
pos: BytePos
}
// it appears this function is called only from pprust... that's
// probably not a good thing.
pub fn gather_comments_and_literals(span_diagnostic:
@mut diagnostic::span_handler,
path: @str,
srdr: &mut io::Reader)
-> (~[cmnt], ~[lit]) {
let src = str::from_utf8_owned(srdr.read_to_end()).to_managed();
let cm = CodeMap::new();
let filemap = cm.new_filemap(path, src);
let rdr = lexer::new_low_level_string_reader(span_diagnostic, filemap);
let mut comments: ~[cmnt] = ~[];
let mut literals: ~[lit] = ~[];
let mut first_read: bool = true;
while !is_eof(rdr) {
loop {
let mut code_to_the_left = !first_read;
consume_non_eol_whitespace(rdr);
if rdr.curr == '\n' {
code_to_the_left = false;
consume_whitespace_counting_blank_lines(rdr, &mut comments);
}
while peeking_at_comment(rdr) {
consume_comment(rdr, code_to_the_left, &mut comments);
consume_whitespace_counting_blank_lines(rdr, &mut comments);
}
break;
}
let bstart = rdr.last_pos;
rdr.next_token();
//discard, and look ahead; we're working with internal state
let TokenAndSpan {tok: tok, sp: sp} = rdr.peek();
if token::is_lit(&tok) {
with_str_from(rdr, bstart, |s| {
debug!("tok lit: {}", s);
literals.push(lit {lit: s.to_owned(), pos: sp.lo});
})
} else {
debug!("tok: {}", token::to_str(get_ident_interner(), &tok));
}
first_read = false;
}
(comments, literals)
}
#[cfg(test)]
mod test {
use super::*;
#[test] fn test_block_doc_comment_1() {
let comment = "/**\n * Test \n ** Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, ~" Test \n* Test\n Test");
}
#[test] fn test_block_doc_comment_2() {
let comment = "/**\n * Test\n * Test\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, ~" Test\n Test");
}
#[test] fn test_block_doc_comment_3() {
let comment = "/**\n let a: *int;\n *a = 5;\n*/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, ~" let a: *int;\n *a = 5;");
}
#[test] fn test_block_doc_comment_4() {
let comment = "/*******************\n test\n *********************/";
let stripped = strip_doc_comment_decoration(comment);
assert_eq!(stripped, ~" test");
}
#[test] fn test_line_doc_comment() {
let stripped = strip_doc_comment_decoration("/// test");
assert_eq!(stripped, ~" test");
let stripped = strip_doc_comment_decoration("///! test");
assert_eq!(stripped, ~" test");
let stripped = strip_doc_comment_decoration("// test");
assert_eq!(stripped, ~" test");
let stripped = strip_doc_comment_decoration("// test");
assert_eq!(stripped, ~" test");
let stripped = strip_doc_comment_decoration("///test");
assert_eq!(stripped, ~"test");
let stripped = strip_doc_comment_decoration("///!test");
assert_eq!(stripped, ~"test");
let stripped = strip_doc_comment_decoration("//test");
assert_eq!(stripped, ~"test");
}
}
| {
"content_hash": "98b40f334defec0ca51147f0419ad26f",
"timestamp": "",
"source": "github",
"line_count": 435,
"max_line_length": 77,
"avg_line_length": 32.726436781609195,
"alnum_prop": 0.4952936218038775,
"repo_name": "fabricedesre/rust",
"id": "0704bf913d7c419d1f1f35d735b653f26ac0f6dd",
"size": "14236",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/libsyntax/parse/comments.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "20065"
},
{
"name": "C",
"bytes": "526873"
},
{
"name": "C++",
"bytes": "33090"
},
{
"name": "CSS",
"bytes": "12875"
},
{
"name": "Emacs Lisp",
"bytes": "34614"
},
{
"name": "JavaScript",
"bytes": "42047"
},
{
"name": "Perl",
"bytes": "619"
},
{
"name": "Puppet",
"bytes": "5358"
},
{
"name": "Python",
"bytes": "48672"
},
{
"name": "Rust",
"bytes": "11603116"
},
{
"name": "Shell",
"bytes": "2065"
},
{
"name": "VimL",
"bytes": "22082"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> RiveScript </title>
</head>
<frameset cols="20%,80%">
<frameset rows="30%,70%">
<frame src="toc.html" name="moduleListFrame"
id="moduleListFrame" />
<frame src="toc-everything.html" name="moduleFrame"
id="moduleFrame" />
</frameset>
<frame src="module-tree.html" name="mainFrame" id="mainFrame" />
</frameset>
</html>
| {
"content_hash": "5fab8727ac0ee7cba71c7341a2d95dbd",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 67,
"avg_line_length": 34.05882352941177,
"alnum_prop": 0.6269430051813472,
"repo_name": "plasmashadow/rivescript-python",
"id": "43120bc34c7a57fc627f97f0475c282e48d98402",
"size": "579",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "docs/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Perl",
"bytes": "1319"
},
{
"name": "Python",
"bytes": "143669"
},
{
"name": "Shell",
"bytes": "280"
}
],
"symlink_target": ""
} |
.class Lcom/nianticlabs/nia/iap/NianticBillingManager$4;
.super Ljava/lang/Object;
.source "NianticBillingManager.java"
# interfaces
.implements Ljava/lang/Runnable;
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Lcom/nianticlabs/nia/iap/NianticBillingManager;->redeemReceiptResult(ZLjava/lang/String;)V
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/nianticlabs/nia/iap/NianticBillingManager;
.field final synthetic val$success:Z
.field final synthetic val$transactionToken:Ljava/lang/String;
# direct methods
.method constructor <init>(Lcom/nianticlabs/nia/iap/NianticBillingManager;ZLjava/lang/String;)V
.registers 4
.param p1, "this$0" # Lcom/nianticlabs/nia/iap/NianticBillingManager;
.prologue
.line 80
iput-object p1, p0, Lcom/nianticlabs/nia/iap/NianticBillingManager$4;->this$0:Lcom/nianticlabs/nia/iap/NianticBillingManager;
iput-boolean p2, p0, Lcom/nianticlabs/nia/iap/NianticBillingManager$4;->val$success:Z
iput-object p3, p0, Lcom/nianticlabs/nia/iap/NianticBillingManager$4;->val$transactionToken:Ljava/lang/String;
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public run()V
.registers 4
.prologue
.line 83
iget-object v0, p0, Lcom/nianticlabs/nia/iap/NianticBillingManager$4;->this$0:Lcom/nianticlabs/nia/iap/NianticBillingManager;
# getter for: Lcom/nianticlabs/nia/iap/NianticBillingManager;->inAppBillingProvider:Lcom/nianticlabs/nia/iap/InAppBillingProvider;
invoke-static {v0}, Lcom/nianticlabs/nia/iap/NianticBillingManager;->access$100(Lcom/nianticlabs/nia/iap/NianticBillingManager;)Lcom/nianticlabs/nia/iap/InAppBillingProvider;
move-result-object v0
iget-boolean v1, p0, Lcom/nianticlabs/nia/iap/NianticBillingManager$4;->val$success:Z
iget-object v2, p0, Lcom/nianticlabs/nia/iap/NianticBillingManager$4;->val$transactionToken:Ljava/lang/String;
invoke-interface {v0, v1, v2}, Lcom/nianticlabs/nia/iap/InAppBillingProvider;->onProcessedGoogleBillingTransaction(ZLjava/lang/String;)V
.line 84
return-void
.end method
| {
"content_hash": "88436c037be01c53552cd3fbf2d94e84",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 178,
"avg_line_length": 33.38235294117647,
"alnum_prop": 0.7731277533039648,
"repo_name": "shenxdtw/PokemonGo-Plugin",
"id": "1fa2d9d9b8798cb9da33b8ec6ea5c34b20037e2b",
"size": "2270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PokemonGo_Smali/com/nianticlabs/nia/iap/NianticBillingManager$4.smali",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Smali",
"bytes": "35925787"
}
],
"symlink_target": ""
} |
A simple Python 3 library for converting Spline Font Database files to Python bytes
| {
"content_hash": "eb2fcc435c53c562dbf9a6d8e4684d15",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 83,
"avg_line_length": 84,
"alnum_prop": 0.8333333333333334,
"repo_name": "mmabey/py-spline-to-bytes",
"id": "58dfe3a3ba0af83ea9508a28efd926fcc7874c91",
"size": "105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""A parser for Relay's text format."""
from __future__ import absolute_import
import sys
from collections import deque
from typing import TypeVar, Deque, Tuple, Optional, Union, NamedTuple, List, Callable, Any, Dict
import tvm
from . import module
from .base import Span, SourceName
from . import expr
from . import ty
from . import op
class ParseError(Exception):
"""Exception type for parse errors."""
def __init__(self, message):
# type: (str) -> None
super(ParseError, self).__init__()
self.message = message
PYTHON_VERSION = sys.version_info.major
try:
from .grammar.py3.RelayVisitor import RelayVisitor
from .grammar.py3.RelayParser import RelayParser
from .grammar.py3.RelayLexer import RelayLexer
except ImportError:
raise ParseError("Couldn't find ANTLR parser. Try building with USE_ANTLR=ON.")
try:
from antlr4 import ParserRuleContext, InputStream, CommonTokenStream
from antlr4.tree.Tree import TerminalNode
except ImportError:
raise ParseError("Couldn't find ANTLR runtime." +
"Try running `pip{version} install antlr4-python{version}-runtime`."
.format(version=PYTHON_VERSION))
BINARY_OPS = {
RelayParser.MUL: op.multiply,
RelayParser.DIV: op.divide,
RelayParser.ADD: op.add,
RelayParser.SUB: op.subtract,
RelayParser.LT: op.less,
RelayParser.GT: op.greater,
RelayParser.LE: op.less_equal,
RelayParser.GE: op.greater_equal,
RelayParser.EQ: op.equal,
RelayParser.NE: op.not_equal,
}
TYPE_PREFIXES = [
"int",
"uint",
"float",
"bool",
]
T = TypeVar("T")
Scope = Deque[Tuple[str, T]]
Scopes = Deque[Scope[T]]
def lookup(scopes, name):
# type: (Scopes[T], str) -> Optional[T]
"""Look up `name` in `scopes`."""
for scope in scopes:
for key, val in scope:
if key == name:
return val
return None
def spanify(f):
"""A decorator which attaches span information
to the value returned by calling `f`.
Intended for use with the below AST visiting
methods. The idea is that after we do the work
of constructing the AST we attach Span information.
"""
def _wrapper(*args, **kwargs):
# Assumes 0th arg is self and gets source_name from object.
sn = args[0].source_name
# Assumes 1st arg is an ANTLR parser context.
ctx = args[1]
ast = f(*args, **kwargs)
line, col = ctx.getSourceInterval()
sp = Span(sn, line, col)
ast.set_span(sp)
return ast
return _wrapper
# TODO(@jmp): Use https://stackoverflow.com/q/13889941
# to figure out how to get ANTLR4 to be more unhappy about syntax errors
class ParseTreeToRelayIR(RelayVisitor):
"""Parse Relay text format into Relay IR."""
def __init__(self, source_name):
# type: (str) -> None
self.source_name = source_name
self.module = module.Module({}) # type: module.Module
# Adding an empty scope allows naked lets without pain.
self.var_scopes = deque([deque()]) # type: Scopes[expr.Var]
self.global_var_scope = deque() # type: Scope[expr.GlobalVar]
self.type_param_scopes = deque([deque()]) # type: Scopes[ty.TypeVar]
self.graph_expr = [] # type: List[expr.Expr]
super(ParseTreeToRelayIR, self).__init__()
def enter_var_scope(self):
# type: () -> None
"""Enter a new Var scope so it can be popped off later."""
self.var_scopes.appendleft(deque())
def exit_var_scope(self):
# type: () -> Scope[expr.Var]
"""Pop off the current Var scope and return it."""
return self.var_scopes.popleft()
def mk_var(self, name, type_):
# type: (str, ty.Type) -> expr.Var
"""Create a new Var and add it to the Var scope."""
var = expr.Var(name, type_)
self.var_scopes[0].appendleft((name, var))
return var
def mk_global_var(self, name):
# type: (str) -> expr.GlobalVar
"""Create a new GlobalVar and add it to the GlobalVar scope."""
var = expr.GlobalVar(name)
self.global_var_scope.append((name, var))
return var
def enter_type_param_scope(self):
# type: () -> None
"""Enter a new TypeVar scope so it can be popped off later."""
self.type_param_scopes.appendleft(deque())
def exit_type_param_scope(self):
# type: () -> Scope[ty.TypeVar]
"""Pop off the current TypeVar scope and return it."""
return self.type_param_scopes.popleft()
def mk_typ(self, name, kind):
# (str, ty.Kind) -> ty.TypeVar
"""Create a new TypeVar and add it to the TypeVar scope."""
typ = ty.TypeVar(name, kind)
self.type_param_scopes[0].appendleft((name, typ))
return typ
def visitTerminal(self, node):
# type: (TerminalNode) -> Union[expr.Expr, int, float]
"""Visit lexer tokens that aren't ignored or visited by other functions."""
node_type = node.getSymbol().type
node_text = node.getText()
name = node_text[1:]
# variables
if node_type == RelayLexer.GLOBAL_VAR:
return lookup(deque([self.global_var_scope]), node_text[1:])
if node_type == RelayLexer.LOCAL_VAR:
# Remove the leading '%' and lookup the name.
var = lookup(self.var_scopes, name)
if var is None:
raise ParseError("Couldn't resolve `{}`.".format(name))
return var
if node_type == RelayLexer.GRAPH_VAR:
try:
return self.graph_expr[int(name)]
except IndexError:
raise ParseError("Couldn't resolve `{}`".format(name))
# data types
if node_type == RelayLexer.NAT:
return int(node_text)
if node_type == RelayLexer.FLOAT:
return float(node_text[:-1])
if node_type == RelayLexer.BOOL_LIT:
if node_text == "True":
return True
if node_text == "False":
return False
raise ParseError("Unrecognized BOOL_LIT: `{}`".format(node_text))
raise ParseError("todo: {}".format(node_text))
def visit_list(self, ctx_list):
# type: (List[ParserRuleContext]) -> List[Any]
""""Visit a list of contexts."""
return [self.visit(ctx) for ctx in ctx_list]
def getType_(self, ctx):
# type: (Optional[RelayParser.Type_Context]) -> Optional[ty.Type]
"""Return a (possibly None) Relay type."""
if ctx is None:
return None
return self.visit(ctx)
def visitProg(self, ctx):
# type: (RelayParser.ProgContext) -> Union[expr.Expr, module.Module]
if ctx.defn():
self.visit_list(ctx.defn())
return self.module
if ctx.expr():
return self.visit(ctx.expr())
return self.module
# Exprs
def visitOpIdent(self, ctx):
# type: (RelayParser.OpIdentContext) -> op.Op
return op.get(ctx.CNAME().getText())
# pass through
def visitParens(self, ctx):
# type: (RelayParser.ParensContext) -> expr.Expr
return self.visit(ctx.expr())
# pass through
def visitBody(self, ctx):
# type: (RelayParser.BodyContext) -> expr.Expr
return self.visit(ctx.expr())
def visitScalarFloat(self, ctx):
# type: (RelayParser.ScalarFloatContext) -> expr.Constant
return expr.const(self.visit(ctx.FLOAT()))
def visitScalarInt(self, ctx):
# type: (RelayParser.ScalarIntContext) -> expr.Constant
return expr.const(self.visit(ctx.NAT()))
def visitScalarBool(self, ctx):
# type: (RelayParser.ScalarBoolContext) -> expr.Constant
return expr.const(self.visit(ctx.BOOL_LIT()))
def visitNeg(self, ctx):
# type: (RelayParser.NegContext) -> Union[expr.Constant, expr.Call]
val = self.visit(ctx.expr())
if isinstance(val, expr.Constant) and val.data.asnumpy().ndim == 0:
# fold Neg in for scalars
return expr.const(-val.data.asnumpy().item())
return op.negative(val)
def visitTuple(self, ctx):
# type: (RelayParser.TupleContext) -> expr.Tuple
tup = self.visit_list(ctx.expr())
return expr.Tuple(tup)
# Currently doesn't support mutable sequencing.
def visitLet(self, ctx):
# type: (RelayParser.SeqContext) -> expr.Let
"""Desugar various sequence constructs to Relay Let nodes."""
if ctx.MUT() is not None:
raise ParseError("Mutation is currently unsupported.")
if ctx.var() is None or ctx.var().ident() is None:
# anonymous identity
ident = "_"
type_ = None
else:
local_var = ctx.var().ident().LOCAL_VAR()
if local_var is None:
raise ParseError("Only local ids may be used in `let`s.")
ident = local_var.getText()[1:]
type_ = self.getType_(ctx.var().type_())
var = self.mk_var(ident, type_)
self.enter_var_scope()
value = self.visit(ctx.expr(0))
self.exit_var_scope()
body = self.visit(ctx.expr(1))
return expr.Let(var, value, body)
def visitBinOp(self, ctx):
# type: (RelayParser.BinOpContext) -> expr.Call
"""Desugar binary operators."""
arg0, arg1 = self.visit_list(ctx.expr())
relay_op = BINARY_OPS.get(ctx.op.type)
if relay_op is None:
raise ParseError("Unimplemented binary op.")
return relay_op(arg0, arg1)
@spanify
def visitVar(self, ctx):
# type: (RelayParser.VarContext) -> expr.Var
"""Visit a single variable."""
ident = ctx.ident().LOCAL_VAR()
if ident is None:
raise ParseError("Only local ids may be used in vars.")
type_ = self.getType_(ctx.type_())
return self.mk_var(ident.getText()[1:], type_)
def visitVarList(self, ctx):
# type: (RelayParser.VarListContext) -> List[expr.Var]
return self.visit_list(ctx.var())
# TODO: support a larger class of values than just Relay exprs
def visitAttr(self, ctx):
# type: (RelayParser.AttrContext) -> Tuple[str, expr.Expr]
return (ctx.CNAME().getText(), self.visit(ctx.expr()))
def visitAttrList(self, ctx):
# type: (RelayParser.AttrListContext) -> Dict[str, expr.Expr]
return dict(self.visit_list(ctx.attr()))
def visitArgList(self,
ctx # type: RelayParser.ArgListContext
):
# type: (...) -> Tuple[Optional[List[expr.Var]], Optional[Dict[str, expr.Expr]]]
var_list = self.visit(ctx.varList()) if ctx.varList() else None
attr_list = self.visit(ctx.attrList()) if ctx.attrList() else None
return (var_list, attr_list)
def mk_func(self, ctx):
# type: (Union[RelayParser.FuncContext, RelayParser.DefnContext]) -> expr.Function
"""Construct a function from either a Func or Defn."""
# Enter var scope early to put params in scope.
self.enter_var_scope()
# Capture type params in params.
self.enter_type_param_scope()
type_params = ctx.typeParamSeq()
if type_params is not None:
type_params = type_params.ident()
assert type_params
for ty_param in type_params:
name = ty_param.getText()
self.mk_typ(name, ty.Kind.Type)
var_list, attr_list = self.visit(ctx.argList())
if var_list is None:
var_list = []
ret_type = self.getType_(ctx.type_())
body = self.visit(ctx.body())
# NB(@jroesch): you must stay in the type parameter scope until
# after you exit the body, you can reference the type parameters
# of your parent scopes.
type_params = list(self.exit_type_param_scope())
if type_params:
_, type_params = zip(*type_params)
self.exit_var_scope()
attrs = tvm.make.node("DictAttrs", **attr_list) if attr_list is not None else None
return expr.Function(var_list, body, ret_type, type_params, attrs)
@spanify
def visitFunc(self, ctx):
# type: (RelayParser.FuncContext) -> expr.Function
return self.mk_func(ctx)
# TODO: how to set spans for definitions?
# @spanify
def visitDefn(self, ctx):
# type: (RelayParser.DefnContext) -> None
ident = ctx.ident().GLOBAL_VAR()
if ident is None:
raise ParseError("Only global ids may be used in `def`s.")
ident_name = ident.getText()[1:]
ident = self.mk_global_var(ident_name)
self.module[ident] = self.mk_func(ctx)
@spanify
def visitCall(self, ctx):
# type: (RelayParser.CallContext) -> expr.Call
visited_exprs = self.visit_list(ctx.expr())
func = visited_exprs[0]
args = visited_exprs[1:]
return expr.Call(func, args, None, None)
@spanify
def visitIfElse(self, ctx):
# type: (RelayParser.IfElseContext) -> expr.If
"""Construct a Relay If node. Creates a new scope for each branch."""
cond = self.visit(ctx.expr())
self.enter_var_scope()
true_branch = self.visit(ctx.body(0))
self.exit_var_scope()
self.enter_var_scope()
false_branch = self.visit(ctx.body(1))
self.exit_var_scope()
return expr.If(cond, true_branch, false_branch)
@spanify
def visitGraph(self, ctx):
# type: (RelayParser.GraphContext) -> expr.Expr
"""Visit a graph variable assignment."""
if ctx.ident().GRAPH_VAR() is None:
raise ParseError("Expected a graph var, but got `{}`".format(ctx.ident().getText()))
graph_nid = int(ctx.ident().GRAPH_VAR().getText()[1:])
self.enter_var_scope()
value = self.visit(ctx.expr(0))
self.exit_var_scope()
if graph_nid != len(self.graph_expr):
raise ParseError(
"Expected new graph variable to be `%{}`,".format(len(self.graph_expr)) + \
"but got `%{}`".format(graph_nid))
self.graph_expr.append(value)
kont = self.visit(ctx.expr(1))
return kont
# Types
# pylint: disable=unused-argument
def visitIncompleteType(self, ctx):
# type (RelayParser.IncompleteTypeContext) -> None:
return None
def visitTypeIdent(self, ctx):
# type: (RelayParser.TypeIdentContext) -> Union[ty.TensorType, str]
'''
Handle type identifier.
'''
type_ident = ctx.CNAME().getText()
# Look through all type prefixes for a match
for type_prefix in TYPE_PREFIXES:
if type_ident.startswith(type_prefix):
return ty.scalar_type(type_ident)
type_param = lookup(self.type_param_scopes, type_ident)
if type_param is not None:
return type_param
raise ParseError("Unknown builtin type: {}".format(type_ident))
# def visitCallType(self, ctx):
# # type: (RelayParser.CallTypeContext) -> Union[expr.Expr, ty.TensorType]
# ident_type = ctx.identType().CNAME().getText()
# args = self.visit_list(ctx.type_())
# if not args:
# raise ParseError("Type-level functions must have arguments!")
# func_type = TYPE_FUNCS.get(ident_type)(args)
# if func_type is None:
# raise ParseError("Unknown type-level function: `{}`".format(ident_type))
# else:
# return func_type
def visitParensShape(self, ctx):
# type: (RelayParser.ParensShapeContext) -> int
return self.visit(ctx.shape())
def visitShapeSeq(self, ctx):
# type: (RelayParser.ShapeSeqContext) -> List[int]
return self.visit_list(ctx.shape())
def visitTensorType(self, ctx):
# type: (RelayParser.TensorTypeContext) -> ty.TensorType
"""Create a simple tensor type. No generics."""
shape = self.visit(ctx.shapeSeq())
dtype = self.visit(ctx.type_())
if not isinstance(dtype, ty.TensorType):
raise ParseError("Expected dtype to be a Relay base type.")
dtype = dtype.dtype
return ty.TensorType(shape, dtype)
def visitTupleType(self, ctx):
# type: (RelayParser.TupleTypeContext) -> ty.TupleType
return ty.TupleType(self.visit_list(ctx.type_()))
def visitFuncType(self, ctx):
# type: (RelayParser.FuncTypeContext) -> ty.FuncType
types = self.visit_list(ctx.type_())
arg_types = types[:-1]
ret_type = types[-1]
return ty.FuncType(arg_types, ret_type, [], None)
def make_parser(data):
# type: (str) -> RelayParser
"""Construct a RelayParser a given data stream."""
input_stream = InputStream(data)
lexer = RelayLexer(input_stream)
token_stream = CommonTokenStream(lexer)
return RelayParser(token_stream)
__source_name_counter__ = 0
def fromtext(data, source_name=None):
# type: (str, str) -> Union[expr.Expr, module.Module]
"""Parse a Relay program."""
if data == "":
raise ParseError("Cannot parse the empty string.")
global __source_name_counter__
if source_name is None:
source_name = "source_file{0}".format(__source_name_counter__)
if isinstance(source_name, str):
source_name = SourceName(source_name)
tree = make_parser(data).prog()
return ParseTreeToRelayIR(source_name).visit(tree)
| {
"content_hash": "96b15183cb7eaaca3e589daee1dec7a7",
"timestamp": "",
"source": "github",
"line_count": 541,
"max_line_length": 96,
"avg_line_length": 32.724584103512015,
"alnum_prop": 0.5960799819249887,
"repo_name": "mlperf/training_results_v0.7",
"id": "c483f4f75900d92d05812f2501ab03d238586c36",
"size": "18536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/python/tvm/relay/_parser.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Awk",
"bytes": "14530"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "172914"
},
{
"name": "C++",
"bytes": "13037795"
},
{
"name": "CMake",
"bytes": "113458"
},
{
"name": "CSS",
"bytes": "70255"
},
{
"name": "Clojure",
"bytes": "622652"
},
{
"name": "Cuda",
"bytes": "1974745"
},
{
"name": "Dockerfile",
"bytes": "149523"
},
{
"name": "Groovy",
"bytes": "160449"
},
{
"name": "HTML",
"bytes": "171537"
},
{
"name": "Java",
"bytes": "189275"
},
{
"name": "JavaScript",
"bytes": "98224"
},
{
"name": "Julia",
"bytes": "430755"
},
{
"name": "Jupyter Notebook",
"bytes": "11091342"
},
{
"name": "Lua",
"bytes": "17720"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "215967"
},
{
"name": "Perl",
"bytes": "1551186"
},
{
"name": "PowerShell",
"bytes": "13906"
},
{
"name": "Python",
"bytes": "36943114"
},
{
"name": "R",
"bytes": "134921"
},
{
"name": "Raku",
"bytes": "7280"
},
{
"name": "Ruby",
"bytes": "4930"
},
{
"name": "SWIG",
"bytes": "140111"
},
{
"name": "Scala",
"bytes": "1304960"
},
{
"name": "Shell",
"bytes": "1312832"
},
{
"name": "Smalltalk",
"bytes": "3497"
},
{
"name": "Starlark",
"bytes": "69877"
},
{
"name": "TypeScript",
"bytes": "243012"
}
],
"symlink_target": ""
} |
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css({.tmp,app}) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
</head>
<body ng-app="yomanApp">
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="container" ng-view=""></div>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-X');
ga('send', 'pageview');
</script>
<!--[if lt IE 9]>
<script src="bower_components/es5-shim/es5-shim.js"></script>
<script src="bower_components/json3/lib/json3.min.js"></script>
<![endif]-->
<!-- build:js scripts/vendor.js -->
<!-- bower:js -->
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-cookies/angular-cookies.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/lodash/dist/lodash.compat.js"></script>
<script src="bower_components/restangular/dist/restangular.min.js"></script>
<!-- endbower -->
<!-- endbuild -->
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<!-- endbuild -->
</body>
</html>
| {
"content_hash": "5f3f09bda34f5110b98fbc46fb8335a0",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 178,
"avg_line_length": 45.01538461538462,
"alnum_prop": 0.6103896103896104,
"repo_name": "jiwhiz/CIExample",
"id": "ef18863df42f29b489ef320be8c2397b74a400f6",
"size": "2926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/webapp/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1411"
},
{
"name": "Java",
"bytes": "5675"
},
{
"name": "JavaScript",
"bytes": "600"
}
],
"symlink_target": ""
} |
package org.springframework.cloud.dataflow.server.service;
import java.util.List;
import java.util.Map;
import org.springframework.cloud.dataflow.core.StreamDefinition;
import org.springframework.cloud.dataflow.core.StreamDeployment;
import org.springframework.cloud.dataflow.server.controller.support.InvalidStreamDefinitionException;
import org.springframework.cloud.dataflow.server.repository.NoSuchStreamDefinitionException;
import org.springframework.cloud.deployer.spi.app.DeploymentState;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/**
* Provide deploy, undeploy, info and state operations on the stream.
*
* @author Mark Pollack
* @author Ilayaperumal Gopinathan
* @author Christian Tzolov
* @author Glenn Renfro
*/
public interface StreamService {
/**
* Create a new stream.
*
* @param streamName stream name
* @param dsl DSL definition for stream
* @param deploy if {@code true}, the stream is deployed upon creation (default is
* {@code false})
* @return the created stream definition already exists
* @throws InvalidStreamDefinitionException if there are errors in parsing the stream DSL,
* resolving the name, or type of applications in the stream
*/
StreamDefinition createStream(String streamName, String dsl, boolean deploy);
/**
* Deploys the stream with the user provided deployment properties.
* Implementations are responsible for expanding deployment wildcard expressions.
* @param name the name of the stream
* @param deploymentProperties deployment properties to use as passed in from the client.
*/
void deployStream(String name, Map<String, String> deploymentProperties);
/**
* Un-deploys the stream identified by the given stream name.
*
* @param name the name of the stream to un-deploy
*/
void undeployStream(String name);
/**
* Delete the stream, including undeloying.
* @param name the name of the stream to delete
*/
void deleteStream(String name);
/**
* Delete all streams, including undeploying.
*/
void deleteAll();
/**
* Retrieve the deployment state for list of stream definitions.
*
* @param streamDefinitions the list of Stream definitions to calculate the deployment states.
* @return the map containing the stream definitions and their deployment states.
*/
Map<StreamDefinition, DeploymentState> state(List<StreamDefinition> streamDefinitions);
/**
* Get stream information including the deployment properties etc.
* @param streamName the name of the stream
* @return the stream deployment information
*/
StreamDeployment info(String streamName);
/**
* Find streams related to the given stream name.
* @param name name of the stream
* @param nested if should recursively findByNameLike for related stream definitions
* @return a list of related stream definitions
*/
List<StreamDefinition> findRelatedStreams(String name, boolean nested);
/**
* Find stream definitions where the findByNameLike parameter
* @param search the findByNameLike parameter to use
* @return Page of stream definitions
*/
Page<StreamDefinition> findDefinitionByNameLike(Pageable pageable, String search);
/**
* Find a stream definition by name.
* @param streamDefinitionName the name of the stream definition
* @return the stream definition
* @throws NoSuchStreamDefinitionException if the definition can not be found.
*/
StreamDefinition findOne(String streamDefinitionName);
/**
* Verifies that all apps in the stream are valid.
* @param name the name of the definition
* @return {@link ValidationStatus} for a stream.
*/
ValidationStatus validateStream(String name);
}
| {
"content_hash": "e60e171a277458a5163d7e1895a5dbb2",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 101,
"avg_line_length": 33.81651376146789,
"alnum_prop": 0.764514378730331,
"repo_name": "markfisher/spring-cloud-data",
"id": "c0e802d3716976efbac699da2c7a06a3ad3d8a37",
"size": "4306",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/StreamService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5654"
},
{
"name": "Java",
"bytes": "787924"
},
{
"name": "Ruby",
"bytes": "423"
},
{
"name": "Shell",
"bytes": "14192"
},
{
"name": "XSLT",
"bytes": "33659"
}
],
"symlink_target": ""
} |
ALTER TABLE `security_users` MODIFY `username` VARCHAR(255) NOT NULL, MODIFY `password` VARCHAR(255) NOT NULL;
ALTER IGNORE TABLE `security_users` ADD UNIQUE (`username`);
| {
"content_hash": "dceafa121a72d33fa6120db5d8053010",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 110,
"avg_line_length": 57.666666666666664,
"alnum_prop": 0.7572254335260116,
"repo_name": "frmst/creator",
"id": "3dda3c0cdf54e27a089206070c7734fc6c5313be",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frameset-core/src/main/resources/migrations/2014-06-12-001.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "161374"
}
],
"symlink_target": ""
} |
/* $NetBSD: pickmode.c,v 1.4 2011/04/09 20:53:39 christos Exp $ */
/*-
* Copyright (c) 2006 The NetBSD Foundation
* All rights reserved.
*
* this code was contributed to The NetBSD Foundation by Michael Lorenz
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE NETBSD FOUNDATION BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: pickmode.c,v 1.4 2011/04/09 20:53:39 christos Exp $");
#include <sys/param.h>
#include <dev/videomode/videomode.h>
#if !defined(__minix)
#include "opt_videomode.h"
#else
#include <minix/sysutil.h>
#endif /* !defined(__minix) */
#ifndef abs
#define abs(x) (((x) < 0) ? -(x) : (x))
#endif
#ifdef PICKMODE_DEBUG
#define DPRINTF printf
#else
#define DPRINTF while (0) printf
#endif
const struct videomode *
pick_mode_by_dotclock(int width, int height, int dotclock)
{
const struct videomode *this, *best = NULL;
int i;
DPRINTF("%s: looking for %d x %d at up to %d kHz\n", __func__, width,
height, dotclock);
for (i = 0; i < videomode_count; i++) {
this = &videomode_list[i];
if ((this->hdisplay != width) || (this->vdisplay != height) ||
(this->dot_clock > dotclock))
continue;
if (best != NULL) {
if (this->dot_clock > best->dot_clock)
best = this;
} else
best = this;
}
if (best != NULL)
DPRINTF("found %s\n", best->name);
return best;
}
const struct videomode *
pick_mode_by_ref(int width, int height, int refresh)
{
const struct videomode *this, *best = NULL;
int mref, closest = 1000, i, diff;
DPRINTF("%s: looking for %d x %d at up to %d Hz\n", __func__, width,
height, refresh);
for (i = 0; i < videomode_count; i++) {
this = &videomode_list[i];
mref = this->dot_clock * 1000 / (this->htotal * this->vtotal);
diff = abs(mref - refresh);
if ((this->hdisplay != width) || (this->vdisplay != height))
continue;
DPRINTF("%s in %d hz, diff %d\n", this->name, mref, diff);
if (best != NULL) {
if (diff < closest) {
best = this;
closest = diff;
}
} else {
best = this;
closest = diff;
}
}
if (best != NULL)
DPRINTF("found %s %d\n", best->name, best->dot_clock);
return best;
}
static inline void
swap_modes(struct videomode *left, struct videomode *right)
{
struct videomode temp;
temp = *left;
*left = *right;
*right = temp;
}
/*
* Sort modes by refresh rate, aspect ratio (*), then resolution.
* Preferred mode or largest mode is first in the list and other modes
* are sorted on closest match to that mode.
* (*) Note that the aspect ratio calculation treats "close" aspect ratios
* (within 12.5%) as the same for this purpose.
*/
#define DIVIDE(x, y) (((x) + ((y) / 2)) / (y))
void
sort_modes(struct videomode *modes, struct videomode **preferred, int nmodes)
{
int aspect, refresh, hbest, vbest, abest, atemp, rbest, rtemp;
int i, j;
struct videomode *mtemp = NULL;
if (nmodes < 2)
return;
if (*preferred != NULL) {
/* Put the preferred mode first in the list */
aspect = (*preferred)->hdisplay * 100 / (*preferred)->vdisplay;
refresh = DIVIDE(DIVIDE((*preferred)->dot_clock * 1000,
(*preferred)->htotal), (*preferred)->vtotal);
if (*preferred != modes) {
swap_modes(*preferred, modes);
*preferred = modes;
}
} else {
/*
* Find the largest horizontal and vertical mode and put that
* first in the list. Preferred refresh rate is taken from
* the first mode of this size.
*/
hbest = 0;
vbest = 0;
for (i = 0; i < nmodes; i++) {
if (modes[i].hdisplay > hbest) {
hbest = modes[i].hdisplay;
vbest = modes[i].vdisplay;
mtemp = &modes[i];
} else if (modes[i].hdisplay == hbest &&
modes[i].vdisplay > vbest) {
vbest = modes[i].vdisplay;
mtemp = &modes[i];
}
}
aspect = mtemp->hdisplay * 100 / mtemp->vdisplay;
refresh = DIVIDE(DIVIDE(mtemp->dot_clock * 1000,
mtemp->htotal), mtemp->vtotal);
if (mtemp != modes)
swap_modes(mtemp, modes);
}
/* Sort other modes by refresh rate, aspect ratio, then resolution */
for (j = 1; j < nmodes - 1; j++) {
rbest = 1000;
abest = 1000;
hbest = 0;
vbest = 0;
for (i = j; i < nmodes; i++) {
rtemp = abs(refresh -
DIVIDE(DIVIDE(modes[i].dot_clock * 1000,
modes[i].htotal), modes[i].vtotal));
atemp = (modes[i].hdisplay * 100 / modes[i].vdisplay);
if (rtemp < rbest) {
rbest = rtemp;
mtemp = &modes[i];
}
if (rtemp == rbest) {
/* Treat "close" aspect ratios as identical */
if (abs(abest - atemp) > (abest / 8) &&
abs(aspect - atemp) < abs(aspect - abest)) {
abest = atemp;
mtemp = &modes[i];
}
if (atemp == abest ||
abs(abest - atemp) <= (abest / 8)) {
if (modes[i].hdisplay > hbest) {
hbest = modes[i].hdisplay;
mtemp = &modes[i];
}
if (modes[i].hdisplay == hbest &&
modes[i].vdisplay > vbest) {
vbest = modes[i].vdisplay;
mtemp = &modes[i];
}
}
}
}
if (mtemp != &modes[j])
swap_modes(mtemp, &modes[j]);
}
}
| {
"content_hash": "37ff5931401c5ce79f965083eb15fd80",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 82,
"avg_line_length": 29.247619047619047,
"alnum_prop": 0.6362748290459134,
"repo_name": "veritas-shine/minix3-rpi",
"id": "bc656367589ae56c023f819066cd1f64d8ed5fbc",
"size": "6142",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sys/dev/videomode/pickmode.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89060"
},
{
"name": "Arc",
"bytes": "2839"
},
{
"name": "Assembly",
"bytes": "2791293"
},
{
"name": "Awk",
"bytes": "39398"
},
{
"name": "Bison",
"bytes": "137952"
},
{
"name": "C",
"bytes": "45473316"
},
{
"name": "C#",
"bytes": "55726"
},
{
"name": "C++",
"bytes": "577647"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "254"
},
{
"name": "Emacs Lisp",
"bytes": "4528"
},
{
"name": "IGOR Pro",
"bytes": "2975"
},
{
"name": "JavaScript",
"bytes": "25168"
},
{
"name": "Logos",
"bytes": "14672"
},
{
"name": "Lua",
"bytes": "4385"
},
{
"name": "Makefile",
"bytes": "669790"
},
{
"name": "Max",
"bytes": "3667"
},
{
"name": "Objective-C",
"bytes": "62068"
},
{
"name": "Pascal",
"bytes": "40318"
},
{
"name": "Perl",
"bytes": "100129"
},
{
"name": "Perl6",
"bytes": "243"
},
{
"name": "Prolog",
"bytes": "97"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "SAS",
"bytes": "1711"
},
{
"name": "Shell",
"bytes": "2207644"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "346d2bdbcb98b476a57254003b4a8c49",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "0e1d5a53419faca58188ca2f0ac78f08b14e21a9",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Polygonaceae/Eriogonum/Eriogonum reliquum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160318161420 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE water_areas_experience DROP INDEX UNIQ_F2454E05F92F3E70, ADD INDEX IDX_F2454E05F92F3E70 (country_id)');
$this->addSql('ALTER TABLE water_areas_experience DROP INDEX UNIQ_F2454E05A8833921, ADD INDEX IDX_F2454E05A8833921 (aquatory_id)');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE water_areas_experience DROP INDEX IDX_F2454E05F92F3E70, ADD UNIQUE INDEX UNIQ_F2454E05F92F3E70 (country_id)');
$this->addSql('ALTER TABLE water_areas_experience DROP INDEX IDX_F2454E05A8833921, ADD UNIQUE INDEX UNIQ_F2454E05A8833921 (aquatory_id)');
}
}
| {
"content_hash": "c45b9880cd30f82e104f8eec68074331",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 146,
"avg_line_length": 40.75,
"alnum_prop": 0.6987048398091343,
"repo_name": "igorRovenki/freeyachting.devsize.ru",
"id": "ffb4d3b4958d141e153d3c5598747f1c16cffd37",
"size": "1467",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/DoctrineMigrations/Version20160318161420.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3297"
},
{
"name": "CSS",
"bytes": "92206"
},
{
"name": "HTML",
"bytes": "163718"
},
{
"name": "JavaScript",
"bytes": "178094"
},
{
"name": "PHP",
"bytes": "173702"
},
{
"name": "Ruby",
"bytes": "1452"
}
],
"symlink_target": ""
} |
void test(){
sem_t sem;
int pshared = 5;
sem_init(&sem, pshared, 3);
}
//线程参数
struct NativeWorkerArgs {
jint id;
jint iterations;
};
// 用来调用Java的方法id,不要在线程中获取
static jmethodID gOnNativeMessage = NULL;
// Java VM interface pointer
extern JavaVM *gVM;
// Global reference to object
static jobject gObj = NULL;
// 互斥锁
static pthread_mutex_t mutex;
JNIEXPORT void JNICALL Java_com_ztiany_bionic_JniBridge_nativeInit(JNIEnv *env, jobject obj) {
//step 1 初始化互斥锁
if (0 != pthread_mutex_init(&mutex, NULL)) {
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to initialize mutex");
goto exit;
}
//step 2 初始化全局引用
if (NULL == gObj) {
gObj = env->NewGlobalRef(obj);
if (NULL == gObj) {
goto exit;
}
}
// step 3 获取回调方法id
if (NULL == gOnNativeMessage) {
jclass clazz = env->GetObjectClass(obj);
gOnNativeMessage = env->GetMethodID(clazz, "onNativeMessage", "(Ljava/lang/String;)V");
if (NULL == gOnNativeMessage) {
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to find method");
}
}
exit:
return;
}
JNIEXPORT void JNICALL Java_com_ztiany_bionic_JniBridge_nativeFree(JNIEnv *env, jobject obj) {
//删除全局引用
if (NULL != gObj) {
env->DeleteGlobalRef(gObj);
gObj = NULL;
}
//销毁锁
if (0 != pthread_mutex_destroy(&mutex)) {
// Get the exception class
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to destroy mutex");
}
}
//线程任务
void nativeWorker(JNIEnv *env, jobject obj, jint id, jint iterations) {
// 上锁
if (0 != pthread_mutex_lock(&mutex)) {
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to lock mutex");
goto exit;
}
//模拟任务
for (jint i = 0; i < iterations; i++) {
char message[26];
sprintf(message, "Worker %d: Iteration %d", id, i);
jstring messageString = env->NewStringUTF(message);
env->CallVoidMethod(obj, gOnNativeMessage, messageString);
// 如果有异常发送则退出
if (NULL != env->ExceptionOccurred()) {
break;
}
//睡一秒
sleep(1);
}
// 释放锁
if (0 != pthread_mutex_unlock(&mutex)) {
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to unlock mutex");
}
exit:
return;
}
static void *nativeWorkerThread(void *args) {
JNIEnv *env = NULL;
//如果需要和Java进行交互,原生线程必须先attach到JVM上
if (0 == gVM->AttachCurrentThread(&env, NULL)) {
// Get the native worker thread arguments
NativeWorkerArgs *nativeWorkerArgs = (NativeWorkerArgs *) args;
//执行模拟任务
nativeWorker(env, gObj, nativeWorkerArgs->id, nativeWorkerArgs->iterations);
delete nativeWorkerArgs;
//必须detach
gVM->DetachCurrentThread();
}
return (void *) 1;
}
JNIEXPORT void JNICALL
Java_com_ztiany_bionic_JniBridge_posixThreads(JNIEnv *env, jobject obj,
jint threads, jint iterations) {
// 创建线程
for (jint i = 0; i < threads; i++) {
//创建一个线程空间
pthread_t thread;
// Native worker thread arguments
NativeWorkerArgs *nativeWorkerArgs = new NativeWorkerArgs();
nativeWorkerArgs->id = i;
nativeWorkerArgs->iterations = iterations;
// 线程实例
int result = pthread_create(
&thread,//线程引用
NULL,//用于设置线程的属性,传NULL则使用默认属性
nativeWorkerThread,//线程创建后执行的方法,必须是 void * method(void *args)类型
(void *) nativeWorkerArgs);//传递给nativeWorkerThread的参数
if (0 != result) {
jclass exceptionClazz = env->FindClass("java/lang/RuntimeException");
env->ThrowNew(exceptionClazz, "Unable to create thread");
}
}
} | {
"content_hash": "56b044e9706c4bfed999bd789e6c3710",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 95,
"avg_line_length": 26.525641025641026,
"alnum_prop": 0.6041565973900435,
"repo_name": "Ztiany/Repository",
"id": "d2c2d85a5a224d32a57eb5a00ac3a3ba1ff18f21",
"size": "4573",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Android/NDK/BionicAPI/app/src/main/cpp/threads-api.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "38608"
},
{
"name": "C++",
"bytes": "52662"
},
{
"name": "CMake",
"bytes": "316"
},
{
"name": "CSS",
"bytes": "28"
},
{
"name": "Groovy",
"bytes": "151193"
},
{
"name": "HTML",
"bytes": "126611"
},
{
"name": "Java",
"bytes": "632743"
},
{
"name": "Kotlin",
"bytes": "81491"
},
{
"name": "Python",
"bytes": "16189"
}
],
"symlink_target": ""
} |
/*
* $Id: AbstractTableMap.java 38 2012-01-04 22:44:15Z andre@naef.com $
* See LICENSE.txt for license terms.
*/
package com.naef.jnlua.util;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import com.naef.jnlua.LuaState;
import com.naef.jnlua.LuaValueProxy;
/**
* Abstract map implementation backed by a Lua table.
*/
public abstract class AbstractTableMap<K> extends AbstractMap<K, Object>
implements LuaValueProxy {
// -- State
private Set<Map.Entry<K, Object>> entrySet;
// -- Construction
/**
* Creates a new instance.
*/
public AbstractTableMap() {
}
// -- Map methods
@Override
public Set<Map.Entry<K, Object>> entrySet() {
if (entrySet == null) {
entrySet = new EntrySet();
}
return entrySet;
}
@Override
public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override
public boolean containsKey(Object key) {
checkKey(key);
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushJavaObject(key);
luaState.getTable(-2);
try {
return !luaState.isNil(-1);
} finally {
luaState.pop(2);
}
}
}
@Override
public Object get(Object key) {
checkKey(key);
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushJavaObject(key);
luaState.getTable(-2);
try {
return luaState.toJavaObject(-1, Object.class);
} finally {
luaState.pop(2);
}
}
}
@Override
public Object put(K key, Object value) {
checkKey(key);
LuaState luaState = getLuaState();
synchronized (luaState) {
Object oldValue = get(key);
pushValue();
luaState.pushJavaObject(key);
luaState.pushJavaObject(value);
luaState.setTable(-3);
luaState.pop(1);
return oldValue;
}
}
@Override
public Object remove(Object key) {
checkKey(key);
LuaState luaState = getLuaState();
synchronized (luaState) {
Object oldValue = get(key);
pushValue();
luaState.pushJavaObject(key);
luaState.pushNil();
luaState.setTable(-3);
luaState.pop(1);
return oldValue;
}
}
// -- Protected methods
/**
* Checks a key for validity. If the key is not valid, the method throws an
* appropriate runtime exception. The method is invoked for all input keys.
*
* <p>
* This implementation checks that the key is not <code>null</code>. Lua
* does not allow <code>nil</code> as a table key. Subclasses may implement
* more restrictive checks.
* </p>
*
* @param key
* the key
* @throws NullPointerException
* if the key is <code>null</code>
*/
protected void checkKey(Object key) {
if (key == null) {
throw new NullPointerException("key must not be null");
}
}
/**
* Indicates if this table map filters keys from the Lua table. If the
* method returns <code>true</code>, the table map invokes
* {@link #acceptKey(int)} on each key retrieved from the underlying table
* to determine whether the key is accepted or rejected.
*
* <p>
* This implementation returns <code>false</code>. Subclasses may override
* the method alongside {@link #acceptKey(int)} to implement key filtering.
* </p>
*
* @return whether this table map filters keys from the Lua table
*/
protected boolean filterKeys() {
return false;
}
/**
* Accepts or rejects a key from the Lua table. Only table keys that are
* accepted are processed. The method allows subclasses to filter the Lua
* table. The method is called only if {@link #filterKeys()} returns
* <code>true</code>.
*
* <p>
* This implementation returns <code>true</code> regardless of the input,
* thus accepting all keys. Subclasses may override the method alongside
* {@link #filterKeys()} to implement key filtering.
* </p>
*
* @param index
* the stack index containing the candidate key
* @return whether the key is accepted
*/
protected boolean acceptKey(int index) {
return true;
}
/**
* Converts the key at the specified stack index to a Java object. If this
* table maps performs key filtering, the method is invoked only for keys it
* has accepted.
*
* @param index
* the stack index containing the key
* @return the Java object representing the key
* @see #filterKeys()
* @see #acceptKey(int)
*/
protected abstract K convertKey(int index);
// -- Nested types
/**
* Lua table entry set.
*/
private class EntrySet extends AbstractSet<Map.Entry<K, Object>> {
// -- Set methods
@Override
public Iterator<Map.Entry<K, Object>> iterator() {
return new EntryIterator();
}
@Override
public boolean isEmpty() {
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushNil();
while (luaState.next(-2)) {
if (!filterKeys() || acceptKey(-2)) {
luaState.pop(3);
return false;
}
}
luaState.pop(1);
return true;
}
}
@Override
public int size() {
LuaState luaState = getLuaState();
synchronized (luaState) {
int count = 0;
pushValue();
if (filterKeys()) {
luaState.pushNil();
while (luaState.next(-2)) {
if (acceptKey(-2)) {
count++;
}
luaState.pop(1);
}
} else {
count = luaState.tableSize(-1);
}
luaState.pop(1);
return count;
}
}
@Override
public boolean contains(Object object) {
checkKey(object);
if (!(object instanceof AbstractTableMap<?>.Entry)) {
return false;
}
@SuppressWarnings("unchecked")
Entry luaTableEntry = (Entry) object;
if (luaTableEntry.getLuaState() != getLuaState()) {
return false;
}
return containsKey(luaTableEntry.key);
}
@Override
public boolean remove(Object object) {
if (!(object instanceof AbstractTableMap<?>.Entry)) {
return false;
}
@SuppressWarnings("unchecked")
Entry luaTableEntry = (Entry) object;
if (luaTableEntry.getLuaState() != getLuaState()) {
return false;
}
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushJavaObject(object);
luaState.getTable(-2);
boolean contains = !luaState.isNil(-1);
luaState.pop(1);
if (contains) {
luaState.pushJavaObject(object);
luaState.pushNil();
luaState.setTable(-3);
}
luaState.pop(1);
return contains;
}
}
}
/**
* Lua table iterator.
*/
private class EntryIterator implements Iterator<Map.Entry<K, Object>> {
// -- State
private K key;
// -- Iterator methods
@Override
public boolean hasNext() {
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushJavaObject(key);
while (luaState.next(-2)) {
if (!filterKeys() || acceptKey(-2)) {
luaState.pop(3);
return true;
}
}
luaState.pop(1);
return false;
}
}
@Override
public Map.Entry<K, Object> next() {
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushJavaObject(key);
while (luaState.next(-2)) {
if (!filterKeys() || acceptKey(-2)) {
key = convertKey(-2);
luaState.pop(3);
return new Entry(key);
}
}
luaState.pop(1);
throw new NoSuchElementException();
}
}
@Override
public void remove() {
LuaState luaState = getLuaState();
synchronized (luaState) {
pushValue();
luaState.pushJavaObject(key);
luaState.pushNil();
luaState.setTable(-3);
luaState.pop(1);
}
}
}
/**
* Bindings entry.
*/
private class Entry implements Map.Entry<K, Object> {
// -- State
private K key;
// -- Construction
/**
* Creates a new instance.
*/
public Entry(K key) {
this.key = key;
}
// -- Map.Entry methods
@Override
public K getKey() {
return key;
}
@Override
public Object getValue() {
return get(key);
}
@Override
public Object setValue(Object value) {
return put(key, value);
}
// -- Object methods
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AbstractTableMap<?>.Entry)) {
return false;
}
@SuppressWarnings("unchecked")
Entry other = (Entry) obj;
return getLuaState() == other.getLuaState()
&& key.equals(other.key);
}
@Override
public int hashCode() {
return getLuaState().hashCode() * 65599 + key.hashCode();
}
@Override
public String toString() {
return key.toString();
}
// -- Private methods
/**
* Returns the Lua script engine.
*/
private LuaState getLuaState() {
return AbstractTableMap.this.getLuaState();
}
}
} | {
"content_hash": "1007aa78043e65588e1735aae206ca41",
"timestamp": "",
"source": "github",
"line_count": 390,
"max_line_length": 77,
"avg_line_length": 23.31025641025641,
"alnum_prop": 0.6148938510614894,
"repo_name": "buksy/jnlua",
"id": "5a8a6139c0d9dcb8d66811583e36bff8ca9a4816",
"size": "9091",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/com/naef/jnlua/util/AbstractTableMap.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "76912"
},
{
"name": "Java",
"bytes": "327581"
},
{
"name": "Lua",
"bytes": "10106"
}
],
"symlink_target": ""
} |
package com.sun.jmx.snmp.daemon;
// java import
//
import java.util.logging.Level;
import java.util.Vector;
// jmx imports
//
import static com.sun.jmx.defaults.JmxProperties.SNMP_ADAPTOR_LOGGER;
import com.sun.jmx.snmp.SnmpPdu;
import com.sun.jmx.snmp.SnmpVarBind;
import com.sun.jmx.snmp.SnmpDefinitions;
import com.sun.jmx.snmp.SnmpStatusException;
import com.sun.jmx.snmp.SnmpEngine;
// SNMP Runtime import
//
import com.sun.jmx.snmp.agent.SnmpMibAgent;
import com.sun.jmx.snmp.agent.SnmpMibRequest;
import com.sun.jmx.snmp.ThreadContext;
import com.sun.jmx.snmp.internal.SnmpIncomingRequest;
class SnmpSubRequestHandler implements SnmpDefinitions, Runnable {
protected SnmpIncomingRequest incRequest = null;
protected SnmpEngine engine = null;
/**
* V3 enabled Adaptor. Each Oid is added using updateRequest method.
*/
protected SnmpSubRequestHandler(SnmpEngine engine,
SnmpIncomingRequest incRequest,
SnmpMibAgent agent,
SnmpPdu req) {
this(agent, req);
init(engine, incRequest);
}
/**
* V3 enabled Adaptor.
*/
protected SnmpSubRequestHandler(SnmpEngine engine,
SnmpIncomingRequest incRequest,
SnmpMibAgent agent,
SnmpPdu req,
boolean nouse) {
this(agent, req, nouse);
init(engine, incRequest);
}
/**
* SNMP V1/V2 . To be called with updateRequest.
*/
protected SnmpSubRequestHandler(SnmpMibAgent agent, SnmpPdu req) {
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpSubRequestHandler.class.getName(),
"constructor", "creating instance for request " + String.valueOf(req.requestId));
}
version= req.version;
type= req.type;
this.agent= agent;
// We get a ref on the pdu in order to pass it to SnmpMibRequest.
reqPdu = req;
//Pre-allocate room for storing varbindlist and translation table.
//
int length= req.varBindList.length;
translation= new int[length];
varBind= new NonSyncVector<SnmpVarBind>(length);
}
/**
* SNMP V1/V2 The constructor initialize the subrequest with the whole varbind list contained
* in the original request.
*/
@SuppressWarnings("unchecked") // cast to NonSyncVector<SnmpVarBind>
protected SnmpSubRequestHandler(SnmpMibAgent agent,
SnmpPdu req,
boolean nouse) {
this(agent,req);
// The translation table is easy in this case ...
//
int max= translation.length;
SnmpVarBind[] list= req.varBindList;
for(int i=0; i < max; i++) {
translation[i]= i;
((NonSyncVector<SnmpVarBind>)varBind).addNonSyncElement(list[i]);
}
}
SnmpMibRequest createMibRequest(Vector<SnmpVarBind> vblist,
int protocolVersion,
Object userData) {
// This is an optimization:
// The SnmpMibRequest created in the check() phase is
// reused in the set() phase.
//
if (type == pduSetRequestPdu && mibRequest != null)
return mibRequest;
//This is a request comming from an SnmpV3AdaptorServer.
//Full power.
SnmpMibRequest result = null;
if(incRequest != null) {
result = SnmpMibAgent.newMibRequest(engine,
reqPdu,
vblist,
protocolVersion,
userData,
incRequest.getPrincipal(),
incRequest.getSecurityLevel(),
incRequest.getSecurityModel(),
incRequest.getContextName(),
incRequest.getAccessContext());
} else {
result = SnmpMibAgent.newMibRequest(reqPdu,
vblist,
protocolVersion,
userData);
}
// If we're doing the check() phase, we store the SnmpMibRequest
// so that we can reuse it in the set() phase.
//
if (type == pduWalkRequest)
mibRequest = result;
return result;
}
void setUserData(Object userData) {
data = userData;
}
public void run() {
try {
final ThreadContext oldContext =
ThreadContext.push("SnmpUserData",data);
try {
switch(type) {
case pduGetRequestPdu:
// Invoke a get operation
//
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:get operation on " + agent.getMibName());
}
agent.get(createMibRequest(varBind,version,data));
break;
case pduGetNextRequestPdu:
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:getNext operation on " + agent.getMibName());
}
//#ifdef DEBUG
agent.getNext(createMibRequest(varBind,version,data));
break;
case pduSetRequestPdu:
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:set operation on " + agent.getMibName());
}
agent.set(createMibRequest(varBind,version,data));
break;
case pduWalkRequest:
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:check operation on " + agent.getMibName());
}
agent.check(createMibRequest(varBind,version,data));
break;
default:
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:unknown operation (" + type + ") on " +
agent.getMibName());
}
errorStatus= snmpRspGenErr;
errorIndex= 1;
break;
}// end of switch
} finally {
ThreadContext.restore(oldContext);
}
} catch(SnmpStatusException x) {
errorStatus = x.getStatus() ;
errorIndex= x.getErrorIndex();
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:an Snmp error occurred during the operation", x);
}
}
catch(Exception x) {
errorStatus = SnmpDefinitions.snmpRspGenErr ;
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() +
"]:a generic error occurred during the operation", x);
}
}
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpSubRequestHandler.class.getName(),
"run", "[" + Thread.currentThread() + "]:operation completed");
}
}
// -------------------------------------------------------------
//
// This function does a best-effort to map global error status
// to SNMP v1 valid global error status.
//
// An SnmpStatusException can contain either:
// <li> v2 local error codes (that should be stored in the varbind)</li>
// <li> v2 global error codes </li>
// <li> v1 global error codes </li>
//
// v2 local error codes (noSuchInstance, noSuchObject) are
// transformed in a global v1 snmpRspNoSuchName error.
//
// v2 global error codes are transformed in the following way:
//
// If the request was a GET/GETNEXT then either
// snmpRspNoSuchName or snmpRspGenErr is returned.
//
// Otherwise:
// snmpRspNoAccess, snmpRspInconsistentName
// => snmpRspNoSuchName
// snmpRspAuthorizationError, snmpRspNotWritable, snmpRspNoCreation
// => snmpRspReadOnly (snmpRspNoSuchName for GET/GETNEXT)
// snmpRspWrong*
// => snmpRspBadValue (snmpRspNoSuchName for GET/GETNEXT)
// snmpRspResourceUnavailable, snmpRspRspCommitFailed,
// snmpRspUndoFailed
// => snmpRspGenErr
//
// -------------------------------------------------------------
//
static final int mapErrorStatusToV1(int errorStatus, int reqPduType) {
// Map v2 codes onto v1 codes
//
if (errorStatus == SnmpDefinitions.snmpRspNoError)
return SnmpDefinitions.snmpRspNoError;
if (errorStatus == SnmpDefinitions.snmpRspGenErr)
return SnmpDefinitions.snmpRspGenErr;
if (errorStatus == SnmpDefinitions.snmpRspNoSuchName)
return SnmpDefinitions.snmpRspNoSuchName;
if ((errorStatus == SnmpStatusException.noSuchInstance) ||
(errorStatus == SnmpStatusException.noSuchObject) ||
(errorStatus == SnmpDefinitions.snmpRspNoAccess) ||
(errorStatus == SnmpDefinitions.snmpRspInconsistentName) ||
(errorStatus == SnmpDefinitions.snmpRspAuthorizationError)){
return SnmpDefinitions.snmpRspNoSuchName;
} else if ((errorStatus ==
SnmpDefinitions.snmpRspAuthorizationError) ||
(errorStatus == SnmpDefinitions.snmpRspNotWritable)) {
if (reqPduType == SnmpDefinitions.pduWalkRequest)
return SnmpDefinitions.snmpRspReadOnly;
else
return SnmpDefinitions.snmpRspNoSuchName;
} else if ((errorStatus == SnmpDefinitions.snmpRspNoCreation)) {
return SnmpDefinitions.snmpRspNoSuchName;
} else if ((errorStatus == SnmpDefinitions.snmpRspWrongType) ||
(errorStatus == SnmpDefinitions.snmpRspWrongLength) ||
(errorStatus == SnmpDefinitions.snmpRspWrongEncoding) ||
(errorStatus == SnmpDefinitions.snmpRspWrongValue) ||
(errorStatus == SnmpDefinitions.snmpRspWrongLength) ||
(errorStatus ==
SnmpDefinitions.snmpRspInconsistentValue)) {
if ((reqPduType == SnmpDefinitions.pduSetRequestPdu) ||
(reqPduType == SnmpDefinitions.pduWalkRequest))
return SnmpDefinitions.snmpRspBadValue;
else
return SnmpDefinitions.snmpRspNoSuchName;
} else if ((errorStatus ==
SnmpDefinitions.snmpRspResourceUnavailable) ||
(errorStatus ==
SnmpDefinitions.snmpRspCommitFailed) ||
(errorStatus == SnmpDefinitions.snmpRspUndoFailed)) {
return SnmpDefinitions.snmpRspGenErr;
}
// At this point we should have a V1 error code
//
if (errorStatus == SnmpDefinitions.snmpRspTooBig)
return SnmpDefinitions.snmpRspTooBig;
if( (errorStatus == SnmpDefinitions.snmpRspBadValue) ||
(errorStatus == SnmpDefinitions.snmpRspReadOnly)) {
if ((reqPduType == SnmpDefinitions.pduSetRequestPdu) ||
(reqPduType == SnmpDefinitions.pduWalkRequest))
return errorStatus;
else
return SnmpDefinitions.snmpRspNoSuchName;
}
// We have a snmpRspGenErr, or something which is not defined
// in RFC1905 => return a snmpRspGenErr
//
return SnmpDefinitions.snmpRspGenErr;
}
// -------------------------------------------------------------
//
// This function does a best-effort to map global error status
// to SNMP v2 valid global error status.
//
// An SnmpStatusException can contain either:
// <li> v2 local error codes (that should be stored in the varbind)</li>
// <li> v2 global error codes </li>
// <li> v1 global error codes </li>
//
// v2 local error codes (noSuchInstance, noSuchObject)
// should not raise this level: they should have been stored in the
// varbind earlier. If they, do there is nothing much we can do except
// to transform them into:
// <li> a global snmpRspGenErr (if the request is a GET/GETNEXT) </li>
// <li> a global snmpRspNoSuchName otherwise. </li>
//
// v2 global error codes are transformed in the following way:
//
// If the request was a GET/GETNEXT then snmpRspGenErr is returned.
// (snmpRspGenErr is the only global error that is expected to be
// raised by a GET/GETNEXT request).
//
// Otherwise the v2 code itself is returned
//
// v1 global error codes are transformed in the following way:
//
// snmpRspNoSuchName
// => snmpRspNoAccess (snmpRspGenErr for GET/GETNEXT)
// snmpRspReadOnly
// => snmpRspNotWritable (snmpRspGenErr for GET/GETNEXT)
// snmpRspBadValue
// => snmpRspWrongValue (snmpRspGenErr for GET/GETNEXT)
//
// -------------------------------------------------------------
//
static final int mapErrorStatusToV2(int errorStatus, int reqPduType) {
// Map v1 codes onto v2 codes
//
if (errorStatus == SnmpDefinitions.snmpRspNoError)
return SnmpDefinitions.snmpRspNoError;
if (errorStatus == SnmpDefinitions.snmpRspGenErr)
return SnmpDefinitions.snmpRspGenErr;
if (errorStatus == SnmpDefinitions.snmpRspTooBig)
return SnmpDefinitions.snmpRspTooBig;
// For get / getNext / getBulk the only global error
// (PDU-level) possible is genErr.
//
if ((reqPduType != SnmpDefinitions.pduSetRequestPdu) &&
(reqPduType != SnmpDefinitions.pduWalkRequest)) {
if(errorStatus == SnmpDefinitions.snmpRspAuthorizationError)
return errorStatus;
else
return SnmpDefinitions.snmpRspGenErr;
}
// Map to noSuchName
// if ((errorStatus == SnmpDefinitions.snmpRspNoSuchName) ||
// (errorStatus == SnmpStatusException.noSuchInstance) ||
// (errorStatus == SnmpStatusException.noSuchObject))
// return SnmpDefinitions.snmpRspNoSuchName;
// SnmpStatusException.noSuchInstance and
// SnmpStatusException.noSuchObject can't happen...
if (errorStatus == SnmpDefinitions.snmpRspNoSuchName)
return SnmpDefinitions.snmpRspNoAccess;
// Map to notWritable
if (errorStatus == SnmpDefinitions.snmpRspReadOnly)
return SnmpDefinitions.snmpRspNotWritable;
// Map to wrongValue
if (errorStatus == SnmpDefinitions.snmpRspBadValue)
return SnmpDefinitions.snmpRspWrongValue;
// Other valid V2 codes
if ((errorStatus == SnmpDefinitions.snmpRspNoAccess) ||
(errorStatus == SnmpDefinitions.snmpRspInconsistentName) ||
(errorStatus == SnmpDefinitions.snmpRspAuthorizationError) ||
(errorStatus == SnmpDefinitions.snmpRspNotWritable) ||
(errorStatus == SnmpDefinitions.snmpRspNoCreation) ||
(errorStatus == SnmpDefinitions.snmpRspWrongType) ||
(errorStatus == SnmpDefinitions.snmpRspWrongLength) ||
(errorStatus == SnmpDefinitions.snmpRspWrongEncoding) ||
(errorStatus == SnmpDefinitions.snmpRspWrongValue) ||
(errorStatus == SnmpDefinitions.snmpRspWrongLength) ||
(errorStatus == SnmpDefinitions.snmpRspInconsistentValue) ||
(errorStatus == SnmpDefinitions.snmpRspResourceUnavailable) ||
(errorStatus == SnmpDefinitions.snmpRspCommitFailed) ||
(errorStatus == SnmpDefinitions.snmpRspUndoFailed))
return errorStatus;
// Ivalid V2 code => genErr
return SnmpDefinitions.snmpRspGenErr;
}
static final int mapErrorStatus(int errorStatus,
int protocolVersion,
int reqPduType) {
if (errorStatus == SnmpDefinitions.snmpRspNoError)
return SnmpDefinitions.snmpRspNoError;
// Too bad, an error occurs ... we need to translate it ...
//
if (protocolVersion == SnmpDefinitions.snmpVersionOne)
return mapErrorStatusToV1(errorStatus,reqPduType);
if (protocolVersion == SnmpDefinitions.snmpVersionTwo ||
protocolVersion == SnmpDefinitions.snmpVersionThree)
return mapErrorStatusToV2(errorStatus,reqPduType);
return SnmpDefinitions.snmpRspGenErr;
}
/**
* The method returns the error status of the operation.
* The method takes into account the protocol version.
*/
protected int getErrorStatus() {
if (errorStatus == snmpRspNoError)
return snmpRspNoError;
return mapErrorStatus(errorStatus,version,type);
}
/**
* The method returns the error index as a position in the var bind list.
* The value returned by the method corresponds to the index in the original
* var bind list as received by the SNMP protocol adaptor.
*/
protected int getErrorIndex() {
if (errorStatus == snmpRspNoError)
return -1;
// An error occurs. We need to be carefull because the index
// we are getting is a valid SNMP index (so range starts at 1).
// FIX ME: Shall we double-check the range here ?
// The response is : YES :
if ((errorIndex == 0) || (errorIndex == -1))
errorIndex = 1;
return translation[errorIndex -1];
}
/**
* The method updates the varbind list of the subrequest.
*/
protected void updateRequest(SnmpVarBind var, int pos) {
int size= varBind.size();
translation[size]= pos;
varBind.addElement(var);
}
/**
* The method updates a given var bind list with the result of a
* previsouly invoked operation.
* Prior to calling the method, one must make sure that the operation was
* successful. As such the method getErrorIndex or getErrorStatus should be
* called.
*/
protected void updateResult(SnmpVarBind[] result) {
if (result == null) return;
final int max=varBind.size();
final int len=result.length;
for(int i= 0; i< max ; i++) {
// bugId 4641694: must check position in order to avoid
// ArrayIndexOutOfBoundException
final int pos=translation[i];
if (pos < len) {
result[pos] =
(SnmpVarBind)((NonSyncVector)varBind).elementAtNonSync(i);
} else {
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpSubRequestHandler.class.getName(),
"updateResult","Position `"+pos+"' is out of bound...");
}
}
}
}
private void init(SnmpEngine engine,
SnmpIncomingRequest incRequest) {
this.incRequest = incRequest;
this.engine = engine;
}
// PRIVATE VARIABLES
//------------------
/**
* Store the protocol version to handle
*/
protected int version= snmpVersionOne;
/**
* Store the operation type. Remember if the type is Walk, it means
* that we have to invoke the check method ...
*/
protected int type= 0;
/**
* Agent directly handled by the sub-request handler.
*/
protected SnmpMibAgent agent;
/**
* Error status.
*/
protected int errorStatus= snmpRspNoError;
/**
* Index of error.
* A value of -1 means no error.
*/
protected int errorIndex= -1;
/**
* The varbind list specific to the current sub request.
* The vector must contain object of type SnmpVarBind.
*/
protected Vector<SnmpVarBind> varBind;
/**
* The array giving the index translation between the content of
* <VAR>varBind</VAR> and the varbind list as specified in the request.
*/
protected int[] translation;
/**
* Contextual object allocated by the SnmpUserDataFactory.
**/
protected Object data;
/**
* The SnmpMibRequest that will be passed to the agent.
*
**/
private SnmpMibRequest mibRequest = null;
/**
* The SnmpPdu that will be passed to the request.
*
**/
private SnmpPdu reqPdu = null;
// All the methods of the Vector class are synchronized.
// Synchronization is a very expensive operation. In our case it is not always
// required...
//
@SuppressWarnings("serial") // we never serialize this
class NonSyncVector<E> extends Vector<E> {
public NonSyncVector(int size) {
super(size);
}
final void addNonSyncElement(E obj) {
ensureCapacity(elementCount + 1);
elementData[elementCount++] = obj;
}
@SuppressWarnings("unchecked") // cast to E
final E elementAtNonSync(int index) {
return (E) elementData[index];
}
};
}
| {
"content_hash": "f53d4547b5a1234758ca154ef5d85a0c",
"timestamp": "",
"source": "github",
"line_count": 607,
"max_line_length": 101,
"avg_line_length": 38.01976935749588,
"alnum_prop": 0.5648236415633937,
"repo_name": "rokn/Count_Words_2015",
"id": "c2858deffcc2388b2b636e7092e80a81e1c3e6c4",
"size": "24290",
"binary": false,
"copies": "26",
"ref": "refs/heads/master",
"path": "testing/openjdk2/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpSubRequestHandler.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "61802"
},
{
"name": "Ruby",
"bytes": "18888605"
}
],
"symlink_target": ""
} |
var argscheck = require('cordova/argscheck'),
exec = require('cordova/exec'),
ContactError = require('./ContactError'),
utils = require('cordova/utils'),
Contact = require('./Contact'),
fieldType = require('./ContactFieldType');
/**
* Represents a group of Contacts.
* @constructor
*/
var contacts = {
fieldType: fieldType,
/**
* Returns an array of Contacts matching the search criteria.
* @param fields that should be searched
* @param successCB success callback
* @param errorCB error callback
* @param {ContactFindOptions} options that can be applied to contact searching
* @return array of Contacts matching search criteria
*/
find:function(successCB, errorCB, fields, options) {
argscheck.checkArgs('fFaO', 'contacts.find', arguments);
if (!fields.length) {
errorCB && errorCB(new ContactError(ContactError.INVALID_ARGUMENT_ERROR));
} else {
var win = function(result) {
var cs = [];
for (var i = 0, l = result.length; i < l; i++) {
cs.push(contacts.create(result[i]));
}
successCB(cs);
};
exec(win, errorCB, "Contacts", "search", [fields, options]);
}
},
/**
* This function picks contact from phone using contact picker UI
* @returns new Contact object
*/
pickContact: function (successCB, errorCB) {
argscheck.checkArgs('fF', 'contacts.pick', arguments);
var win = function (result) {
// if Contacts.pickContact return instance of Contact object
// don't create new Contact object, use current
var contact = result instanceof Contact ? result : contacts.create(result);
successCB(contact);
};
exec(win, errorCB, "Contacts", "pickContact", []);
},
/**
* This function creates a new contact, but it does not persist the contact
* to device storage. To persist the contact to device storage, invoke
* contact.save().
* @param properties an object whose properties will be examined to create a new Contact
* @returns new Contact object
*/
create:function(properties) {
argscheck.checkArgs('O', 'contacts.create', arguments);
var contact = new Contact();
for (var i in properties) {
if (typeof contact[i] !== 'undefined' && properties.hasOwnProperty(i)) {
contact[i] = properties[i];
}
}
return contact;
}
};
module.exports = contacts;
| {
"content_hash": "998a6a507fc5d7132dd1024ce89ccb13",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 92,
"avg_line_length": 34.03896103896104,
"alnum_prop": 0.5936665394887447,
"repo_name": "gemanor/OrangeMenu",
"id": "1ecd28c9d520bbe8eaa5b56a4e681760bb6e6ed0",
"size": "3433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/org.apache.cordova.contacts/www/contacts.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "1208"
},
{
"name": "C",
"bytes": "1025"
},
{
"name": "C#",
"bytes": "368094"
},
{
"name": "C++",
"bytes": "177552"
},
{
"name": "CSS",
"bytes": "103453"
},
{
"name": "D",
"bytes": "63903"
},
{
"name": "Erlang",
"bytes": "2687"
},
{
"name": "Java",
"bytes": "1766908"
},
{
"name": "JavaScript",
"bytes": "1037128"
},
{
"name": "Objective-C",
"bytes": "1256824"
},
{
"name": "PHP",
"bytes": "222"
},
{
"name": "Perl",
"bytes": "891"
},
{
"name": "Shell",
"bytes": "40952"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
<Asset Type="RolePlayingGameData.Item">
<Name>Physical Defense Elixir</Name>
<Description>Increases physical defense by 1 point.</Description>
<GoldValue>500</GoldValue>
<IsDroppable>true</IsDroppable>
<MinimumCharacterLevel>1</MinimumCharacterLevel>
<SupportedClasses />
<IconTextureName>Potion01g</IconTextureName>
<Usage>Combat</Usage>
<IsOffensive>false</IsOffensive>
<TargetDuration>0</TargetDuration>
<TargetEffectRange>
<HealthPointsRange>
<Minimum>0</Minimum>
<Maximum>0</Maximum>
</HealthPointsRange>
<MagicPointsRange>
<Minimum>0</Minimum>
<Maximum>0</Maximum>
</MagicPointsRange>
<PhysicalOffenseRange>
<Minimum>0</Minimum>
<Maximum>0</Maximum>
</PhysicalOffenseRange>
<PhysicalDefenseRange>
<Minimum>1</Minimum>
<Maximum>1</Maximum>
</PhysicalDefenseRange>
<MagicalOffenseRange>
<Minimum>0</Minimum>
<Maximum>0</Maximum>
</MagicalOffenseRange>
<MagicalDefenseRange>
<Minimum>0</Minimum>
<Maximum>0</Maximum>
</MagicalDefenseRange>
</TargetEffectRange>
<AdjacentTargets>0</AdjacentTargets>
<UsingCueName>HealPotion</UsingCueName>
<TravelingCueName />
<ImpactCueName>HealImpact</ImpactCueName>
<BlockCueName>HealImpact</BlockCueName>
<CreationSprite>
<TextureName>Spells\Potion1g</TextureName>
<FrameDimensions>48 48</FrameDimensions>
<FramesPerRow>1</FramesPerRow>
<SourceOffset>19 9</SourceOffset>
<Animations>
<Item>
<Name>Creation</Name>
<StartingFrame>1</StartingFrame>
<EndingFrame>1</EndingFrame>
<Interval>500</Interval>
<IsLoop>false</IsLoop>
</Item>
</Animations>
</CreationSprite>
<SpellSprite>
<TextureName>Spells\HealSmallSpell</TextureName>
<FrameDimensions>48 48</FrameDimensions>
<FramesPerRow>6</FramesPerRow>
<SourceOffset>19 9</SourceOffset>
<Animations>
<Item>
<Name>Traveling</Name>
<StartingFrame>12</StartingFrame>
<EndingFrame>12</EndingFrame>
<Interval>120</Interval>
<IsLoop>true</IsLoop>
</Item>
<Item>
<Name>Impact</Name>
<StartingFrame>13</StartingFrame>
<EndingFrame>18</EndingFrame>
<Interval>200</Interval>
<IsLoop>false</IsLoop>
</Item>
</Animations>
</SpellSprite>
<Overlay>
<TextureName>Spells\EffectSmall</TextureName>
<FrameDimensions>61 98</FrameDimensions>
<FramesPerRow>6</FramesPerRow>
<Animations>
<Item>
<StartingFrame>1</StartingFrame>
<EndingFrame>6</EndingFrame>
<Interval>100</Interval>
<IsLoop>false</IsLoop>
</Item>
</Animations>
</Overlay>
</Asset>
</XnaContent> | {
"content_hash": "581db60e075e55faa546d029f5650677",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 69,
"avg_line_length": 31.197916666666668,
"alnum_prop": 0.6230383973288814,
"repo_name": "DDReaper/XNAGameStudio",
"id": "a48042c45af9b08f6c8f4083446fa92e35ceaad7",
"size": "2997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Samples/RolePlayingGame_4_0_Phone/RolePlayingGameContentWindowsPhone/Gear/Items/PDElixir.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "77207"
}
],
"symlink_target": ""
} |
package org.eluder.coveralls.maven.plugin.source;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eluder.coveralls.maven.plugin.domain.Source;
public class MultiSourceLoader implements SourceLoader {
private final List<SourceLoader> sourceLoaders = new ArrayList<SourceLoader>();
public MultiSourceLoader add(final SourceLoader sourceLoader) {
this.sourceLoaders.add(sourceLoader);
return this;
}
@Override
public Source load(final String sourceFile) throws IOException {
for (SourceLoader sourceLoader : sourceLoaders) {
Source source = sourceLoader.load(sourceFile);
if (source != null) {
return source;
}
}
throw new IOException("No source found for " + sourceFile);
}
}
| {
"content_hash": "de4918f6bb0367184ec91bbf44fdfa3c",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 83,
"avg_line_length": 28.266666666666666,
"alnum_prop": 0.6768867924528302,
"repo_name": "psiniemi/coveralls-maven-plugin",
"id": "9e45a77b80a6f76b11576e837f20d65fff4ff968",
"size": "2038",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/eluder/coveralls/maven/plugin/source/MultiSourceLoader.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "135"
},
{
"name": "Java",
"bytes": "277500"
},
{
"name": "JavaScript",
"bytes": "662"
},
{
"name": "Shell",
"bytes": "3288"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `PolyProjectionPredicate` type in crate `rustc_trans`.">
<meta name="keywords" content="rust, rustlang, rust-lang, PolyProjectionPredicate">
<title>rustc_trans::middle::ty::PolyProjectionPredicate - Rust</title>
<link rel="stylesheet" type="text/css" href="../../../main.css">
<link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<a href='../../../rustc_trans/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../../index.html'>rustc_trans</a>::<wbr><a href='../index.html'>middle</a>::<wbr><a href='index.html'>ty</a></p><script>window.sidebarCurrent = {name: 'PolyProjectionPredicate', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content type">
<h1 class='fqn'><span class='in-band'><a href='../../index.html'>rustc_trans</a>::<wbr><a href='../index.html'>middle</a>::<wbr><a href='index.html'>ty</a>::<wbr><a class='type' href=''>PolyProjectionPredicate</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'>
<a id="collapse-all" href="#">[-]</a> <a id="expand-all" href="#">[+]</a>
</span><a id='src-214375' href='../../../rustc/middle/ty/type.PolyProjectionPredicate.html?gotosrc=214375'>[src]</a></span></h1>
<pre class='rust typedef'>type PolyProjectionPredicate<'tcx> = <a class='struct' href='../../../rustc_trans/middle/ty/struct.Binder.html' title='rustc_trans::middle::ty::Binder'>Binder</a><<a class='struct' href='../../../rustc_trans/middle/ty/struct.ProjectionPredicate.html' title='rustc_trans::middle::ty::ProjectionPredicate'>ProjectionPredicate</a><'tcx>>;</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
</div>
</div>
<script>
window.rootPath = "../../../";
window.currentCrate = "rustc_trans";
window.playgroundUrl = "";
</script>
<script src="../../../jquery.js"></script>
<script src="../../../main.js"></script>
<script async src="../../../search-index.js"></script>
</body>
</html> | {
"content_hash": "1ccfbc00e7814d3166ec445f1f3c537e",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 395,
"avg_line_length": 44.32631578947368,
"alnum_prop": 0.5573497981477084,
"repo_name": "ArcherSys/ArcherSys",
"id": "d924cb27d0b1fde37e8abaf9f49b0be0a178bd90",
"size": "4211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Rust/share/doc/rust/html/rustc_trans/middle/ty/type.PolyProjectionPredicate.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
require 'rails_helper'
describe Api::V1::Props do
let(:user) { create(:user) }
let(:receivers) { create_list(:user, 3) }
describe 'GET /api/v1/props' do
context 'user is a guest' do
it 'returns unathorized response' do
get '/api/v1/props'
expect(response).to have_http_status(401)
end
end
context 'user is signed in' do
let(:params) { { propser_id: user.id }.as_json }
let!(:props) { create_list(:prop, 2, propser: user) }
before do
sign_in(user)
get '/api/v1/props', params
end
after { sign_out }
it 'returns search result' do
results = json_response['props']
expect(results.class).to be Array
expect(results.count).to eq 2
end
it 'returns meta key with pagination data' do
results = json_response['meta']
expect(results['current_page']).to eq 1
expect(results['total_count']).to eq 2
expect(results['total_pages']).to eq 1
end
end
end
describe 'GET /api/v1/props/total' do
context 'user is a guest' do
it 'returns unathorized response' do
get '/api/v1/props/total'
expect(response).to have_http_status(401)
end
end
context 'user is signed in' do
let!(:props) { create_list(:prop, 3, propser: user) }
before do
sign_in(user)
get '/api/v1/props/total'
end
after { sign_out }
it 'returns props count' do
expect(json_response).to eq 3
end
end
end
describe 'POST /api/v1/props' do
context 'user is a guest' do
it 'returns unathorized response' do
post '/api/v1/props'
expect(response).to have_http_status(401)
end
end
context 'user is signed in' do
before do
sign_in(user)
allow_any_instance_of(Notifier::SlackNotifier).to receive(:notify).and_return(double(ping: true))
post '/api/v1/props', prop_params
end
after { sign_out }
context 'with valid attributes' do
let(:prop_params) { { user_ids: receivers.map(&:id).join(','), body: 'sample text' }.as_json }
it 'returns success' do
expect(response).to have_http_status(:success)
end
it 'adds new prop to database' do
expect(Prop.all.count).to eq 1
expect(Prop.first.body).to eq 'sample text'
end
end
end
end
describe 'POST /api/v1/props/:prop_id/upvotes' do
let(:prop) { create(:prop) }
context 'user is a guest' do
it 'returns unathorized response' do
post "/api/v1/props/#{prop.id}/upvotes"
expect(response).to have_http_status(401)
end
end
context 'user is signed in' do
before { sign_in(user) }
after { sign_out }
it 'increases prop upvotes count by 1' do
post "/api/v1/props/#{prop.id}/upvotes"
expect(json_response['upvotes_count']).to eq 1
end
end
end
describe 'DELETE /api/v1/props/:prop_id/undo_upvotes' do
let(:prop) { create(:prop) }
let(:user2) { create(:user) }
let(:upvote) { create(:upvote, prop: prop, user: user2) }
context 'user is a guest' do
it 'returns unathorized response' do
delete "/api/v1/props/#{prop.id}/undo_upvotes"
expect(response).to have_http_status(401)
end
end
context 'user tries to undo upvote of different user' do
before { sign_in(user2) }
after { sign_out }
it 'undoes the upvote' do
delete "/api/v1/props/#{prop.id}/undo_upvotes"
expect(json_response['errors']).to eq(I18n.t('props.errors.no_upvote'))
end
end
context 'user undoes own upvote' do
before { sign_in(user) }
after { sign_out }
it 'undoes the upvote' do
delete "/api/v1/props/#{prop.id}/undo_upvotes"
expect(json_response['errors']).to eq(I18n.t('props.errors.no_upvote'))
end
end
end
end
| {
"content_hash": "be362410a33587a3ba3d5f2a30523727",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 105,
"avg_line_length": 26.604026845637584,
"alnum_prop": 0.5900605449041373,
"repo_name": "mic-kul/props",
"id": "1dacf5c9646ab07735e8e1ba52ad07637c086955",
"size": "3964",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/requests/api/v1/props_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3450"
},
{
"name": "CoffeeScript",
"bytes": "29383"
},
{
"name": "HTML",
"bytes": "11267"
},
{
"name": "JavaScript",
"bytes": "31912"
},
{
"name": "Ruby",
"bytes": "71066"
}
],
"symlink_target": ""
} |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseCreationForPIWebAPI
{
public class PIWebAPIWrapper
{
private static string base_url = "https://marc-web-sql.marc.net/piwebapi/";
public static string GetAssetDatabaseWebId(string piSystemName, string afDatabaseName)
{
dynamic jsonObj = jsonObj = MakeGetRequest(base_url + @"assetdatabases?path=\\" + piSystemName + @"\" + afDatabaseName);
string json = jsonObj.ToString();
int intResult = 0;
bool result = Int32.TryParse(json, out intResult);
if (result == false)
{
return jsonObj.WebId.Value;
}
else
{
return null;
}
}
public static string GetPISystemWebId(string piSystemName)
{
dynamic jsonObj = jsonObj = MakeGetRequest(base_url + @"assetservers?path=\\" + piSystemName);
return jsonObj.WebId.Value;
}
public static int CreateAssetDatabase(string piSystemName, string afDatabaseName)
{
string piSystemWebId = GetPISystemWebId(piSystemName);
int statusCode = -1;
string url = base_url + "assetservers/" + piSystemWebId + "/assetdatabases";
string postData = "{\"Name\": \"" + afDatabaseName + "\", \"Description\": \"Database of the PI Web API white paper\"}";
MakePostRequest(url, postData, out statusCode);
return statusCode;
}
public static string GetElementTemplateWebId(string piSystemName, string afDatabaseName, string afElementTemplateName)
{
string elementTemplatePath = @"\\" + piSystemName + @"\" + afDatabaseName + @"\ElementTemplates[" + afElementTemplateName + "]";
dynamic jsonObj = MakeGetRequest(base_url + @"elementtemplates?path=" + elementTemplatePath);
return jsonObj.WebId.Value;
}
public static string GetElementWebId(string elementPath)
{
dynamic jsonObj = MakeGetRequest(base_url + @"elements?path=" + elementPath);
return jsonObj.WebId.Value;
}
public static int CreateElement(string afElementName, string webId, bool onRoot, string templateName = null)
{
int statusCode = -1;
string url = string.Empty;
string postData = "{\"Name\": \"" + afElementName + "\"}";
if (templateName != null)
{
postData = "{\"Name\": \"" + afElementName + "\", \"TemplateName\": \"" + templateName + "\"}";
}
if (onRoot == true)
{
url = base_url + "assetdatabases/" + webId + "/elements";
}
else
{
url = base_url + "elements/" + webId + "/elements";
}
MakePostRequest(url, postData, out statusCode);
return statusCode;
}
public static int CreateElementTemplate(string afElementTemplateName, string assetdatabasesWebId)
{
int statusCode = -1;
string postData = "{\"Name\": \"" + afElementTemplateName + "\"}";
string url = base_url + "assetdatabases/" + assetdatabasesWebId + "/elementtemplates";
MakePostRequest(url, postData, out statusCode);
return statusCode;
}
public static int CreateAttributeTemplate(string elementTemplateWebId, string afAttributeTemplateName, string uomString, string piServerName, string attributeType)
{
int statusCode = -1;
string postData = "{\"Name\": \"" + afAttributeTemplateName + "\",\"Type\": \"" + attributeType + "\",\"DefaultUnitsName\": \"" + uomString + "\",\"DataReferencePlugIn\": \"PI Point\", \"ConfigString\": \"\\\\\\\\" + piServerName + "\\\\%Element%_%Attribute%\"}";
string url = base_url + "elementtemplates/" + elementTemplateWebId + "/attributetemplates";
MakePostRequest(url, postData, out statusCode);
return statusCode;
}
internal static dynamic MakeGetRequest(string url)
{
WebRequest request = WebRequest.Create(url);
//Basic Authentication
request.Credentials = new NetworkCredential("username", "password");
//Kerberos
//request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
int statusCode = (int)((HttpWebResponse)ex.Response).StatusCode;
return (dynamic)statusCode;
}
using (StreamReader sw = new StreamReader(response.GetResponseStream()))
{
using (JsonTextReader reader = new JsonTextReader(sw))
{
return JObject.ReadFrom(reader);
}
}
}
internal static void MakePostRequest(string url, string postData, out int statusCode)
{
WebRequest request = WebRequest.Create(url);
((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";
request.Method = "POST";
//Basic Authentication
request.Credentials = new NetworkCredential("username", "password");
//Kerberos
//request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
statusCode = Convert.ToInt32(((System.Net.HttpWebResponse)(response)).StatusCode);
}
}
}
| {
"content_hash": "5059b462500003b85d2e603b91cbf30d",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 276,
"avg_line_length": 38.63354037267081,
"alnum_prop": 0.5813504823151125,
"repo_name": "pthivierge/PI-Web-API-White-Paper",
"id": "a637ed2eb9cb5cdf87f5cc233932b853552e8de4",
"size": "6222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Chapter 5/MigratingToPIWebAPI/DatabaseCreationForPIWebAPI/PIWebAPIWrapper.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "113"
},
{
"name": "C#",
"bytes": "34426"
},
{
"name": "CSS",
"bytes": "4515"
},
{
"name": "HTML",
"bytes": "4973"
},
{
"name": "Java",
"bytes": "3855"
},
{
"name": "JavaScript",
"bytes": "18523"
},
{
"name": "Matlab",
"bytes": "2695"
},
{
"name": "PHP",
"bytes": "4155"
},
{
"name": "R",
"bytes": "1817"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menuContext_update"
android:icon="@drawable/pencil"
android:title="@string/menuContext_update"
app:showAsAction="ifRoom" />
<item
android:id="@+id/menuContext_delete"
android:icon="@drawable/delete"
android:title="@string/menuContext_delete"
app:showAsAction="ifRoom" />
</menu> | {
"content_hash": "cf7b98066b11737f728b00941c2a85c3",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 64,
"avg_line_length": 38.142857142857146,
"alnum_prop": 0.6423220973782772,
"repo_name": "JMedinilla/CondominApp",
"id": "79d5ed3aeabfd2174640514e95551c340467d6c5",
"size": "534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/menu/menu_context_list.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "215004"
}
],
"symlink_target": ""
} |
USING_NS_CC;
// the class inherit from TestScene
// every Scene each test used must inherit from TestScene,
// make sure the test have the menu item for back to main menu
class ActionsTestScene : public TestScene
{
public:
virtual void runThisTest();
};
class ActionsDemo : public BaseTest
{
protected:
Sprite* _grossini;
Sprite* _tamara;
Sprite* _kathia;
public:
virtual void onEnter();
virtual void onExit();
void centerSprites(unsigned int numberOfSprites);
void alignSpritesLeft(unsigned int numberOfSprites);
virtual std::string title();
virtual std::string subtitle();
void restartCallback(Object* sender);
void nextCallback(Object* sender);
void backCallback(Object* sender);
};
class ActionManual : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionMove : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionScale : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionSkew : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRotationalSkew : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRotationalSkewVSStandardSkew : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionSkewRotateScale : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRotate : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionJump : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionBezier : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionBlink : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionFade : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionTint : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionAnimate : public ActionsDemo
{
public:
virtual void onEnter();
virtual void onExit();
virtual std::string title();
virtual std::string subtitle();
};
class ActionSequence : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionSequence2 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
void callback1();
void callback2(Node* sender);
void callback3(Node* sender, long data);
};
class ActionSpawn : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionReverse : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRepeat : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionDelayTime : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionReverseSequence : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionReverseSequence2 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionOrbit : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRemoveSelf : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRepeatForever : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
void repeatForever(Node* pTarget);
};
class ActionRotateToRepeat : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionRotateJerk : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
};
class ActionCallFuncN : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
void callback(Node* sender);
};
class ActionCallFuncND : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
void doRemoveFromParentAndCleanup(Node* sender, bool cleanup);
};
class ActionCallFuncO : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
void callback(Node* object, bool cleanup);
};
class ActionCallFunction : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
void callback1();
void callback2(Node* pTarget);
void callback3(Node* pTarget, long data);
};
class ActionFollow : public ActionsDemo
{
public:
virtual void onEnter();
virtual void draw();
virtual std::string subtitle();
};
class ActionTargeted : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class ActionTargetedReverse : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class ActionStacked : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
virtual void addNewSpriteWithCoords(Point p);
virtual void runActionsInSprite(Sprite* sprite);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
};
class ActionMoveStacked : public ActionStacked
{
public:
virtual std::string title();
virtual void runActionsInSprite(Sprite* sprite);
};
class ActionMoveJumpStacked : public ActionStacked
{
public:
virtual std::string title();
virtual void runActionsInSprite(Sprite* sprite);
};
class ActionMoveBezierStacked : public ActionStacked
{
public:
virtual std::string title();
virtual void runActionsInSprite(Sprite* sprite);
};
class ActionCatmullRomStacked : public ActionsDemo
{
public:
virtual ~ActionCatmullRomStacked();
virtual void draw();
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
private:
PointArray* _array1;
PointArray* _array2;
};
class ActionCardinalSplineStacked : public ActionsDemo
{
public:
virtual ~ActionCardinalSplineStacked();
virtual void draw();
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
private:
PointArray* _array;
};
class Issue1305 : public ActionsDemo
{
public:
virtual void onEnter();
virtual void onExit();
void log(Node* sender);
void addSprite(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
Sprite* _spriteTmp;
};
class Issue1305_2 : public ActionsDemo
{
public:
virtual void onEnter();
void printLog1();
void printLog2();
void printLog3();
void printLog4();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1288 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1288_2 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1327 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
virtual std::string title();
void logSprRotation(Sprite* sender);
};
class Issue1398 : public ActionsDemo
{
public:
void incrementInteger();
void incrementIntegerCallback(void* data);
virtual void onEnter();
virtual std::string subtitle();
virtual std::string title();
private:
int _testInteger;
};
class ActionCatmullRom : public ActionsDemo
{
public:
~ActionCatmullRom();
virtual void onEnter();
virtual void draw();
virtual std::string subtitle();
virtual std::string title();
private:
PointArray *_array1;
PointArray *_array2;
};
class ActionCardinalSpline : public ActionsDemo
{
public:
~ActionCardinalSpline();
virtual void onEnter();
virtual void draw();
virtual std::string subtitle();
virtual std::string title();
private:
PointArray *_array;
};
class PauseResumeActions : public ActionsDemo
{
public:
PauseResumeActions();
virtual ~PauseResumeActions();
virtual void onEnter();
virtual std::string subtitle();
virtual std::string title();
void pause(float dt);
void resume(float dt);
private:
Set *_pausedTargets;
};
#endif
| {
"content_hash": "250bd9b08771ed0f4622a4c2a2fb89e7",
"timestamp": "",
"source": "github",
"line_count": 454,
"max_line_length": 82,
"avg_line_length": 19.676211453744493,
"alnum_prop": 0.6961826933840815,
"repo_name": "gibtang/CCNSCoding",
"id": "c064ee3436e9053496ec7deb814553bf508e0af0",
"size": "9063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "52298226"
},
{
"name": "C#",
"bytes": "3520"
},
{
"name": "C++",
"bytes": "26358013"
},
{
"name": "CSS",
"bytes": "27667"
},
{
"name": "Clojure",
"bytes": "8891"
},
{
"name": "F#",
"bytes": "5688"
},
{
"name": "IDL",
"bytes": "11995"
},
{
"name": "Java",
"bytes": "285202"
},
{
"name": "JavaScript",
"bytes": "36912223"
},
{
"name": "Lua",
"bytes": "558824"
},
{
"name": "Objective-C",
"bytes": "1387273"
},
{
"name": "Perl",
"bytes": "13787"
},
{
"name": "Python",
"bytes": "1629302"
},
{
"name": "Ruby",
"bytes": "120900"
},
{
"name": "Shell",
"bytes": "1517397"
},
{
"name": "TeX",
"bytes": "60330"
},
{
"name": "Visual Basic",
"bytes": "2884"
}
],
"symlink_target": ""
} |
/* $NetBSD: gai_strerror.c,v 1.1.1.2 2013/04/06 15:57:51 christos Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: /repoman/r/ncvs/src/lib/libc/net/gai_strerror.c,v 1.1 2005/04/06 12:45:51 ume Exp $");
*/
#ifdef WIN32
#include <ws2tcpip.h>
#else
#include <netdb.h>
#endif
/* Entries EAI_ADDRFAMILY (1) and EAI_NODATA (7) are obsoleted, but left */
/* for backward compatibility with userland code prior to 2553bis-02 */
static char *ai_errlist[] = {
"Success", /* 0 */
"Address family for hostname not supported", /* 1 */
"Temporary failure in name resolution", /* EAI_AGAIN */
"Invalid value for ai_flags", /* EAI_BADFLAGS */
"Non-recoverable failure in name resolution", /* EAI_FAIL */
"ai_family not supported", /* EAI_FAMILY */
"Memory allocation failure", /* EAI_MEMORY */
"No address associated with hostname", /* 7 */
"hostname nor servname provided, or not known", /* EAI_NONAME */
"servname not supported for ai_socktype", /* EAI_SERVICE */
"ai_socktype not supported", /* EAI_SOCKTYPE */
"System error returned in errno", /* EAI_SYSTEM */
"Invalid value for hints", /* EAI_BADHINTS */
"Resolved protocol is unknown" /* EAI_PROTOCOL */
};
#ifndef EAI_MAX
#define EAI_MAX (sizeof(ai_errlist)/sizeof(ai_errlist[0]))
#endif
/* on MingW, gai_strerror is available.
We need to compile gai_strerrorA only for Cygwin
*/
#ifndef gai_strerror
char *
WSAAPI gai_strerrorA(int ecode)
{
if (ecode >= 0 && ecode < EAI_MAX)
return ai_errlist[ecode];
return "Unknown error";
}
#endif /* gai_strerror */ | {
"content_hash": "e6c7614c69041e57da72e5746a259ad3",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 106,
"avg_line_length": 36.89411764705882,
"alnum_prop": 0.7152423469387755,
"repo_name": "execunix/vinos",
"id": "a5eb3984e7906cf5563c9ee850c80388fef59ab2",
"size": "3136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "external/bsd/libpcap/dist/Win32/Src/gai_strerror.c",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Game } from './game';
@Injectable()
export class GameService {
private gameListURL = 'https://nodev.se/data/hs2017.json'
private gameBaseURL = 'https://nodev.se/data/'
constructor(private http: Http) { }
getGamesList() {
return this.http.get(this.gameListURL)
.toPromise()
.then(response => response.json().games as String[])
.catch(this.handleError);
}
getGameData(game: String) {
return this.http.get(this.gameBaseURL+game+'.json')
.toPromise()
.then(response => response.json() as Game)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
| {
"content_hash": "b78650ccc80a503a9b7a643b797fb78e",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 72,
"avg_line_length": 28.666666666666668,
"alnum_prop": 0.6268498942917548,
"repo_name": "togus/uhc",
"id": "d06804f85c9d48e55046381cf21b32b4bf24e8d5",
"size": "946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/game.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2718"
},
{
"name": "HTML",
"bytes": "11673"
},
{
"name": "JavaScript",
"bytes": "1884"
},
{
"name": "TypeScript",
"bytes": "16797"
}
],
"symlink_target": ""
} |
import React from 'react'
import {Route, IndexRoute} from 'react-router'
import Root from './containers/Root'
export default (
<Route path="/" component={Root}>
<IndexRoute component={Root} />
</Route>
)
| {
"content_hash": "4e9c8c0ef92dc0cfa2c06bdfd93edc5f",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 46,
"avg_line_length": 23.666666666666668,
"alnum_prop": 0.6901408450704225,
"repo_name": "simongfxu/violet",
"id": "829af7e1262b2ed786f1ea7888c6637889e89abd",
"size": "213",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26300"
},
{
"name": "HTML",
"bytes": "874"
},
{
"name": "JavaScript",
"bytes": "113677"
}
],
"symlink_target": ""
} |
\comment (c)2017-2020, Cris Luengo.
\comment Based on original DIPimage user manual: (c)1999-2014, Delft University of Technology.
\comment Licensed under the Apache License, Version 2.0 [the "License"];
\comment you may not use this file except in compliance with the License.
\comment You may obtain a copy of the License at
\comment
\comment http://www.apache.org/licenses/LICENSE-2.0
\comment
\comment Unless required by applicable law or agreed to in writing, software
\comment distributed under the License is distributed on an "AS IS" BASIS,
\comment WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\comment See the License for the specific language governing permissions and
\comment limitations under the License.
\page sec_dum_mex_files Writing MEX-files that use *DIPlib*
A MEX-file is a compiled C, C++ or Fortran function (C++ if it uses *DIPlib*) that
can be called from *MATLAB* as if it were a normal *MATLAB* function. It must take
*MATLAB* data as input and produce *MATLAB* data as output. To call a *DIPlib* function
from the MEX-file, the *MATLAB* data must be converted to the right C++ types.
This chapter describes the functionality we wrote for this purpose.
It is assumed that the reader is familiar with basic MEX-files (see the
[*MATLAB* MEX-file documentation](https://www.mathworks.com/help/matlab/matlab-api-for-c.html)
if not) and basic *DIPlib* (see the \ref index "documentation" if not).
We exclusively use [the C API](https://www.mathworks.com/help/matlab/cc-mx-matrix-library.html).
\section sec_dum_mex_files_dml The *DIPlib--MATLAB* interface
The header file \ref "dip_matlab_interface.h" contains a series of functions that can
be used to convert *MATLAB* types to *DIPlib* types and vice versa. These functions
make it very easy to write a *MATLAB* interface to *DIPlib* functions (and this is
its main purpose), but could be used for other purposes too.
All its functionality is in the \ref dml namespace.
\subsection sec_dum_mex_files_dml_output_images Output images
The main trick that it can do is prepare a \ref dip::Image object that, when forged
by a *DIPlib* function, will have *MATLAB* allocate the memory for the pixels,
such that no copy needs to be made when this image is returned to *MATLAB*. For
this, create an object of type \ref dml::MatlabInterface. Its \ref dml::MatlabInterface::NewImage
function creates a raw image that can be forged (or passed as output image to
any *DIPlib* function). The \ref dml::GetArray(dip::Image const&, bool) function
can then be used to obtain a pointer to the `mxArray` containing a `dip_image`
object with the same pixel data. Note that the `dml::MatlabInterface` object
needs to exist throughout this process, as it owns the data until `dml::GetArray`
extracts it.
This is a skeleton MEX-file that outputs such an image:
```cpp
#include <dip_matlab_interface.h> // Always include this, it includes diplib.h and mex.h
void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] ) {
try {
// Create an output image
dml::MatlabInterface mi;
dip::Image out = mi.NewImage();
// Forge it
out.ReForge( { 256, 256 }, 1, dip::DT_UINT8 );
out.Fill( 0 ); // Usually you'd do something more exciting here!
// Retrieve the MATLAB array for the output image (it's a dip_image object)
plhs[ 0 ] = dml::GetArray( out );
} DML_CATCH
}
```
The documentation to \ref dml::MatlabInterface gives more details about how to use
the images created in this way.
\subsection sec_dum_mex_files_dml_input_images Input images
The function \ref dml::GetImage takes an `mxArray` pointer, checks it for validity,
and returns a \ref dip::Image object that shares data with the `mxArray` (except in
exceptional circumstances: complex-valued numeric arrays must be copied because
their storage is different in *MATLAB* and *DIPlib*; complex-valued `dip_image`
objects are not copied).
For example, one can add the following line to the `mexFunction` above:
```cpp
dip::Image const in = ( nrhs > 0 ) ? dml::GetImage( prhs[ 0 ] ) : dip::Image();
```
This line calls \ref dml::GetImage only if `prhs[0]` actually exists. If not, it
creates a raw image object. You should always check `nrhs` before reading any of
the `prhs` elements. Likewise, you should always check `nlhs` before assigning
to any of the `plhs` elements except the first one (`plhs` always has at least
one element, even if `nlhs == 0`).
\subsection sec_dum_mex_files_dml_input_data Converting other types
There exist similar `Get...` functions for just about every *DIPlib* type, for example
\ref dml::GetFloat, \ref dml::GetFloatArray or \ref dml::GetFloatCoordinateArray. See
the documentation to the \ref dml namespace for a complete list. These
take an `mxArray` pointer as input, validate it, and output a value of the appropriate
type. If the validation fails, an exception is thrown.
There exist also a series of \ref dml::GetArray functions that do the reverse process:
they take a value of any type typically returned by a *DIPlib* function, and
convert it to an `mxArray`, returning its pointer. Note that *MATLAB* always takes
care of freeing any `mxArray` objects created by the MEX-file, there is no need
to do any manual memory management.
These data conversion functions all copy the data (only images are passed without
copy, other data is typically not large enough to matter).
For more complex examples of MEX-files, see
[`examples/external_interfaces/matlab_mex_example.cpp`](https://github.com/DIPlib/diplib/tree/master/examples/external_interfaces/matlab_mex_example.cpp),
as well as the *DIPimage* MEX-files in
[`dipimage/private/`](https://github.com/DIPlib/diplib/tree/master/dipimage/private) and
[`dipimage/@dip_image/private`](https://github.com/DIPlib/diplib/tree/master/dipimage/%40dip_image/private).
\section sec_dum_mex_files_mex Compiling a MEX-file
To compile a MEX-file like the one shown in the previous section, save it for example
as `myfunction.cpp`, and use the `dipmex` function in *MATLAB*:
```matlab
dipmex myfunction.cpp
```
This function simply calls the `mex` function, adding arguments to allow the compiler
to find the *DIPlib* header files and to link in the *DIPlib* library. Because this
is C++, it is important that the same compiler (and often also the same version) be
used to build the MEX-file as was used to build the *DIPlib* library. We recommend
that you build the library yourself. `mex -setup C++` should be used to configure
*MATLAB*'s `mex` command to use the right compiler.
The result of the `dipmex` command above is a MEX-file called `myfunction`. You can
call it like any other *MATLAB* function:
```matlab
img = myfunction; % it has no input arguments
```
If your MEX-file needs more source files and/or libraries, simply add them to the
`dipmex` command. You can also add [other arguments for `mex`](https://www.mathworks.com/help/matlab/ref/mex.html) here:
```matlab
dipmex myfunction.cpp other_source.cpp /home/me/mylibs/libstuff.a -I/home/me/mylibs/
```
The MEX-file will always have as name the name of the first source file in the list,
unless an `-output mexname` argument is given.
| {
"content_hash": "1798e5a92714b33398c53a104c0a8353",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 154,
"avg_line_length": 47.22222222222222,
"alnum_prop": 0.7539100346020762,
"repo_name": "DIPlib/diplib",
"id": "6a15e8014e2441e422a522b95c8c9160801d68b4",
"size": "7225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/src/DIPimage/09_mex_files.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4572"
},
{
"name": "C",
"bytes": "3829"
},
{
"name": "C++",
"bytes": "6124225"
},
{
"name": "CMake",
"bytes": "133083"
},
{
"name": "Java",
"bytes": "22792"
},
{
"name": "M",
"bytes": "906"
},
{
"name": "MATLAB",
"bytes": "1322116"
},
{
"name": "NSIS",
"bytes": "5595"
},
{
"name": "Python",
"bytes": "16657"
},
{
"name": "Shell",
"bytes": "10142"
}
],
"symlink_target": ""
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.beastiebots.ftcScoringLite.blockParty;
import org.beastiebots.ftcScoringLite.blockParty.enums.*;
import javax.swing.DefaultComboBoxModel;
/**
*
* @author Jacob
*/
public class BlockPartyScorePanel extends javax.swing.JPanel {
private BlockPartyScore score = new BlockPartyScore();
/**
* Creates new form AllianceScore
*/
public BlockPartyScorePanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
irPos = new javax.swing.JComboBox();
jLabel9 = new javax.swing.JLabel();
auto = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
auto1Pos = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
auto1Block = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
auto2Pos = new javax.swing.JComboBox();
jLabel7 = new javax.swing.JLabel();
auto2Block = new javax.swing.JComboBox();
jLabel8 = new javax.swing.JLabel();
blocks = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
pendulum1 = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
pendulum2 = new javax.swing.JSpinner();
jLabel13 = new javax.swing.JLabel();
pendulum3 = new javax.swing.JSpinner();
jLabel14 = new javax.swing.JLabel();
pendulum4 = new javax.swing.JSpinner();
jLabel15 = new javax.swing.JLabel();
low = new javax.swing.JSpinner();
jLabel19 = new javax.swing.JLabel();
balanced = new javax.swing.JCheckBox();
endgame = new javax.swing.JPanel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
lift2 = new javax.swing.JCheckBox();
lift1 = new javax.swing.JCheckBox();
flag = new javax.swing.JComboBox();
penalties = new javax.swing.JPanel();
jLabel23 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
major = new javax.swing.JSpinner();
minor = new javax.swing.JSpinner();
irPos.setModel(new DefaultComboBoxModel(AutoBlock.valuesPendulum()));
irPos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
irPosActionPerformed(evt);
}
});
jLabel9.setText("IR Beacon Basket");
auto.setBorder(javax.swing.BorderFactory.createTitledBorder("Autonomous"));
jLabel5.setText("Block:");
auto1Pos.setModel(new DefaultComboBoxModel(AutoPosition.values()));
auto1Pos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
auto1PosActionPerformed(evt);
}
});
jLabel3.setText("Robot 1");
auto1Block.setModel(new DefaultComboBoxModel(AutoBlock.values()));
auto1Block.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
auto1BlockActionPerformed(evt);
}
});
jLabel4.setText("Position:");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(auto1Pos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(auto1Block, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel3))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(auto1Pos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(auto1Block, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jLabel6.setText("Block:");
auto2Pos.setModel(new DefaultComboBoxModel(AutoPosition.values()));
auto2Pos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
auto2PosActionPerformed(evt);
}
});
jLabel7.setText("Robot 2");
auto2Block.setModel(new DefaultComboBoxModel(AutoBlock.values()));
auto2Block.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
auto2BlockActionPerformed(evt);
}
});
jLabel8.setText("Position:");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(auto2Pos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(auto2Block, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(auto2Pos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(auto2Block, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout autoLayout = new javax.swing.GroupLayout(auto);
auto.setLayout(autoLayout);
autoLayout.setHorizontalGroup(
autoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(autoLayout.createSequentialGroup()
.addGroup(autoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
autoLayout.setVerticalGroup(
autoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(autoLayout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
blocks.setBorder(javax.swing.BorderFactory.createTitledBorder("Blocks"));
jLabel10.setText("Pendulum Goals");
jLabel11.setText("1:");
pendulum1.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99, 1));
pendulum1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
pendulum1StateChanged(evt);
}
});
jLabel12.setText("2:");
pendulum2.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99, 1));
pendulum2.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
pendulum2StateChanged(evt);
}
});
jLabel13.setText("3:");
pendulum3.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99, 1));
pendulum3.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
pendulum3StateChanged(evt);
}
});
jLabel14.setText("4:");
pendulum4.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99, 1));
pendulum4.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
pendulum4StateChanged(evt);
}
});
jLabel15.setText("Low goal:");
low.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99, 1));
low.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
lowStateChanged(evt);
}
});
jLabel19.setText("Balanced:");
balanced.setMargin(new java.awt.Insets(0, 0, 0, 0));
balanced.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
balancedActionPerformed(evt);
}
});
javax.swing.GroupLayout blocksLayout = new javax.swing.GroupLayout(blocks);
blocks.setLayout(blocksLayout);
blocksLayout.setHorizontalGroup(
blocksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(blocksLayout.createSequentialGroup()
.addContainerGap()
.addGroup(blocksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addGroup(blocksLayout.createSequentialGroup()
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pendulum1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pendulum2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pendulum3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pendulum4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(balanced))
.addGroup(blocksLayout.createSequentialGroup()
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(low, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
blocksLayout.setVerticalGroup(
blocksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(blocksLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(blocksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(balanced, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(blocksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(pendulum1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12)
.addComponent(pendulum2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)
.addComponent(pendulum3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel14)
.addComponent(pendulum4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel19)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(blocksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(low, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
endgame.setBorder(javax.swing.BorderFactory.createTitledBorder("Endgame"));
jLabel16.setText("Flag:");
jLabel17.setText("Robot 1 lifted:");
jLabel18.setText("Robot 2 lifted:");
lift2.setMargin(new java.awt.Insets(0, 0, 0, 0));
lift2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lift2ActionPerformed(evt);
}
});
lift1.setMargin(new java.awt.Insets(0, 0, 0, 0));
lift1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lift1ActionPerformed(evt);
}
});
flag.setModel(new DefaultComboBoxModel(FlagHeight.values()));
flag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
flagActionPerformed(evt);
}
});
javax.swing.GroupLayout endgameLayout = new javax.swing.GroupLayout(endgame);
endgame.setLayout(endgameLayout);
endgameLayout.setHorizontalGroup(
endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(endgameLayout.createSequentialGroup()
.addGroup(endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(endgameLayout.createSequentialGroup()
.addGroup(endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel18)
.addComponent(jLabel17))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lift2)
.addComponent(lift1)))
.addGroup(endgameLayout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(flag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
endgameLayout.setVerticalGroup(
endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(endgameLayout.createSequentialGroup()
.addGroup(endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(flag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(endgameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(endgameLayout.createSequentialGroup()
.addComponent(lift1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lift2))
.addGroup(endgameLayout.createSequentialGroup()
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel18))))
);
penalties.setBorder(javax.swing.BorderFactory.createTitledBorder("Penalites"));
jLabel23.setText("Major:");
jLabel25.setText("Minor:");
major.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
major.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
majorStateChanged(evt);
}
});
minor.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
minor.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
minorStateChanged(evt);
}
});
javax.swing.GroupLayout penaltiesLayout = new javax.swing.GroupLayout(penalties);
penalties.setLayout(penaltiesLayout);
penaltiesLayout.setHorizontalGroup(
penaltiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(penaltiesLayout.createSequentialGroup()
.addGroup(penaltiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(penaltiesLayout.createSequentialGroup()
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(minor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(penaltiesLayout.createSequentialGroup()
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(major, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
penaltiesLayout.setVerticalGroup(
penaltiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(penaltiesLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(penaltiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(major, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(penaltiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25)
.addComponent(minor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 358, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(auto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(blocks, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(irPos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 222, Short.MAX_VALUE))
.addComponent(endgame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(penalties, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 564, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(irPos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(auto, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(blocks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(endgame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(penalties, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
private void irPosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_irPosActionPerformed
score.setIRgoal((AutoBlock)irPos.getSelectedItem());
}//GEN-LAST:event_irPosActionPerformed
private void auto1PosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_auto1PosActionPerformed
score.setAutoPos1((AutoPosition)auto1Pos.getSelectedItem());
}//GEN-LAST:event_auto1PosActionPerformed
private void auto1BlockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_auto1BlockActionPerformed
score.setAutoGoal1((AutoBlock)auto1Block.getSelectedItem());
}//GEN-LAST:event_auto1BlockActionPerformed
private void auto2PosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_auto2PosActionPerformed
score.setAutoPos2((AutoPosition)auto2Pos.getSelectedItem());
}//GEN-LAST:event_auto2PosActionPerformed
private void auto2BlockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_auto2BlockActionPerformed
score.setAutoGoal2((AutoBlock)auto2Block.getSelectedItem());
}//GEN-LAST:event_auto2BlockActionPerformed
private void pendulum1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pendulum1StateChanged
score.getPendulum().setBasket1((Integer)pendulum1.getValue());
}//GEN-LAST:event_pendulum1StateChanged
private void pendulum2StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pendulum2StateChanged
score.getPendulum().setBasket2((Integer)pendulum2.getValue());
}//GEN-LAST:event_pendulum2StateChanged
private void pendulum3StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pendulum3StateChanged
score.getPendulum().setBasket3((Integer)pendulum3.getValue());
}//GEN-LAST:event_pendulum3StateChanged
private void pendulum4StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pendulum4StateChanged
score.getPendulum().setBasket4((Integer)pendulum4.getValue());
}//GEN-LAST:event_pendulum4StateChanged
private void lowStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_lowStateChanged
score.getPendulum().setLow((Integer)low.getValue());
}//GEN-LAST:event_lowStateChanged
private void balancedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_balancedActionPerformed
score.getPendulum().setBalanced(balanced.isSelected());
}//GEN-LAST:event_balancedActionPerformed
private void lift2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lift2ActionPerformed
score.setRobot2Lifted(lift2.isSelected());
}//GEN-LAST:event_lift2ActionPerformed
private void lift1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lift1ActionPerformed
score.setRobot1Lifted(lift1.isSelected());
}//GEN-LAST:event_lift1ActionPerformed
private void flagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_flagActionPerformed
score.setFlagState((FlagHeight)flag.getSelectedItem());
}//GEN-LAST:event_flagActionPerformed
private void majorStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_majorStateChanged
score.setMajorPenalties((Integer)major.getValue());
}//GEN-LAST:event_majorStateChanged
private void minorStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_minorStateChanged
score.setMinorPenalies((Integer)minor.getValue());
}//GEN-LAST:event_minorStateChanged
public BlockPartyScore getScore() {
return score;
}
public void setScore(BlockPartyScore score) {
this.score = score;
irPos.setSelectedItem(score.getIRgoal());
auto1Block.setSelectedItem(score.getAutoGoal1());
auto2Block.setSelectedItem(score.getAutoGoal2());
auto1Pos.setSelectedItem(score.getAutoPos1());
auto2Pos.setSelectedItem(score.getAutoPos2());
pendulum1.setValue(score.getPendulum().getBasket1());
pendulum2.setValue(score.getPendulum().getBasket2());
pendulum3.setValue(score.getPendulum().getBasket3());
pendulum4.setValue(score.getPendulum().getBasket4());
low.setValue(score.getPendulum().getLow());
balanced.setSelected(score.getPendulum().isBalanced());
flag.setSelectedItem(score.getFlagState());
lift1.setSelected(score.isRobot1Lifted());
lift2.setSelected(score.isRobot2Lifted());
major.setValue(score.getMajorPenalties());
minor.setValue(score.getMinorPenalies());
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel auto;
private javax.swing.JComboBox auto1Block;
private javax.swing.JComboBox auto1Pos;
private javax.swing.JComboBox auto2Block;
private javax.swing.JComboBox auto2Pos;
private javax.swing.JCheckBox balanced;
private javax.swing.JPanel blocks;
private javax.swing.JPanel endgame;
private javax.swing.JComboBox flag;
private javax.swing.JComboBox irPos;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JCheckBox lift1;
private javax.swing.JCheckBox lift2;
private javax.swing.JSpinner low;
private javax.swing.JSpinner major;
private javax.swing.JSpinner minor;
private javax.swing.JPanel penalties;
private javax.swing.JSpinner pendulum1;
private javax.swing.JSpinner pendulum2;
private javax.swing.JSpinner pendulum3;
private javax.swing.JSpinner pendulum4;
// End of variables declaration//GEN-END:variables
}
| {
"content_hash": "37076b92f4ac308b5f6768060dfb1534",
"timestamp": "",
"source": "github",
"line_count": 623,
"max_line_length": 169,
"avg_line_length": 55.62279293739968,
"alnum_prop": 0.6687444088534903,
"repo_name": "hprobotics/ftc-scoring-lite",
"id": "ce8d6cce12921ea5ac0ce5d3116a2ab261399186",
"size": "34653",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FTCScoringLite/src/org/beastiebots/ftcScoringLite/blockParty/BlockPartyScorePanel.java",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package resource;
@SuppressWarnings("serial")
public class FethResourceException extends Exception {
public static final int ANIMATION = 0;
public static final int AUDIO = 1;
private int errorType;
private String url;
public FethResourceException(int errorType,String url){
this.errorType = errorType;
this.url = url;
}
@Override
public String getMessage(){
String txt = "";
if(errorType==ANIMATION){
txt = "Animation file is not found : " + url;
}else{
txt = "AudioClip file is not found : " + url;
}
return txt;
}
}
| {
"content_hash": "2719739af937a3ee0c488247725da6ed",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 56,
"avg_line_length": 21.26923076923077,
"alnum_prop": 0.6980108499095841,
"repo_name": "5731087821-PT/Project-Game",
"id": "e3eb117b2ff0784a553d0c535ebd5fe39ff8335d",
"size": "553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/resource/FethResourceException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "109357"
}
],
"symlink_target": ""
} |
package org.jabref.gui.fieldeditors;
import javafx.scene.control.TextInputControl;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class EditorValidator {
private final PreferencesService preferences;
public EditorValidator(PreferencesService preferences) {
this.preferences = preferences;
}
public void configureValidation(final ValidationStatus status, final TextInputControl textInput) {
if (preferences.getEntryEditorPreferences().shouldEnableValidation()) {
ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
validationVisualizer.setDecoration(new IconValidationDecorator());
validationVisualizer.initVisualization(status, textInput);
}
}
}
| {
"content_hash": "5a9b39d2fd121f4ace55a3889b15af16",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 102,
"avg_line_length": 36.57692307692308,
"alnum_prop": 0.7802313354363828,
"repo_name": "Siedlerchr/jabref",
"id": "6396e4711ac177088ac01982d3b8db2356077200",
"size": "951",
"binary": false,
"copies": "3",
"ref": "refs/heads/testFork",
"path": "src/main/java/org/jabref/gui/fieldeditors/EditorValidator.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "1751"
},
{
"name": "Batchfile",
"bytes": "138"
},
{
"name": "CSS",
"bytes": "40131"
},
{
"name": "GAP",
"bytes": "1466"
},
{
"name": "Groovy",
"bytes": "9355"
},
{
"name": "Java",
"bytes": "6070042"
},
{
"name": "PowerShell",
"bytes": "1688"
},
{
"name": "Python",
"bytes": "28937"
},
{
"name": "Ruby",
"bytes": "1115"
},
{
"name": "Shell",
"bytes": "5705"
},
{
"name": "TeX",
"bytes": "311257"
},
{
"name": "XSLT",
"bytes": "2185"
}
],
"symlink_target": ""
} |
struct Input;
struct Renderer;
struct UIntHashPair
{
uint32 key;
uint32 value;
};
struct UIntHashMap
{
struct UIntHashPair buckets[4096];
};
struct GameMemory
{
void *game_memory;
size_t game_memory_size;
void *render_memory;
size_t render_memory_size;
};
struct Camera
{
vec2 position;
float rotation;
float zoom;
vec2 move_velocity;
float zoom_velocity;
};
enum ShipTeam
{
TEAM_ALLY,
TEAM_ENEMY,
};
enum UnitFlags
{
UNIT_MOVE_ORDER = 0x01,
};
struct Path
{
// TODO: optimize space?
struct VisibilityNode *nodes[32];
uint32 node_count;
uint32 current_node_index;
vec2 start;
vec2 end;
};
struct Ship
{
uint32 id;
uint8 team;
uint32 flags;
vec2 position;
float rotation;
vec2 size;
vec2 move_velocity;
float rotation_velocity;
int32 health;
// TODO: expand on this
float fire_cooldown;
float fire_cooldown_timer;
struct Path path;
};
struct AABB
{
vec2 min;
vec2 max;
};
struct Projectile
{
uint32 owner;
uint8 team;
int32 damage;
vec2 position;
vec2 size;
vec2 velocity;
};
struct WorkingPathNode
{
struct VisibilityNode *node;
struct WorkingPathNode *parent;
float f_cost;
float g_cost;
float h_cost;
};
struct VisibilityNode
{
uint32 vertex_index;
// TODO: linked list if memory becomes an issue?
uint32 neighbor_indices[64];
uint32 neighbor_index_count;
};
struct VisibilityGraph
{
vec2 vertices[4096];
uint32 vertex_count;
struct VisibilityNode nodes[4096];
uint32 node_count;
};
struct Building
{
vec2 position;
vec2 size;
};
struct GameState
{
struct Camera camera;
//
// map
//
struct VisibilityGraph visibility_graph;
struct Building buildings[64];
uint32 building_count;
//
// ship
//
struct Ship ships[64];
uint32 ship_count;
uint32 ship_ids;
struct UIntHashMap ship_id_map;
uint32 selected_ships[256];
uint32 selected_ship_count;
//
// projectile
//
struct Projectile projectiles[256];
uint32 projectile_count;
};
void init_game(struct GameMemory *memory);
void tick_game(struct GameMemory *memory, struct Input *input, uint32 screen_width, uint32 screen_height, float dt);
void render_game(struct GameMemory *memory, struct Renderer *renderer, uint32 screen_width, uint32 screen_height);
| {
"content_hash": "095d4d7939d2755bc4758da7e0089aa5",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 116,
"avg_line_length": 14.520710059171599,
"alnum_prop": 0.6524042379788101,
"repo_name": "truncator/gx",
"id": "e1dbcae629b75257c5f62763fb3911e425f9965b",
"size": "2513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/gx.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "738199"
},
{
"name": "C++",
"bytes": "113557"
},
{
"name": "GLSL",
"bytes": "2390"
},
{
"name": "Makefile",
"bytes": "1144"
}
],
"symlink_target": ""
} |
* [Release 1: Summarization Questions](#release-1-summarization-questions)
* [Release 2: Mini-Challenges](#release-2-mini-challenges)
* [Challenge 4.2.1: Defining Variables](https://github.com/dasKevinHuang/phase-0/blob/master/week-4/defining-variables.rb)
* [Challenge 4.2.2: Simple String Methods](https://github.com/dasKevinHuang/phase-0/blob/master/week-4/simple-string.rb)
* [Challenge 4.2.3: Local Variables and Basic Arithmetical Expressions](https://github.com/dasKevinHuang/phase-0/blob/master/week-4/basic-math.rb)
* [Release 7: Reflection](#release-7-reflection)
### Release 1: Summarization Questions
####What does 'puts' do?
`puts` is a way to output to console with a new line at the end. Writing `puts` will return nil. Somewhat related to `puts` is `prints`, which will print to console, but without a new line.
`puts` and `print` are examples of how simple Ruby is to write code with.
To illustrate, consider the following code:
```
puts "Hello there!"
print "This second line will not print a new line at the end. "
puts "See? It's much easier in Ruby!"
```
This will output:
```
Hello there!
This second line will not print a new line at the end. See? It's much easier in Ruby!
```
You could compare this to C++ or Java, which are commonly used as languages taught to students.
C++
```
#include <iostream>
int main()
{
std::cout >> "Hello there!" >> endl;
std::cout >> "This second line will not print a new line at the end. ";
std::cout >> "See? It's much easier in Ruby!";
}
```
or
Java
```
public class Output{
public static void main(String[] args){
System.out.println("Hello there!");
System.out.print("This second line will not print a new line at the end. ");
System.out.print("See? It's much easier in Ruby!");
}
}
```
Notice how much easier it is to output this simple passage in Ruby compared to other common languages?
####What is an integer? What is a float?
An `integer` is a data type that can be any number without decimal points.
Here are a few examples of integers:
```
2332634643
2
5363
50005
```
You can initialize an integer variable using the *assignment operator* `=` by writing:
`int x = 12`
A `float` is a data type is a number with decimal points - or sometimes called `floating-point numbers`.
Here are a few examples of floats:
```
2.2
1000.4205005
0.336643
```
You can initialize a float variable with values using the *assignment operator* `=` by writing:
`x = 2.2`
####What is the difference between float and integer division? How would you explain the difference to someone who doesn't know anything about programming?
The major difference between float and integer division is the respect for decimal points. Integer division *will not* take account of decimal points or remainders when dividing, causing the result of `21 / 2` to be cut off at the decimal point resulting in `10`.
Float division will actually take the resulting decimal point into account and show the final result as `10.5`. This is important to take note of to avoid any mathematical logic errors.
### Release 2: Mini-Challenges
#### Program to calculate and output Hours in a year
Code
```ruby
days_in_year = 365
hours_per_day = 24
hours_per_year = days_in_year * hours_per_day
puts "Given " + days_in_year.to_s + " days in a year and " + hours_per_day.to_s + " hours per day,"
puts "We can calculate that there are " + hours_per_year.to_s + " hours in a year."
#Extra tip: When concatenating numbers and strings this way, you have to convert the object into a string before it can be used. The method .to_s will do this.
```
Output
```
Given 365 days in a year and 24 hours per day,
We can calculate that there are 8760 hours in a year.
```
#### Program to calculate Minutes in a decade
Code
```ruby
years_in_decade = 10
days_in_year = 365
hours_per_day = 24
minutes_per_hour = 60
minutes_in_decade = years_in_decade * days_in_year * hours_per_day * minutes_per_hour
puts "There are " + minutes_in_decade.to_s + " minutes in a decade."
```
Output
```
There are 5256000 minutes in a decade.
```
###Release 7: Reflection
####How does Ruby handle addition, subtraction, multiplication, and division of numbers?
Ruby handles addition, subtraction, multiplication, and division very easily. A developer can write code to make a ruby program calculate arithmetic operations by using arithmetic operators such as `+` `-` `*` `/` `%`.
####What is the difference between integers and floats?
Integers are numbers without decimal points.
Floats are numbers with decimal points - they are also callled floating-point numbers.
These are the main differences between the two. There are also some small arithmetic differences that must be taken to account before using them.
####What is the difference between integer and float division?
The major difference between float and integer division is the respect for decimal points. Integer division *will not* take account of decimal points or remainders when dividing, causing the result of `21 / 2` to be cut off at the decimal point resulting in `10`.
Float division will actually take the resulting decimal point into account and show the final result as `10.5`. This is important to take note of to avoid any mathematical logic errors.
####What are strings? Why and when would you use them?
Strings are essentially groups of letters (as well as numbers, punctuation, symbols, etc..) strung together. Strings are important because they allow you to store a message or a group of characters together to be used later - whereas integers and float types can only get you so far.
You would use strings to output messages, store information in the form of text, and many other uses.
####What are local variables? Why and when would you use them?
Local variables are variables that have been given a local scope, meaning it can be used within its local block or function. You would use them to do simple operations within a function or a code block. Local variables are important in programming because they allow developers to avoid bugs that might be caused by using global variables inappropriately.
####How was this challenge? Did you get a good review of some of the basics?
This challenge was fairly simple! The parts that took me the longest were just the parts where I had to write. This was a fairly simple review of the basics. I hope the later challenges will delve a bit deeper into Ruby.
| {
"content_hash": "55a004ef6e67913513e3c9c426ff13af",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 355,
"avg_line_length": 40.82165605095541,
"alnum_prop": 0.7480106100795756,
"repo_name": "dasKevinHuang/phase-0",
"id": "3c3c694f16cdcc85bce3a305a943e444f0929e41",
"size": "6481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week-4/nums-letters.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6333"
},
{
"name": "HTML",
"bytes": "31359"
},
{
"name": "JavaScript",
"bytes": "40915"
},
{
"name": "Ruby",
"bytes": "149310"
}
],
"symlink_target": ""
} |
#pragma once
#include <unordered_map>
#include <arpa/inet.h>
#include <linux/limits.h>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include "osquery/core/conversions.h"
namespace osquery {
const std::string kLinuxProcPath = "/proc";
struct SocketInfo final {
std::string socket;
ino_t net_ns;
int family{0};
int protocol{0};
std::string local_address;
std::uint16_t local_port{0U};
std::string remote_address;
std::uint16_t remote_port{0U};
std::string unix_socket_path;
std::string state;
};
typedef std::vector<SocketInfo> SocketInfoList;
struct SocketProcessInfo final {
std::string pid;
std::string fd;
};
typedef std::map<std::string, SocketProcessInfo> SocketInodeToProcessInfoMap;
// Linux proc protocol define to net stats file name.
const std::map<int, std::string> kLinuxProtocolNames = {
{IPPROTO_ICMP, "icmp"},
{IPPROTO_TCP, "tcp"},
{IPPROTO_UDP, "udp"},
{IPPROTO_UDPLITE, "udplite"},
{IPPROTO_RAW, "raw"},
};
const std::vector<std::string> tcp_states = {"UNKNOWN",
"ESTABLISHED",
"SYN_SENT",
"SYN_RECV",
"FIN_WAIT1",
"FIN_WAIT2",
"TIME_WAIT",
"CLOSED",
"CLOSE_WAIT",
"LAST_ACK",
"LISTEN",
"CLOSING"};
using ProcessNamespaceList = std::map<std::string, ino_t>;
Status procGetProcessNamespaces(
const std::string& process_id,
ProcessNamespaceList& namespace_list,
std::vector<std::string> namespaces = std::vector<std::string>());
Status procReadDescriptor(const std::string& process,
const std::string& descriptor,
std::string& result);
/// This function parses the inode value in the destination of a user namespace
/// symlink; fail if the namespace name is now what we expect
Status procGetNamespaceInode(ino_t& inode,
const std::string& namespace_name,
const std::string& process_namespace_root);
std::string procDecodeAddressFromHex(const std::string& encoded_address,
int family);
unsigned short procDecodePortFromHex(const std::string& encoded_port);
/**
* @brief Construct a map of socket inode number to socket information collected
* from /proc/<pid>/net for a certain family and protocol under a certain pid.
*
* The output parameter result is used as-is, i.e. it IS NOT cleared beforehand,
* so values will either be added or replace existing ones without check.
*
* @param family The socket family. One of AF_INET, AF_INET6 or AF_UNIX.
* @param protocol The socket protocol. For AF_INET and AF_INET6 one of the keys
* @param pid Query data for this pid.
* of kLinuxProtocolNames. For AF_UNIX only IPPROTO_IP is valid.
* @param result The output parameter.
*/
Status procGetSocketList(int family,
int protocol,
ino_t net_ns,
const std::string& pid,
SocketInfoList& result);
/**
* @brief Construct a map of socket inode number to process information for the
* process that owns the socket by reading entries under /proc/<pid>/fd.
*
* The output parameter result is used as-is, i.e. it IS NOT cleared beforehand,
* so values will either be added or replace existing ones without check.
*
* @param pid The process of interests
* @param result The output parameter.
*/
Status procGetSocketInodeToProcessInfoMap(const std::string& pid,
SocketInodeToProcessInfoMap& result);
/**
* @brief Enumerate all pids in the system by listing pid numbers under /proc
* and execute a callback for each one of them. The callback will receive the
* pid and the user_data provided as argument.
*
* Notice there isn't any type of locking here so race conditions might occur,
* e.g. a process is destroyed right before the callback being called.
*
* The loop will stop after the first callback failed, i.e. returned false.
*
* @param user_data User provided data to be passed to the callback
* @param callback A pointer to the callback function
*/
template <typename UserData>
Status procEnumerateProcesses(UserData& user_data,
bool (*callback)(const std::string&, UserData&)) {
boost::filesystem::directory_iterator it(kLinuxProcPath), end;
try {
for (; it != end; ++it) {
if (!boost::filesystem::is_directory(it->status())) {
continue;
}
// See #792: std::regex is incomplete until GCC 4.9
const auto& pid = it->path().leaf().string();
if (std::atoll(pid.data()) <= 0) {
continue;
}
bool ret = callback(pid, user_data);
if (ret == false) {
break;
}
}
} catch (const boost::filesystem::filesystem_error& e) {
VLOG(1) << "Exception iterating Linux processes: " << e.what();
return Status(1, e.what());
}
return Status(0);
}
/**
* @brief Enumerate all file descriptors of a certain process identified by its
* pid by listing files under /proc/<pid>/fd and execute a callback for each one
* of them. The callback will receive the pid the file descriptor and the real
* path the file descriptor links to, and the user_data provided as argument.
*
* Notice there isn't any type of locking here so race conditions might occur,
* e.g. a socket is closed right before the callback being called.
*
* The loop will stop after the first callback failed, i.e. returned false.
*
* @param pid The process id of interest
* @param user_data User provided data to be passed to the callback
* @param callback A pointer to the callback function
*/
template <typename UserData>
Status procEnumerateProcessDescriptors(const std::string& pid,
UserData& user_data,
bool (*callback)(const std::string& pid,
const std::string& fd,
const std::string& link,
UserData& user_data)) {
std::string descriptors_path = kLinuxProcPath + "/" + pid + "/fd";
try {
boost::filesystem::directory_iterator it(descriptors_path), end;
for (; it != end; ++it) {
auto fd = it->path().leaf().string();
std::string link;
Status status = procReadDescriptor(pid, fd, link);
if (!status.ok()) {
VLOG(1) << "Failed to read the link for file descriptor " << fd
<< " of pid " << pid << ". Data might be incomplete.";
}
bool ret = callback(pid, fd, link, user_data);
if (ret == false) {
break;
}
}
} catch (boost::filesystem::filesystem_error& e) {
VLOG(1) << "Exception iterating process file descriptors: " << e.what();
return Status(1, e.what());
}
return Status(0);
}
} // namespace osquery
| {
"content_hash": "9bf69149e8b53e26dddf6f6d7b461394",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 80,
"avg_line_length": 34.53953488372093,
"alnum_prop": 0.5941287368704552,
"repo_name": "jedi22/osquery",
"id": "771842af91652a5fc80d9edf13b9868fa7591244",
"size": "7808",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "osquery/filesystem/linux/proc.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "38093"
},
{
"name": "C++",
"bytes": "2437561"
},
{
"name": "CMake",
"bytes": "78446"
},
{
"name": "Makefile",
"bytes": "7926"
},
{
"name": "Objective-C++",
"bytes": "65363"
},
{
"name": "Shell",
"bytes": "2038"
},
{
"name": "Thrift",
"bytes": "2969"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/accentAColor" />
<size
android:width="18dp"
android:height="18dp" />
</shape>
| {
"content_hash": "496e7b5276d208eec7ea1604a6005a18",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 65,
"avg_line_length": 29.22222222222222,
"alnum_prop": 0.6349809885931559,
"repo_name": "edx/edx-app-android",
"id": "923e422d1b5be1c336175f94e105595d9e97e401",
"size": "263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OpenEdXMobile/res/drawable/player_seekbar_thumb.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1273"
},
{
"name": "HTML",
"bytes": "585518"
},
{
"name": "Java",
"bytes": "2665045"
},
{
"name": "JavaScript",
"bytes": "1319"
},
{
"name": "Kotlin",
"bytes": "222561"
},
{
"name": "Makefile",
"bytes": "2673"
},
{
"name": "Python",
"bytes": "35951"
},
{
"name": "Shell",
"bytes": "2137"
}
],
"symlink_target": ""
} |
local JSON = dofile("lib/dkjson.lua")
local updater = {}
local function getLocal(v)
if v then
if fs.exists("lib/.version") then
local file = fs.open("lib/.version", "r")
local ver = file.readAll()
file.close()
return tonumber(ver)
else
return 0
end
else
if fs.exists("lib/.dlversion") then
local file = fs.open("lib/.dlversion", "r")
local ver = file.readAll()
file.close()
return tonumber(ver)
else
return 0
end
end
end
local function getOnline(user, repo)
local size = 0
local query = "https://api.github.com/repos/"..user.."/"..repo.."/commits"
local request = http.get(query).readAll()
local data = JSON.decode(request)
size = size + #data
local sha = data[#data].sha
repeat
local query = "https://api.github.com/repos/"..user.."/"..repo.."/commits?sha="..sha
local request = http.get(query).readAll()
local data = JSON.decode(request)
if #data ~= 1 then
size = size + #data
size = size - 1
end
sha = data[#data].sha
until #data == 1
return size
end
local function setLocal(ver, v)
if v then
local file = fs.open("lib/.version", "w")
file.write(ver)
file.close()
else
local file = fs.open("lib/.dlversion", "w")
file.write(ver)
file.close()
end
end
function updater.update(funcToRun, user, repo)
local onl = getOnline(user, repo)
local loc = getLocal(true)
if onl > loc then
setLocal(onl, true)
funcToRun()
end
end
function updater.new()
local onl = getOnline("Kolpa", "cc-update-checker")
local loc = getLocal(false)
if onl > loc then
print("a new version of the updater api is downloading now")
local new = http.get("https://raw.github.com/Kolpa/cc-update-checker/master/lib/updater.lua").readAll()
local file = fs.open("lib/updater.lua", "w")
file.write(new)
file.close()
setLocal(onl, false)
print("Restarting now")
sleep(1)
shell.run(shell.getRunningProgram())
end
end
return updater
| {
"content_hash": "7efba15f9bf57acae2234d8e8bc83c21",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 105,
"avg_line_length": 23.821428571428573,
"alnum_prop": 0.638680659670165,
"repo_name": "TheTakenFox/CP-DOS",
"id": "99e560286a766750f961cbe640c3eb7249ef2cc5",
"size": "2001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Releases/1.3/CP-DOS/lib/updater.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "71660"
}
],
"symlink_target": ""
} |
package com.badlogic.gdx.backends.headless;
import com.badlogic.gdx.ApplicationLogger;
/**
* Default implementation of {@link ApplicationLogger} for headless
*/
public class HeadlessApplicationLogger implements ApplicationLogger {
@Override
public void log (String tag, String message) {
System.out.println("[" + tag + "] " + message);
}
@Override
public void log (String tag, String message, Throwable exception) {
System.out.println("[" + tag + "] " + message);
exception.printStackTrace(System.out);
}
@Override
public void error (String tag, String message) {
System.err.println("[" + tag + "] " + message);
}
@Override
public void error (String tag, String message, Throwable exception) {
System.err.println("[" + tag + "] " + message);
exception.printStackTrace(System.err);
}
@Override
public void debug (String tag, String message) {
System.out.println("[" + tag + "] " + message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
System.out.println("[" + tag + "] " + message);
exception.printStackTrace(System.out);
}
}
| {
"content_hash": "e326e50f60d575eb6059dcc97b209983",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 70,
"avg_line_length": 25.25,
"alnum_prop": 0.6903690369036903,
"repo_name": "alex-dorokhov/libgdx",
"id": "a361e6b8c8e4beb1622012e7bc208462b348addf",
"size": "1864",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "backends/gdx-backend-headless/src/com/badlogic/gdx/backends/headless/HeadlessApplicationLogger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "3962"
},
{
"name": "C",
"bytes": "8330368"
},
{
"name": "C++",
"bytes": "10606494"
},
{
"name": "CMake",
"bytes": "42744"
},
{
"name": "CSS",
"bytes": "58714"
},
{
"name": "DIGITAL Command Language",
"bytes": "35816"
},
{
"name": "GLSL",
"bytes": "75416"
},
{
"name": "Groff",
"bytes": "2333"
},
{
"name": "HTML",
"bytes": "1068234"
},
{
"name": "Java",
"bytes": "12851755"
},
{
"name": "JavaScript",
"bytes": "72"
},
{
"name": "Lua",
"bytes": "1354"
},
{
"name": "Makefile",
"bytes": "174979"
},
{
"name": "Objective-C",
"bytes": "67352"
},
{
"name": "Objective-C++",
"bytes": "58296"
},
{
"name": "OpenEdge ABL",
"bytes": "15076"
},
{
"name": "Perl",
"bytes": "12798"
},
{
"name": "Python",
"bytes": "179712"
},
{
"name": "Ragel in Ruby Host",
"bytes": "29477"
},
{
"name": "Shell",
"bytes": "348844"
}
],
"symlink_target": ""
} |
import JSONAPISerializer from 'ember-data/serializers/json-api';
export default JSONAPISerializer.extend({
serializeIntoHash: function(data, type, snapshot, options) {
this._super(data, type, snapshot, options);
if (snapshot.adapterOptions && snapshot.adapterOptions.meta) {
data.data.meta = snapshot.adapterOptions.meta;
}
}
});
| {
"content_hash": "693f471d2cc9134c71bb37cfa421c60a",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 64,
"avg_line_length": 34.2,
"alnum_prop": 0.7543859649122807,
"repo_name": "gossi/trixionary-client",
"id": "c71fbcaf3177b96dff7ba1c6fdd8becbc93a6ce4",
"size": "342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ember/app/serializers/application.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7362"
},
{
"name": "HTML",
"bytes": "80435"
},
{
"name": "JavaScript",
"bytes": "136988"
},
{
"name": "PHP",
"bytes": "49758"
}
],
"symlink_target": ""
} |
<div class="container-fluid address-container address-book-container credit-Card-Container">
<div class="row credit-card-headerTitle">
<p class="my-account-content-title">Credit Cards</p>
<div class="add-button col-md-3 col-lg-3 hidden-xs hidden-sm">
<button type="button" class="btn" ng-click="creditCards.newCardInput();creditCards.YearDropDown();"> + Add New Card</button>
</div>
</div>
<div class="row credit-card-list-cont not-default">
<!-- <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 credit-card-list-item">
<div class="col-xs-12 col-sm-12 col-md-2 col-lg-2 default-payment">
<p class="title">Default Payment</p>
<div class="Checkbox">
<input type="radio" checked name="rad">
<div class="Checkbox-visible"></div>
</div>
</div>
<div class="col-xs-2 col-sm-4 col-md-1 col-lg-1 visa">
<img src="../../assets/images/batch4web/creditcard/Visa.png" class="visa-icon" />
</div>
<div class="col-xs-10 col-sm-4 col-md-3 col-lg-3 cr-card-num">
<p class="title">Card Number</p>
<p class="addr-line1">XXXX XXXX XXXX {{creditCards.Defaultlist.PartialAccountNumber}}</p>
</div>
<div class="col-xs-5 col-sm-5 col-md-2 col-lg-3 cr-card-name">
<p class="title">Cardholder's Name</p>
<p class="value">{{creditCards.Defaultlist.CardholderName}}</p>
</div>
<div class="col-xs-4 col-sm-4 col-md-2 col-lg-2 expiry-date">
<p class="title">Expiration Date</p>
<p class="value">{{creditCards.Defaultlist.ExpirationDate | date: 'MM/yyyy' : 'UTC' }}</p>
</div>
<div class="col-xs-3 col-sm-3 col-md-2 col-lg-2 edit-options">
<a href="#">Edit</a>
<span class="link-sep">|</span>
<a href="#">Delete</a>
</div>
</div> -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 credit-card-list-item" ng-repeat="card in creditCards.list" ng-if="card">
<div class="col-xs-12 col-sm-12 col-md-2 col-lg-2 default-payment">
<p class="title" ng-if="creditCards.defaultUserCardID==card.ID">Default Payment</p>
<p class="title" ng-if="creditCards.defaultUserCardID!=card.ID">Make Default Payment</p>
<div class="Checkbox">
<input type="radio" ng-model="creditCards.defaultUserCardID" name="rad" ng-click="creditCards.makedefaultcard(card.ID)" value="{{card.ID}}">
<div class="Checkbox-visible"></div>
</div>
</div>
<div class="col-xs-2 col-sm-4 col-md-1 col-lg-1 visa">
<img src="../../assets/images/batch4web/creditcard/{{card.CardType}}.svg" class="visa-icon" />
</div>
<div class="col-xs-10 col-sm-4 col-md-3 col-lg-3 cr-card-num">
<p class="title">Card Number</p>
<p class="addr-line1">XXXX XXXX XXXX {{card.PartialAccountNumber}}</p>
</div>
<div class="col-xs-5 col-sm-5 col-md-2 col-lg-3 cr-card-name">
<p class="title">Name On Card</p>
<p class="value">{{card.CardholderName}}</p>
</div>
<div class="col-xs-4 col-sm-4 col-md-2 col-lg-2 expiry-date">
<p class="title">Expiration Date</p>
<p class="value">{{card.ExpirationDate | date: 'MM/yy' : 'UTC' }}</p>
</div>
<div class="col-xs-3 col-sm-3 col-md-2 col-lg-2 edit-options">
<a href="#" ng-click="creditCards.editCardInput(card);creditCards.YearDropDown();">Edit</a>
<span class="link-sep">|</span>
<a href="#" ng-click="creditCards.deletePopupCard(card)">Delete</a>
</div>
</div>
</div>
<!-- For Input Card Information STARTS -->
<div class="row" ng-hide="!creditCards.newcreditcard" id="bottom">
<div class="col-xs-12 add-new-credit-card-cont p0">
<p class="title">Input Card Information</p>
<div class="add-new-card-div">
<form class="add-new-card-form" name="creditCards.CreditCardCreateForm" role="form" novalidate="">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 p0 card-info">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group holder-name">
<label for="cardHoldName">Name On Card</label>
<input type="text" class="form-control" id="cardHoldName" placeholder="Enter Card Holder Name" ng-model="creditCards.card.CardholderName" autocomplete="off" required/>
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group card-type">
<label for="cardType">Card Type</label>
<select class="form-control" id="cardType" ng-model="creditCards.card.CardType" required>
<option value="">Select a Card Type</option>
<option value="Discover">Discover</option>
<option value="Visa">Visa</option>
<option value="MasterCard">MasterCard</option>
<option value="AmericanExpress">American Express</option>
</select>
<img class="cardIcons {{creditCards.card.CardType}}"/>
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group card-number">
<label for="cardNum">Card Number</label>
<input type="number" ng-minlength="14" maxlength="16" ng-maxlength="16" max-length="16" class="form-control" placeholder="Enter Card Number" id="cardNum" ng-model="creditCards.card.CardNumber" required>
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group exp-date">
<label for="expDate">Expiration Date</label>
<select class="form-control" id="month" placeholder="MM" ng-model="creditCards.card.ExpMonth" required>
<option value="">Month</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
<select class="form-control" id="year" placeholder="YY" ng-model="creditCards.card.ExpYear"
required ng-options="y for y in creditCards.years">
<option value="">Year</option>
</select>
</div>
<!-- <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group card-number">
<label for="cardCVV">Card CVV</label>
<input type="text" card-validation ng-minlength="3" maxlength="3" placeholder="Enter CVV Number" class="form-control" id="cardCVV" ng-model="creditCards.card.CVV" requried>
</div> -->
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 address-info">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group billing-addr">
<label for="billingAddress">Billing Address</label>
<select class="form-control" id="billingAddress" ng-model="creditCards.card.selectedAddress" required>
<option value="">Select Billling Address</option>
<option ng-repeat="address in creditCards.addressBook" value="{{$index}}" >{{address.FirstName}} {{address.LastName}}</option>
</select>
</div>
<p class="addnewlink" ng-click="creditCards.cardnewaddress=!creditCards.cardnewaddress;">+ Add New Address</p>
</div>
<!-- Desktop screen buttons for Card Save and Cancel -->
<div class="col-xs-6 p0 nav-buttons web-btn" ng-class="{withNewAddr:cardnewaddress}">
<div class="col-xs-12 form-group navig-btns">
<div class="col-xs-6 savebtn">
<button type="submit" class="btn purple-btn" ng-click="creditCards.createCard(creditCards.card);">Save</button>
</div>
<div class="col-xs-6 cancelbtn">
<button type="button" class="btn gray-btn" ng-click="creditCards.newcreditcard = !creditCards.newcreditcard; creditCards.card = {};">Cancel</button>
</div>
</div>
</div>
</form>
<!-- Add Address from Credit Card -->
<div class="add-new-card-form replaced-form">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 address-info">
<!-- <p class="addnewlink" ng-click="creditCards.cardnewaddress=!creditCards.cardnewaddress;">+ Add New Address</p> -->
<div class="row address-book-container">
<div class="row row-address-search">
<div class="col-xs-12 add-new-addr-cont" ng-if="creditCards.cardnewaddress">
<form class="add-new-card-form" name="creditCards.newAddressForm" role="form" novalidate="">
<div class="add-new-addr-div">
<div class="add-new-addr-form">
<div class="col-xs-6 form-group nick-name">
<label for="nickName">Nickname</label>
<input type="text" name="nickName" placeholder="Enter Nickname" class="form-control" id="nickName" ng-model="creditCards.addr.xp.NickName" autocomplete="off" ng-requried="true" required>
</div>
<div class="col-xs-6 form-group first-name">
<label for="firstName">First Name</label>
<input type="text" name="firstName" placeholder="Enter First Name" class="form-control" id="firstName" ng-model="creditCards.addr.FirstName" autocomplete="off" ng-required="true" required>
</div>
<div class="col-xs-6 form-group last-name">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" placeholder="Enter Last Name" class="form-control" id="lastName" ng-model="creditCards.addr.LastName" autocomplete="off" ng-required="true" required>
</div>
<div class="col-xs-6 form-group zip-code">
<label for="zipCode">ZIP Code</label>
<input type="number" ng-minlength="5" maxlength="5" placeholder="Enter Zip Code" class="form-control" id="zipCode" ng-model="creditCards.addr.Zip" autocomplete="off" ng-blur="creditCards.getLocation(creditCards.addr.Zip)" ng-required="true" required>
</div>
<div class="col-xs-12 form-group address">
<label for="address">Address 1</label>
<input type="text" placeholder="Enter Address 1" class="form-control" id="address" ng-model="creditCards.addr.Street1" autocomplete="off" ng-required="true" required>
</div>
<div class="col-xs-12 form-group address2">
<label for="address2">Address 2</label>
<input type="text" placeholder="Enter Address 2" class="form-control" id="address2" ng-model="creditCards.addr.Street2" autocomplete="off">
</div>
<div class="col-xs-6 form-group city">
<label for="city">City</label>
<input type="text" placeholder="Enter City" class="form-control" id="city" ng-model="creditCards.addr.City" autocomplete="off" ng-required="true" required>
</div>
<div class="col-xs-6 form-group state">
<label for="state">State</label>
<input type="text" placeholder="Enter State" class="form-control" id="state" ng-model="creditCards.addr.State" autocomplete="off" ng-required="true" required>
</div>
<div class="col-xs-6 form-group phone-number">
<label for="phone1">Phone Number</label>
<div class="row phone-txt">
<div class="col-sm-4 col-md-4 col-xs-4">
<input type="number" phone-validation ng-minlength="3" maxlength="3" ng-maxlength="3" max-length="3" class="form-control" ng-model="creditCards.addr.Phone1" placeholder="Area code" ng-keypress="creditCards.IsPhone($event)" autocomplete="off" ng-required="true"></div>
<div class="col-sm-4 col-md-4 col-xs-4">
<input type="number" phone-validation ng-minlength="3" maxlength="3" ng-maxlength="3" max-length="3" placeholder="Prefix" class="form-control" ng-model="creditCards.addr.Phone2" ng-keypress="creditCards.IsPhone($event)" autocomplete="off" ng-required="true"></div>
<div class="col-sm-4 col-md-4 col-xs-4">
<input type="number" phone-validation ng-minlength="4" maxlength="4" ng-maxlength="4" max-length="4" class="form-control" ng-model="creditCards.addr.Phone3" ng-keypress="creditCards.IsPhone($event)" placeholder="Number"autocomplete="off" ng-required="true"></div>
</div>
</div>
<div class="col-xs-12 form-group shipping-checkbox">
<div class="Checkbox">
<input type="checkbox" id="ship-addr-chkb" ng-model="creditCards.addr.Shipping" />
<div class="Checkbox-visible"></div>
</div>
<label class="ship-addr-label" for="ship-addr-chkb">Shipping Address</label>
</div>
<div class="col-xs-12 form-group billing-checkbox">
<div class="Checkbox">
<input type="checkbox" id="bill-addr-chkb" ng-model="creditCards.addr.Billing"/>
<div class="Checkbox-visible"></div>
</div>
<label class="bill-addr-label" for="bill-addr-chkb">Billing Address</label>
</div>
<!-- Buttons for Address Save and Cancel -->
<div class="col-xs-12 form-group navig-btns">
<div class="col-xs-6 savebtn">
<button type="button" class="btn purple-btn col-xs-6" ng-class="{'disabledbtn': addnewAddress.$invalid }" class="btn purple-btn col-xs-6" ng-click="creditCards.saveNewAddress(creditCards.addr)">Save</button>
</div>
<div class="col-xs-6 cancelbtn">
<button type="button" class="btn gray-btn col-xs-6" ng-click="creditCards.cardnewaddress=!creditCards.cardnewaddress;creditCards.addr={};">Cancel</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Mobile Buttons for Card Save and Cancel -->
<div class="col-xs-6 p0 nav-buttons mob-btn" ng-class="{withNewAddr:cardnewaddress}">
<div class="col-xs-12 form-group navig-btns">
<div class="col-xs-6 savebtn">
<button type="submit" class="btn purple-btn" ng-click="creditCards.createCard(creditCards.card);">Save</button>
</div>
<div class="col-xs-6 cancelbtn">
<button type="button" class="btn gray-btn" ng-click="creditCards.newcreditcard = !creditCards.newcreditcard; creditCards.card = {};">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- For Input Card Information ENDS -->
<!-- For Input Card Edit STARTS -->
<div class="row" ng-hide="!creditCards.editcreditcard">
<div class="col-xs-12 add-new-credit-card-cont p0">
<p class="title">Update Card Information</p>
<div class="add-new-card-div">
<form class="add-new-card-form ng-pristine ng-valid" ng-submit="creditCards.updateCard()" name="CreditCardEditForm" role="form" novalidate="">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 p0 card-info">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group holder-name">
<label for="cardHoldNameEdit">Name On Card</label>
<input type="text" class="form-control" id="cardHoldNameEdit" placeholder="Name" ng-model="creditCards.card.CardholderName" required/>
</div>
<!-- <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group card-type">
<label for="cardType">Card Type</label>
<select class="form-control" id="cardType" ng-model="creditCards.card.CardType" required>
<option value="Select">Select</option>
<option value="Visa">Visa</option>
<option value="Discover">Discover</option>
<option value="MasterCard">MasterCard</option>
<option value="AmericanExpress">American Express</option>
</select>
</div> -->
<!-- <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group card-number">
<label for="cardNum">Card Number</label>
<input type="text" ng-minlength="14" maxlength="16" ng-maxlength="16" max-length="16" class="form-control" id="cardNum" ng-model="creditCards.card.CardNumber" requried>
</div> -->
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group exp-date">
<label for="expDate2">Expiration Date</label>
<select class="form-control" id="monthEdit" placeholder="MM" ng-model="creditCards.card.ExpMonth" required>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
<select class="form-control" id="year" placeholder="YY" ng-model="creditCards.card.expYearDD"
required ng-options="y for y in creditCards.years">
</select>
</div>
<!-- <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group card-number">
<label for="cardCVV">Card CVV</label>
<input type="text" card-validation ng-minlength="3" maxlength="4" class="form-control" id="cardCVV" ng-model="creditCards.card.CVV" required>
</div> -->
</div>
<div class="col-xs-12 p0 nav-buttons">
<div class="col-xs-12 form-group navig-btns">
<div class="col-xs-6 col-sm-6 col-md-3 col-lg-3 savebtn">
<button type="submit" class="btn purple-btn" ng-disabled="CreditCardEditForm.$invalid">Save</button>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 col-lg-3 cancelbtn">
<button type="button" class="btn gray-btn" ng-click="creditCards.editcreditcard = !creditCards.editcreditcard; creditCards.card = null">Cancel</button>
</div>
</div>
</div>
</form>
</div>
<!-- <div class="add-new-card-div">
<form class="add-new-card-form ng-pristine ng-valid" ng-submit="creditCards.updateCard()" name="CreditCardEditForm" role="form" novalidate="">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 p0 card-info">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group holder-name">
<label for="cardHoldNameEdit">Cardholder's Name</label>
<input type="text" class="form-control" id="cardHoldNameEdit" placeholder="Name" ng-model="creditCards.card.CardholderName"/>
</div>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 form-group exp-date">
<label for="expDate2">Expiration Date</label>
<select class="form-control" id="monthEdit" placeholder="MM" ng-model="creditCards.card.ExpMonth" required>
<option>08</option>
<option>09</option>
<option>10</option>
</select>
<select class="form-control" id="yearEdit" placeholder="YY" ng-model="creditCards.card.ExpYear" required>
<option>2016</option>
<option>2016</option>
<option>2016</option>
</select>
</div>
</div>
<div class="col-xs-12 p0 nav-buttons">
<div class="col-xs-12 form-group navig-btns">
<div class="col-xs-6 col-sm-6 col-md-3 col-lg-3 savebtn">
<button type="submit" class="btn purple-btn" ng-disabled="CreditCardEditForm.$invalid">Save</button>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 col-lg-3 cancelbtn">
<button type="button" class="btn gray-btn" ng-click="creditCards.editcreditcard = !creditCards.editcreditcard; creditCards.card = null">Cancel</button>
</div>
</div>
</div>
</form>
</div> -->
</div>
</div>
<!-- For Input Card Edit ENDS -->
</div>
</div>
| {
"content_hash": "b2dadafabd124e6ab5e18acbabc9c033",
"timestamp": "",
"source": "github",
"line_count": 343,
"max_line_length": 324,
"avg_line_length": 75.90379008746356,
"alnum_prop": 0.4630305358171692,
"repo_name": "Shyam-Echidna/new-bachmansstore",
"id": "c377bba62635499638d9deb89f65d7f6bb7a9adf",
"size": "26035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/account/templates/accountCreditCard.tpl.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1700967"
},
{
"name": "HTML",
"bytes": "2193171"
},
{
"name": "JavaScript",
"bytes": "933259"
},
{
"name": "Shell",
"bytes": "519"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.dxf2.importsummary;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.DxfNamespaces;
@JacksonXmlRootElement(localName = "count", namespace = DxfNamespaces.DXF_2_0)
public class ImportCount
{
private int imported;
private int updated;
private int ignored;
private int deleted;
public ImportCount()
{
}
public ImportCount( int imported, int updated, int ignored, int deleted )
{
this.imported = imported;
this.updated = updated;
this.ignored = ignored;
this.deleted = deleted;
}
@JsonProperty
@JacksonXmlProperty(isAttribute = true)
public int getImported()
{
return imported;
}
public void setImported( int imported )
{
this.imported = imported;
}
@JsonProperty
@JacksonXmlProperty(isAttribute = true)
public int getUpdated()
{
return updated;
}
public void setUpdated( int updated )
{
this.updated = updated;
}
@JsonProperty
@JacksonXmlProperty(isAttribute = true)
public int getIgnored()
{
return ignored;
}
public void setIgnored( int ignored )
{
this.ignored = ignored;
}
@JsonProperty
@JacksonXmlProperty(isAttribute = true)
public int getDeleted()
{
return deleted;
}
public void setDeleted( int deleted )
{
this.deleted = deleted;
}
@Override
public String toString()
{
return "[imports=" + imported + ", updates=" + updated + ", ignores=" + ignored + "]";
}
public void incrementImported()
{
imported++;
}
public void incrementUpdated()
{
updated++;
}
public void incrementIgnored()
{
ignored++;
}
public void incrementDeleted()
{
deleted++;
}
public void incrementImported( int n )
{
imported += n;
}
public void incrementUpdated( int n )
{
updated += n;
}
public void incrementIgnored( int n )
{
ignored += n;
}
public void incrementDeleted( int n )
{
deleted += n;
}
}
| {
"content_hash": "0ca0b2dfa25b1ee8a3e9b938b7923c75",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 94,
"avg_line_length": 18.73015873015873,
"alnum_prop": 0.6042372881355932,
"repo_name": "steffeli/inf5750-tracker-capture",
"id": "5b8bea5068a22ec0d684ae7edcf42dc572025708",
"size": "3916",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/importsummary/ImportCount.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "404669"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "402350"
},
{
"name": "Java",
"bytes": "15709343"
},
{
"name": "JavaScript",
"bytes": "7104924"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "388"
},
{
"name": "XSLT",
"bytes": "8281"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Podam should generate evenly distributed random integers</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">
<!--[if IE 7]>
<link rel="stylesheet" href="font-awesome/css/font-awesome-ie7.min.css">
<![endif]--><!-- JQuery -->
<script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script><!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap/js/bootstrap.min.js"></script><link rel="stylesheet" href="css/core.css"/>
<link rel="stylesheet" href="css/link.css"/>
<link type="text/css" media="screen" href="css/screen.css" rel="Stylesheet"/><!-- JQuery-UI -->
<link type="text/css" href="jqueryui/1.11.2-start/jquery-ui.min.css" rel="Stylesheet" />
<script type="text/javascript" src="jqueryui/1.11.2-start/jquery-ui.min.js"></script><!-- DataTables -->
<link type="text/css" href="datatables/1.10.4/media/jqueryui/dataTables.jqueryui.css" rel="Stylesheet"/>
<link type="text/css" href="css/tables.css" rel="stylesheet" />
<script type="text/javascript" src="datatables/1.10.4/media/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="datatables/1.10.4/media/jqueryui/dataTables.jqueryui.min.js"></script><!-- ImgPreview -->
<script src="scripts/imgpreview.full.jquery.js" type="text/javascript"></script>
</head>
<body class="results-page">
<div id="topheader">
<div id="topbanner">
<div id="logo"><a href="index.html"><img src="images/serenity-bdd-logo.png" border="0"/></a></div>
<div id="projectname-banner" style="float:right">
<span class="projectname"></span>
</div>
</div>
</div>
<div class="middlecontent">
<div id="contenttop">
<div class="middlebg">
<span class="breadcrumbs">
<a href="index.html" class="breadcrumbs">Home</a>
> <a href="cb34229e06efff71a22b6da7fd26f6a6.html" title="Randomness (breadcrumbType)">Randomness</a>
> <a href="84124e6d00e8cff7b11adef53285ef56.html" title="Randomness Test (breadcrumbType)">Randomness Test</a>
> Podam should generate evenly distributed random integers
</span>
</div>
<div class="rightbg"></div>
</div>
<div class="clr"></div>
<!--/* starts second table*/-->
<div>
<ul class="nav nav-tabs" role="tablist">
<li class="active">
<a href="#"><i class="fa fa-check-square-o"></i> Overall Test Results</a>
</li>
<li >
<a href="capabilities.html"><i class="fa fa-book"></i> Requirements</a>
</li>
<li >
<a href="c2f88807fda1a5fdef701e37e90d2760.html"><i class="fa fa-comments-o"></i> Epics</a>
</li>
<li >
<a href="45f14f4e50d39cd433b548a78cc2dd0e.html"><i class="fa fa-comments-o"></i> Stories</a>
</li>
</ul>
<span class="date-and-time"><a href="build-info.html"><i class="fa fa-info-circle"></i></a> Report generated 20-10-2017 17:39</span>
<br style="clear:left"/>
</div>
<div class="clr"></div>
<div id="contentbody">
<div class="titlebar">
<div class="story-title">
<table class="outcome-header">
<tr>
<td>
<div>
<h3 class="discreet-story-header">
<i class="fa fa-2x fa-comments-o"></i>
<span class="story-header-title">Randomness Test </span>
</h3>
<div class="discreet-requirement-narrative-title">
</div>
</div>
</td>
<td valign="top">
<p class="tag">
<span class="badge tag-badge">
<i class="fa fa-tag"></i> <a class="tagLink"
href="cb34229e06efff71a22b6da7fd26f6a6.html">Randomness
(epics)</a>
</span>
</p>
</td>
</tr>
</table>
</div>
<div class="story-title">
<table class="outcome-header">
<tr>
<td colspan="2" class="test-title-bar">
<span class="outcome-icon"><i class='fa fa-check-square-o success-icon fa-3x' title='SUCCESS'></i></span>
<span class="test-case-title">
<span class="success-color">
Podam Should Generate Evenly Distributed Random Integers
<span class="related-issue-title"></span>
</span>
</span>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="clr"></div>
<div id="beforetable"></div>
<div id="tablecontents">
<div>
<table class="step-table">
<tr class="step-titles">
<th width="65">
</th>
<th width="%" class="step-description-wide-column greentext">
Steps
</th>
<th width="100" class="greentext">Outcome</th>
<th width="75" class="greentext">Duration</th>
</tr>
<tr class="step-table-separator">
<td colspan="5"></td>
</tr>
<tr class="test-SUCCESS">
<td width="60" class="step-icon">
<a name="0"/>
<span style="margin-left: 20px; margin-right: 5px;"
class="top-level-icon"><i class='fa fa-check-square-o success-icon ' title='SUCCESS'></i></span>
</td>
<td>
<div class="step-description">
<span class="top-level-step">Then the double value 0.18760659999999998 should be between 0.0 and 1.0</span>
</div>
</td>
<td width="100"><span class="top-level-step">SUCCESS</span></td>
<td width="100"><span class="top-level-step">0s</span></td>
</tr>
<tr class="test-SUCCESS">
<td colspan="2"></td>
<td width="100"><span class="top-level-step"><em>SUCCESS</em></span></td>
<td width="100"><span class="top-level-step"><em>0.21s</em></span></td>
</tr>
</table>
</div>
</div>
<div id="beforefooter"></div>
<div id="bottomfooter">
<span class="version">Serenity BDD version 1.2.2</span>
</div>
<script type="text/javascript">
function toggleDiv(divId) {
$("#" + divId).toggle();
var imgsrc = $(".img" + divId).attr('src');
if (imgsrc == 'images/plus.png') {
$(".img" + divId).attr("src", function () {
return "images/minus.png";
});
}
else {
$(".img" + divId).attr("src", function () {
return "images/plus.png";
});
}
}
</script>
<script type="text/javascript">
$('.example-table table').DataTable({
"order": [[0, "asc"]],
"pageLength": 25,
"scrollX": "100%",
"scrollXInner": "100%",
"scrollCollapse": true
});
</script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$('img.screenshot').imgPreview({
imgCSS: {
width: '500px'
},
distanceFromCursor: {top: 10, left: -200}
});
});
//]]>
</script>
<div id="imgPreviewContainer" style="position: absolute; top: 612px; left: 355px; display: none; " class=""><img
src="" style="display: none; "></div>
<div id="imgPreviewContainer2" style="position: absolute; top: 925px; left: 320px; display: none; " class="">
<img style="width: 200px; display: none; " src=""></div>
<div id="imgPreviewWithStyles" style="position: absolute; top: 1272px; left: 321px; display: none; " class="">
<img style="height: 200px; opacity: 1; display: none; " src=""></div>
<div id="imgPreviewWithStyles2" style="display: none; position: absolute; "><img style="height: 200px; "></div>
<div id="imgPreviewWithStyles3" style="display: none; position: absolute; "><img style="height: 200px; "></div>
</body>
</html>
| {
"content_hash": "03dbad76a712573527ee9ef5c27e1012",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 136,
"avg_line_length": 40.61233480176212,
"alnum_prop": 0.4828072459051958,
"repo_name": "Vignesh4vi/podam",
"id": "3a692efe5370b268ee98bd17ad0b9683ed5aac8b",
"size": "9219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "target/site/serenity/70e53f5488eeef5690b624a315861e54.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "344038"
},
{
"name": "HTML",
"bytes": "10310354"
},
{
"name": "Java",
"bytes": "763389"
},
{
"name": "JavaScript",
"bytes": "1732464"
}
],
"symlink_target": ""
} |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.strings;
import docking.widgets.table.constraint.ColumnData;
import docking.widgets.table.constraint.TableFilterContext;
import docking.widgets.table.constrainteditor.ColumnConstraintEditor;
import docking.widgets.table.constrainteditor.DoNothingColumnConstraintEditor;
import ghidra.program.model.data.StringDataInstance;
/**
* Tests if a string value contains only ASCII characters.
*/
public class IsAsciiColumnConstraint extends StringDataInstanceColumnConstraint {
@Override
public boolean accepts(StringDataInstance value, TableFilterContext context) {
String s = value.getStringValue();
return (s != null) && s.chars().allMatch(codePoint -> 0 <= codePoint && codePoint < 0x80);
}
@Override
public String getName() {
return "Is Ascii";
}
@Override
public ColumnConstraintEditor<StringDataInstance> getEditor(
ColumnData<StringDataInstance> columnDataSource) {
return new DoNothingColumnConstraintEditor<>(this);
}
}
| {
"content_hash": "65316d39c99cbb61668e62717cf975ef",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 92,
"avg_line_length": 34.8,
"alnum_prop": 0.7707535121328225,
"repo_name": "NationalSecurityAgency/ghidra",
"id": "36c795e7e682b9de51d832dbfe792c4f55283665",
"size": "1566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/strings/IsAsciiColumnConstraint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "77536"
},
{
"name": "Batchfile",
"bytes": "21610"
},
{
"name": "C",
"bytes": "1132868"
},
{
"name": "C++",
"bytes": "7334484"
},
{
"name": "CSS",
"bytes": "75788"
},
{
"name": "GAP",
"bytes": "102771"
},
{
"name": "GDB",
"bytes": "3094"
},
{
"name": "HTML",
"bytes": "4121163"
},
{
"name": "Hack",
"bytes": "31483"
},
{
"name": "Haskell",
"bytes": "453"
},
{
"name": "Java",
"bytes": "88669329"
},
{
"name": "JavaScript",
"bytes": "1109"
},
{
"name": "Lex",
"bytes": "22193"
},
{
"name": "Makefile",
"bytes": "15883"
},
{
"name": "Objective-C",
"bytes": "23937"
},
{
"name": "Pawn",
"bytes": "82"
},
{
"name": "Python",
"bytes": "587415"
},
{
"name": "Shell",
"bytes": "234945"
},
{
"name": "TeX",
"bytes": "54049"
},
{
"name": "XSLT",
"bytes": "15056"
},
{
"name": "Xtend",
"bytes": "115955"
},
{
"name": "Yacc",
"bytes": "127754"
}
],
"symlink_target": ""
} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/device/geolocation/win/location_provider_winrt.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "base/win/scoped_winrt_initializer.h"
#include "base/win/windows_version.h"
#include "services/device/geolocation/win/fake_geocoordinate_winrt.h"
#include "services/device/geolocation/win/fake_geolocator_winrt.h"
#include "services/device/public/cpp/geolocation/geoposition.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace device {
namespace {
using ABI::Windows::Devices::Geolocation::IGeolocator;
using ABI::Windows::Devices::Geolocation::PositionStatus;
class MockLocationObserver {
public:
MockLocationObserver(base::OnceClosure update_called)
: update_called_(std::move(update_called)) {}
~MockLocationObserver() = default;
void InvalidateLastPosition() {
last_position_.error_code = mojom::Geoposition::ErrorCode::NONE;
EXPECT_FALSE(ValidateGeoposition(last_position_));
}
void OnLocationUpdate(const LocationProvider* provider,
const mojom::Geoposition& position) {
last_position_ = position;
on_location_update_called_ = true;
std::move(update_called_).Run();
}
mojom::Geoposition last_position() { return last_position_; }
bool on_location_update_called() { return on_location_update_called_; }
private:
base::OnceClosure update_called_;
mojom::Geoposition last_position_;
bool on_location_update_called_ = false;
};
} // namespace
class TestingLocationProviderWinrt : public LocationProviderWinrt {
public:
TestingLocationProviderWinrt(
std::unique_ptr<FakeGeocoordinateData> position_data,
PositionStatus position_status)
: position_data_(std::move(position_data)),
position_status_(position_status) {}
bool HasPermissionBeenGrantedForTest() { return permission_granted_; }
bool IsHighAccuracyEnabled() { return enable_high_accuracy_; }
absl::optional<EventRegistrationToken> GetStatusChangedToken() {
return status_changed_token_;
}
absl::optional<EventRegistrationToken> GetPositionChangedToken() {
return position_changed_token_;
}
HRESULT GetGeolocator(IGeolocator** geo_locator) override {
*geo_locator = Microsoft::WRL::Make<FakeGeolocatorWinrt>(
std::move(position_data_), position_status_)
.Detach();
return S_OK;
}
private:
std::unique_ptr<FakeGeocoordinateData> position_data_;
const PositionStatus position_status_;
};
class LocationProviderWinrtTest : public testing::Test {
protected:
LocationProviderWinrtTest()
: observer_(
std::make_unique<MockLocationObserver>(run_loop_.QuitClosure())),
callback_(base::BindRepeating(&MockLocationObserver::OnLocationUpdate,
base::Unretained(observer_.get()))) {}
void SetUp() override {
if (base::win::GetVersion() < base::win::Version::WIN8)
GTEST_SKIP();
winrt_initializer_.emplace();
ASSERT_TRUE(winrt_initializer_->Succeeded());
}
void InitializeProvider(
PositionStatus position_status = PositionStatus::PositionStatus_Ready) {
auto test_data = FakeGeocoordinateData();
test_data.longitude = 0;
test_data.latitude = 0;
test_data.accuracy = 0;
InitializeProvider(test_data, position_status);
}
void InitializeProvider(
FakeGeocoordinateData position_data,
PositionStatus position_status = PositionStatus::PositionStatus_Ready) {
provider_ = std::make_unique<TestingLocationProviderWinrt>(
std::make_unique<FakeGeocoordinateData>(position_data),
position_status);
provider_->SetUpdateCallback(callback_);
}
base::test::TaskEnvironment task_environment_;
base::RunLoop run_loop_;
absl::optional<base::win::ScopedWinrtInitializer> winrt_initializer_;
const std::unique_ptr<MockLocationObserver> observer_;
const LocationProvider::LocationProviderUpdateCallback callback_;
std::unique_ptr<TestingLocationProviderWinrt> provider_;
};
TEST_F(LocationProviderWinrtTest, CreateDestroy) {
InitializeProvider();
EXPECT_TRUE(provider_);
provider_.reset();
}
TEST_F(LocationProviderWinrtTest, OnPermissionGranted) {
InitializeProvider();
EXPECT_FALSE(provider_->HasPermissionBeenGrantedForTest());
provider_->OnPermissionGranted();
EXPECT_TRUE(provider_->HasPermissionBeenGrantedForTest());
}
TEST_F(LocationProviderWinrtTest, SetAccuracyOptions) {
InitializeProvider();
provider_->StartProvider(/*enable_high_accuracy=*/false);
EXPECT_EQ(false, provider_->IsHighAccuracyEnabled());
provider_->StartProvider(/*enable_high_accuracy=*/true);
EXPECT_EQ(true, provider_->IsHighAccuracyEnabled());
}
// Tests when OnPermissionGranted() called location update is provided.
TEST_F(LocationProviderWinrtTest, HasPermissions) {
auto test_data = FakeGeocoordinateData();
test_data.longitude = 1;
test_data.latitude = 2;
test_data.accuracy = 3;
test_data.speed = 4;
InitializeProvider(test_data);
provider_->OnPermissionGranted();
provider_->StartProvider(/*enable_high_accuracy=*/false);
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(ValidateGeoposition(observer_->last_position()));
EXPECT_TRUE(provider_->GetStatusChangedToken().has_value());
EXPECT_TRUE(provider_->GetPositionChangedToken().has_value());
run_loop_.Run();
EXPECT_TRUE(observer_->on_location_update_called());
auto position = observer_->last_position();
EXPECT_TRUE(ValidateGeoposition(position));
EXPECT_EQ(position.latitude, test_data.latitude);
EXPECT_EQ(position.longitude, test_data.longitude);
EXPECT_EQ(position.accuracy, test_data.accuracy);
EXPECT_EQ(position.altitude, device::mojom::kBadAltitude);
EXPECT_EQ(position.altitude_accuracy, device::mojom::kBadAccuracy);
EXPECT_EQ(position.speed, test_data.speed.value());
EXPECT_EQ(position.heading, device::mojom::kBadHeading);
}
// Tests when OnPermissionGranted() called location update is provided with all
// possible values populated.
TEST_F(LocationProviderWinrtTest, HasPermissionsAllValues) {
auto test_data = FakeGeocoordinateData();
test_data.longitude = 1;
test_data.latitude = 2;
test_data.accuracy = 3;
test_data.altitude = 4;
test_data.altitude_accuracy = 5;
test_data.heading = 6;
test_data.speed = 7;
InitializeProvider(test_data);
provider_->OnPermissionGranted();
provider_->StartProvider(/*enable_high_accuracy=*/false);
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(ValidateGeoposition(observer_->last_position()));
EXPECT_TRUE(provider_->GetStatusChangedToken().has_value());
EXPECT_TRUE(provider_->GetPositionChangedToken().has_value());
run_loop_.Run();
EXPECT_TRUE(observer_->on_location_update_called());
auto position = observer_->last_position();
EXPECT_TRUE(ValidateGeoposition(position));
EXPECT_EQ(position.latitude, test_data.latitude);
EXPECT_EQ(position.longitude, test_data.longitude);
EXPECT_EQ(position.accuracy, test_data.accuracy);
EXPECT_EQ(position.altitude, test_data.altitude.value());
EXPECT_EQ(position.altitude_accuracy, test_data.altitude_accuracy.value());
EXPECT_EQ(position.speed, test_data.speed.value());
EXPECT_EQ(position.heading, test_data.heading.value());
}
// Tests when provider is stopped and started quickly access errors
// do not occur and location update is not called.
TEST_F(LocationProviderWinrtTest, StartStopProviderRunTasks) {
InitializeProvider();
provider_->OnPermissionGranted();
provider_->StartProvider(/*enable_high_accuracy=*/false);
provider_->StopProvider();
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(ValidateGeoposition(observer_->last_position()));
run_loop_.RunUntilIdle();
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(provider_->GetStatusChangedToken().has_value());
EXPECT_FALSE(provider_->GetPositionChangedToken().has_value());
}
// Tests when OnPermissionGranted() has not been called location update
// is not provided.
TEST_F(LocationProviderWinrtTest, NoPermissions) {
InitializeProvider();
provider_->StartProvider(/*enable_high_accuracy=*/false);
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(ValidateGeoposition(observer_->last_position()));
run_loop_.RunUntilIdle();
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(provider_->GetStatusChangedToken().has_value());
EXPECT_FALSE(provider_->GetPositionChangedToken().has_value());
}
// Tests when a PositionStatus_Disabled is returned from the OS indicating
// access to location on the OS is disabled, a permission denied is returned.
TEST_F(LocationProviderWinrtTest, PositionStatusDisabledOsPermissions) {
InitializeProvider(PositionStatus::PositionStatus_Disabled);
provider_->OnPermissionGranted();
provider_->StartProvider(/*enable_high_accuracy=*/false);
EXPECT_FALSE(observer_->on_location_update_called());
EXPECT_FALSE(ValidateGeoposition(observer_->last_position()));
EXPECT_TRUE(provider_->GetStatusChangedToken().has_value());
EXPECT_TRUE(provider_->GetPositionChangedToken().has_value());
run_loop_.Run();
EXPECT_TRUE(observer_->on_location_update_called());
auto position = observer_->last_position();
EXPECT_FALSE(ValidateGeoposition(position));
EXPECT_EQ(position.error_code,
mojom::Geoposition::ErrorCode::PERMISSION_DENIED);
}
} // namespace device
| {
"content_hash": "29877b02a7078410d6b9e629ef7ccc76",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 79,
"avg_line_length": 35.885185185185186,
"alnum_prop": 0.7365053153060171,
"repo_name": "ric2b/Vivaldi-browser",
"id": "128dbc8400ed65e3e58f559ec12988d9c14cee4c",
"size": "9689",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/services/device/geolocation/win/location_provider_winrt_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.netflix.florida.startup;
import com.google.inject.Injector;
import com.netflix.archaius.guice.ArchaiusModule;
import com.netflix.governator.InjectorBuilder;
import com.netflix.governator.guice.jetty.Archaius2JettyModule;
import com.netflix.governator.guice.servlet.WebApplicationInitializer;
/**
* The "main" class that boots up the service. When it's deployed within a servlet container such
* as Tomcat, only the createInjector() is called. For local testing one simply invokes the
* main() method as if running a normal Java app.
*
* @author This file is auto-generated by runtime@netflix.com. Feel free to modify.
*/
public class Florida implements WebApplicationInitializer {
public static void main(String[] args) throws Exception {
InjectorBuilder.fromModules(
new FloridaModule(),
new Archaius2JettyModule(),
new ArchaiusModule() {
@Override
protected void configureArchaius() {
bindApplicationConfigurationOverrideResource("laptop");
}
}).createInjector().awaitTermination();
}
@Override
public Injector createInjector() {
return InjectorBuilder.fromModules(new FloridaModule()).createInjector();
}
}
| {
"content_hash": "9cbf8a3e7f38d80f1099759789cdef62",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 97,
"avg_line_length": 37.628571428571426,
"alnum_prop": 0.686408504176158,
"repo_name": "diegopacheco/dynomite-manager-1",
"id": "f88e1da5795fd45dcc55ebb3cf5f3511a79695bd",
"size": "1901",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "dynomitemanager-web/src/main/java/com/netflix/florida/startup/Florida.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "487"
},
{
"name": "Java",
"bytes": "390048"
},
{
"name": "Shell",
"bytes": "1431"
}
],
"symlink_target": ""
} |
Example of creating an Android foreground service with wake and wifi locks.
Read more about this project on my blog: http://www.splinter.com.au/2015/12/20/android-server/
| {
"content_hash": "a7b7d0abda4ef44d0b2e72552af0150f",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 94,
"avg_line_length": 57.333333333333336,
"alnum_prop": 0.7906976744186046,
"repo_name": "chrishulbert/AndroidService",
"id": "15dfdb27621c2ab6f297eaffb45393ba6c2c1254",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "24013"
}
],
"symlink_target": ""
} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class H5 extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('GameRules_model');
$this->load->model('GameTips_model');
}
public function index(){
$this->load->view('h5/index');
}
public function every_color(){
$result = $this->GameRules_model->readData(1);
// $this->load->view('h5/game_rule',$result);
}
public function eleven_select_five(){
$result = $this->GameRules_model->readData(2);
$this->load->view('h5/game_rule',$result);
}
public function happy_ten_minutes(){
$result = $this->GameRules_model->readData(3);
$this->load->view('h5/game_rule',$result);
}
public function three_d_lottery(){
$result = $this->GameRules_model->readData(4);
$this->load->view('h5/game_rule',$result);
}
public function fast_three(){
$result = $this->GameRules_model->readData(5);
$this->load->view('h5/game_rule',$result);
}
public function fast_eight(){
$result = $this->GameRules_model->readData(6);
$this->load->view('h5/game_rule',$result);
}
public function fast_ten(){
$result = $this->GameRules_model->readData(7);
$this->load->view('h5/game_rule',$result);
}
public function promotions_show(){
$result['test'] = 'promotions';
$this->load->view('h5/promotions_show',$result);
}
public function game_tips_api_every_color(){
$result = $this->GameTips_model->readData('every_color');
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function game_tips_api_pk_ten(){
$result = $this->GameTips_model->readData('pk_ten');
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function game_tips_api_fast_three(){
$result = $this->GameTips_model->readData('fast_three');
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function game_tips_api_eleven_select_five(){
$result = $this->GameTips_model->readData('eleven_select_five');
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function game_tips_api_three_d_lottery(){
$result = $this->GameTips_model->readData('three_d_lottery');
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function game_record_every_color(){
$result['test'] = 'promotions';
$this->load->view('h5/record_every_color',$result);
}
public function game_record_pk_ten(){
$result['test'] = 'promotions';
$this->load->view('h5/record_pk_ten',$result);
}
public function game_record_fast_three(){
$result['test'] = 'promotions';
$this->load->view('h5/record_fast_three',$result);
}
public function game_record_eleven_select_five(){
$result['test'] = 'promotions';
$this->load->view('h5/record_eleven_select_five',$result);
}
public function game_record_three_d_lottery(){
$result['test'] = 'promotions';
$this->load->view('h5/record_three_d_lottery',$result);
}
public function game_record_hong_kong_lottery(){
$result['test'] = 'promotions';
$this->load->view('h5/record_hong_kong_lottery',$result);
}
}
| {
"content_hash": "86d9ce35515f8b65b155a1f9f793ad45",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 74,
"avg_line_length": 28.725,
"alnum_prop": 0.5947200464171744,
"repo_name": "dragonzhu88/ci_framework",
"id": "16a9c3ce9d26406d9300e64383dda30e4e779eb6",
"size": "3447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/controllers/H5.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "364"
},
{
"name": "CSS",
"bytes": "321128"
},
{
"name": "HTML",
"bytes": "8509598"
},
{
"name": "JavaScript",
"bytes": "2398047"
},
{
"name": "PHP",
"bytes": "2080871"
}
],
"symlink_target": ""
} |
<?php
namespace Edu\Cnm\GigHub;
require_once("autoload.php");
/**
* @author Brandon Steider <bsteider@cnm.edu>
* @version 3.0.0
**/
class PostTag implements \JsonSerializable {
/**
* Tag id for this postTag; this is a foreign key
* @var int $postTagId
**/
private $postTagTagId;
/**
* id of the post for this PostTag
* @var int $PostTagPost
**/
private $postTagPostId;
/**
* actual keys of this postTag
*
* @param int $newPostTagPostId id of the Post that is referenced
* @param int $newPostTagTagId id of the Tag that is referenced
* @throws \InvalidArgumentException if data types are not valid
* @throws \RangeException if data values are out of bounds (i.e. negative integers)
* @throws \TypeError if data types violate type hints
* @throws \Exception if some other exception occurs
**/
public function __construct(int $newPostTagPostId, int $newPostTagTagId) {
try {
$this->setPostTagPostId($newPostTagPostId);
$this->setPostTagTagId($newPostTagTagId);
} catch(\InvalidArgumentException $invalidArgument) {
//rethrow the exception to the calller
throw(new \InvalidArgumentException($invalidArgument->getMessage(), 0, $invalidArgument));
} catch(\RangeException $range) {
// rethrow the exception to the caller
throw(new \RangeException($range->getMessage(), 0, $range));
} catch(\TypeError $typeError) {
// rethrow the exception to the caller
throw(new \TypeError($typeError->getMessage(), 0, $typeError));
} catch(\Exception $exception) {
// rethrow the exception to the caller
throw(new\Exception($exception->getMessage(), 0, $exception));
}
}
/* FIXME: accessor for postTagTagId here*/ /*is this good?*/
/**
* accessors for class postTag
*/
/**
* accessor method for postTagTagId
* @return int value of PostTag post Id, foreign key
**/
public function getPostTagTagId() {
return ($this->postTagTagId);
}
/**
* mutator method for post tag tag id
*
* @param int|null $newPostTagTagId new value of post tag id
* @throws \RangeException if $newPostTagTagId is not positive
* @throws \TypeError if $newPostTagTagId is not an integer
**/
public function setPostTagTagId(int $newPostTagTagId) {
// verify the post tag tag id is positive
if($newPostTagTagId <= 0) {
throw(new \RangeException("post tag tag id is not positive"));
}
// convert and store the post tag tag id
$this->postTagTagId = $newPostTagTagId;
}
/**
* accessor method for post tag post id
*
* @return int value of post tag post id
**/
public function getPostTagPostId() {
return ($this->postTagPostId);
}
/**
* mutator method for post tag post id
*
* @param int $newPostTagPostId new value of post tag post id
* @throws \RangeException if $newPostTagPostId is not positive
* @throws \TypeError if $newPostTagPostId is not an integer
**/
public function setPostTagPostId(int $newPostTagPostId) {
// verify the post tag post id is positive
if($newPostTagPostId <= 0) {
throw(new \RangeException("post tag post id is not positive"));
}
// convert and store the post tag post id
$this->postTagPostId = $newPostTagPostId;
}
/**
* this is
* the
* PDO
* placeholder
* so i know where to look
* when i screw the pooch
* good luck.
**/
/**
* inserts this post tag into mySQL
*
* @param \PDO $pdo PDO connection object
* @throws \PDOException when mySQL related errors occur
* @throws \TypeError if $pdo is not a PDO connection object
**/
public function insert(\PDO $pdo) {
// ensure the object exists before inserting
if($this->postTagTagId === null || $this->postTagPostId === null) {
throw(new \PDOException("not a valid postTag"));
}
// create query template
$query = "INSERT INTO postTag(postTagPostId, postTagTagId) VALUES(:postTagPostId, :postTagTagId)";
$statement = $pdo->prepare($query);
// bind the member variables to the place holders in the template
$parameters = ["postTagPostId" => $this->postTagPostId, "postTagTagId" => $this->postTagTagId];
$statement->execute($parameters);
}
/**
* deletes this post tag from mySQL
*
* @param \PDO $pdo PDO connection object
* @throws \PDOException when mySQL related errors occur
* @throws \TypeError if $pdo is not a PDO connection object
**/
public function delete(\PDO $pdo) {
// ensure the object exists before deleting
if($this->postTagTagId === null || $this->postTagPostId === null) {
throw(new \PDOException("not a valid postTag"));
}
// create query template
$query = "DELETE FROM postTag WHERE PostTagPostId = :postTagPostId AND postTagTagId = :postTagTagId";
$statement = $pdo->prepare($query);
// bind the member variables to the place hodlers in the template
$parameters = ["postTagPostId" => $this->postTagPostId, "postTagTagId" => $this->postTagTagId];
$statement->execute($parameters);
}
/**
* gets the post tag by tag id
*
* @param \PDO $pdo PDO connection object
* @param int $postTagTagId tag id to search for
* @param int $postTagPostId tat id to search for
* @return PostTag|null Tag found or null if not found
**/
/* FIXME: this method needs to be renamed getPostTagByPostTagTagIdAndPostTagPostId(), */
/* is this gucci?*/
public static function getPostTagByPostTagTagIdAndPostTagPostId(\PDO $pdo, int $postTagTagId, int $postTagPostId) {
// sanitize the post tag id and post tag id before searching
if($postTagTagId <= 0) {
throw(new \PDOException("post tag tag id is not positive"));
}
if($postTagPostId <= 0) {
throw(new \PDOException("post tag post id is not positive"));
}
// create query template
$query = "SELECT postTagPostId, postTagTagId FROM postTag WHERE postTagPostId = :postTagPostId AND postTagTagId = :postTagTagId";
// $statement->execute($parameters);
$statement = $pdo->prepare($query);
//bind the member variables to the placeholders in the template
$parameters = ["postTagPostId" => $postTagPostId, "postTagTagId" => $postTagTagId];
$statement->execute($parameters);
// grab the tag from mySQL
try {
$postTag = null;
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$row = $statement->fetch();
if($row !== false) {
$postTag = new PostTag($row["postTagPostId"], $row["postTagTagId"]);
}
} catch(\Exception $exception) {
// if the row couldn't be converted, rethrow it
var_dump($exception->getTrace());
throw(new \PDOException($exception->getMessage(), 0, $exception));
}
return ($postTag);
}
/* FIXME: we need 2 more methods:
* - getPostTagsByPostTagTagId() - should return an array of all postTags by tagId
* - LOOK AT: getBeerTagByTagId()
*
* - getPostTagsByPostTagPostId() - should return an array of all postTags by postId
* - LOOK AT: getBeerTagByBeerId()
* */
public static function getPostTagsByPostTagTagId(\PDO $pdo, int $postTagTagId) {
// sanitize the tag id
if($postTagTagId < 0) {
throw(new \PDOException ("Tag Id is not positive"));
}
//create query template
$query = "SELECT postTagPostId, postTagTagId FROM postTag WHERE postTagTagId = :postTagTagId";
$statement = $pdo->prepare($query);
//bind the member variables to the placeholders in the template
$parameters = ["postTagTagId" => $postTagTagId];
$statement->execute($parameters);
//build an array of post tags
$postTags = new \SplFixedArray($statement->rowCount());
$statement->setFetchMode(\PDO::FETCH_ASSOC);
while(($row = $statement->fetch()) !== false) {
try {
$postTag = new PostTag($row["postTagPostId"], $row["postTagTagId"]);
$postTags[$postTags->key()] = $postTag;
$postTags->next();
} catch(\Exception $exception) {
//if the row could not be converted, rethrow it
throw(new \PDOException($exception->getMessage(), 0, $exception));
}
}
return ($postTags);
}
public static function getPostTagsByPostTagPostId(\PDO $pdo, int $postTagPostId) {
//sanitize the post id
if($postTagPostId < 0) {
throw (new \PDOException("post id is not positive"));
}
//create query template
$query = "SELECT postTagPostId, postTagTagId FROM postTag WHERE postTagPostId = :postTagPostId";
$statement = $pdo->prepare($query);
//bind the post id to the place holder in the template
$parameters = ["postTagPostId" => $postTagPostId];
$statement->execute($parameters);
//build an array of postTags
$postTags = new \SplFixedArray($statement->rowCount());
$statement->setFetchMode(\PDO::FETCH_ASSOC);
while(($row = $statement->fetch()) !== false) {
try {
$postTag = new PostTag($row["postTagPostId"], $row["postTagTagId"]);
$postTags[$postTags->key()] = $postTag;
$postTags->next();
} catch(\Exception $exception) {
//if the row cant be converted rethrow it
throw(new \PDOException($exception->getMessage(), 0, $exception));
}
}
return ($postTags);
}
/* are these groovy?*/
/**
* Specify data which should be serialized to JSON
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
//jsonSerialize
/**
* formats the state variables for JSON serialization
*
* @return array resulting state variables to serialize
**/
public function jsonSerialize() {
$fields = get_object_vars($this);
return ($fields);
}
// TODO: Implement jsonSerialize() method.
}
| {
"content_hash": "941d59ac1ba48d4a8f7dfeb9d22c0253",
"timestamp": "",
"source": "github",
"line_count": 286,
"max_line_length": 131,
"avg_line_length": 33.03496503496503,
"alnum_prop": 0.6881879762912786,
"repo_name": "cmd-space/gighub",
"id": "54b667f23b618e887d51dbf1f1c65e7bda6c9c8b",
"size": "9448",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "php/classes/PostTag.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1632"
},
{
"name": "CSS",
"bytes": "3953"
},
{
"name": "JavaScript",
"bytes": "2342"
},
{
"name": "PHP",
"bytes": "321978"
},
{
"name": "TypeScript",
"bytes": "23727"
}
],
"symlink_target": ""
} |
"""RAML (REST API Markup Language) errors."""
__all__ = 'ApiError RequestError ParameterError AuthError'.split()
class ApiError(Exception):
default_status = 500
def __init__(self, message, *args, **data):
self.args = args
self.data = data
self.status = data.get('status', self.default_status)
super(ApiError, self).__init__(message.format(*args, **data))
class RequestError(ApiError):
def __init__(self, status, message='invalid request', *args, **data):
super(RequestError, self).__init__(message, *args, status=status, **data)
class ParameterError(ApiError):
default_status = 400
def __init__(self, name, message='invalid {name}', *args, **data):
super(ParameterError, self).__init__(message, *args, name=name, **data)
class AuthError(ApiError):
default_status = 401
def __init__(self, message='unauthorized', *args, **data):
super(AuthError, self).__init__(message, *args, **data)
| {
"content_hash": "50ad04a26731f20abdb82e3f3400a57f",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 81,
"avg_line_length": 34.857142857142854,
"alnum_prop": 0.6372950819672131,
"repo_name": "salsita/pyraml",
"id": "ccd4016e51ca3e0ebc8304cd9ca41cd681bf03b9",
"size": "976",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/errors.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "18591"
}
],
"symlink_target": ""
} |
require 'grpc'
require 'google/ads/google_ads/v10/services/custom_conversion_goal_service_pb'
module Google
module Ads
module GoogleAds
module V10
module Services
module CustomConversionGoalService
# Proto file describing the CustomConversionGoal service.
#
# Service to manage custom conversion goal.
class Service
include ::GRPC::GenericService
self.marshal_class_method = :encode
self.unmarshal_class_method = :decode
self.service_name = 'google.ads.googleads.v10.services.CustomConversionGoalService'
# Creates, updates or removes custom conversion goals. Operation statuses
# are returned.
rpc :MutateCustomConversionGoals, ::Google::Ads::GoogleAds::V10::Services::MutateCustomConversionGoalsRequest, ::Google::Ads::GoogleAds::V10::Services::MutateCustomConversionGoalsResponse
end
Stub = Service.rpc_stub_class
end
end
end
end
end
end
| {
"content_hash": "3973cc919d2e8e9f0366695b51f000b6",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 201,
"avg_line_length": 33.625,
"alnum_prop": 0.6421933085501859,
"repo_name": "googleads/google-ads-ruby",
"id": "2376ce30ec34a95ff9bd7879141f363018e4770e",
"size": "1867",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/google/ads/google_ads/v10/services/custom_conversion_goal_service_services_pb.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "12358"
},
{
"name": "Ruby",
"bytes": "10304247"
},
{
"name": "Shell",
"bytes": "1082"
}
],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.HDInsight.Models.Management;
using Microsoft.Azure.Management.HDInsight.Models;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.HDInsight.Models
{
public class AzureHDInsightConfig
{
/// <summary>
/// Gets additional Azure Storage Account that you want to enable access to.
/// </summary>
public Dictionary<string, string> AdditionalStorageAccounts { get; private set; }
/// <summary>
/// Gets or sets the StorageName for the default Azure Storage Account.
/// </summary>
public string DefaultStorageAccountName { get; set; }
/// <summary>
/// Gets or sets the StorageKey for the default Azure Storage Account.
/// </summary>
public string DefaultStorageAccountKey { get; set; }
/// <summary>
/// Gets or sets the size of the Head Node.
/// </summary>
public string HeadNodeSize { get; set; }
/// <summary>
/// Gets or sets the size of the Data Node.
/// </summary>
public string WorkerNodeSize { get; set; }
/// <summary>
/// Gets or sets the size of the Zookeeper Node.
/// </summary>
public string ZookeeperNodeSize { get; set; }
/// <summary>
/// Gets or sets the flavor for a cluster.
/// </summary>
public string ClusterType { get; set; }
/// <summary>
/// Gets or sets the component version of a service in the cluster
/// </summary>
public Dictionary<string, string> ComponentVersion { get; set; }
/// <summary>
/// Gets or sets the cluster tier.
/// </summary>
public Tier ClusterTier { get; set; }
/// <summary>
/// Gets or sets the database to store the metadata for Oozie.
/// </summary>
public AzureHDInsightMetastore OozieMetastore { get; set; }
/// <summary>
/// Gets or sets the database to store the metadata for Hive.
/// </summary>
public AzureHDInsightMetastore HiveMetastore { get; set; }
/// <summary>
/// Gets Object id of the service principal.
/// </summary>
public Guid ObjectId { get; set; }
/// <summary>
/// Gets the file path of the client certificate file contents associated with the service principal.
/// </summary>
public byte[] CertificateFileContents { get; set; }
/// <summary>
/// Gets the file path of the client certificate file associated with the service principal.
/// </summary>
public string CertificateFilePath { get; set; }
/// <summary>
/// Gets client certificate password associated with service principal.
/// </summary>
public string CertificatePassword { get; set; }
/// <summary>
/// Gets AAD tenant uri of the service principal
/// </summary>
public Guid AADTenantId { get; set; }
/// <summary>
/// Gets the configurations of this HDInsight cluster.
/// </summary>
public Dictionary<string, Hashtable> Configurations { get; private set; }
/// <summary>
/// Gets config actions for the cluster.
/// </summary>
public Dictionary<ClusterNodeType, List<AzureHDInsightScriptAction>> ScriptActions { get; private set; }
/// <summary>
/// Gets or sets the security profile.
/// </summary>
/// <value>
/// The security profile.
/// </value>
public AzureHDInsightSecurityProfile SecurityProfile { get; set; }
public AzureHDInsightConfig()
{
ClusterType = Constants.Hadoop;
AdditionalStorageAccounts = new Dictionary<string, string>();
Configurations = new Dictionary<string, Hashtable>();
ScriptActions = new Dictionary<ClusterNodeType, List<AzureHDInsightScriptAction>>();
ComponentVersion = new Dictionary<string, string>();
}
}
}
| {
"content_hash": "6ec9823a7251d1bbc91bd4dd542d82a0",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 112,
"avg_line_length": 36.95454545454545,
"alnum_prop": 0.5936859368593685,
"repo_name": "yantang-msft/azure-powershell",
"id": "ea055d343f82cc667a6047130bf0920aafea9b60",
"size": "4880",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "src/ResourceManager/HDInsight/Commands.HDInsight/Models/Management/AzureHDInsightConfig.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "16509"
},
{
"name": "C#",
"bytes": "31797124"
},
{
"name": "HTML",
"bytes": "209"
},
{
"name": "JavaScript",
"bytes": "4979"
},
{
"name": "PHP",
"bytes": "41"
},
{
"name": "PowerShell",
"bytes": "3592947"
},
{
"name": "Ruby",
"bytes": "265"
},
{
"name": "Shell",
"bytes": "50"
},
{
"name": "XSLT",
"bytes": "6114"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven">
<info organisation="org.sonatype.forge"
module="forge-parent"
revision="6"
status="release"
publication="20140514191523"
>
<description homepage="http://forge.sonatype.com/" />
<m:properties__forgeSnapshotId>forge-snapshots</m:properties__forgeSnapshotId>
<m:properties__forgeSnapshotUrl>http://repository.sonatype.org/content/repositories/snapshots</m:properties__forgeSnapshotUrl>
<m:properties__forgeReleaseId>forge-releases</m:properties__forgeReleaseId>
<m:properties__forgeReleaseUrl>http://repository.sonatype.org:8081/service/local/staging/deploy/maven2</m:properties__forgeReleaseUrl>
</info>
<configurations>
<conf name="default" visibility="public" description="runtime dependencies and master artifact can be used with this conf" extends="runtime,master"/>
<conf name="master" visibility="public" description="contains only the artifact published by this module itself, with no transitive dependencies"/>
<conf name="compile" visibility="public" description="this is the default scope, used if none is specified. Compile dependencies are available in all classpaths."/>
<conf name="provided" visibility="public" description="this is much like compile, but indicates you expect the JDK or a container to provide it. It is only available on the compilation classpath, and is not transitive."/>
<conf name="runtime" visibility="public" description="this scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath." extends="compile"/>
<conf name="test" visibility="private" description="this scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases." extends="runtime"/>
<conf name="system" visibility="public" description="this scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository."/>
<conf name="sources" visibility="public" description="this configuration contains the source artifact of this module, if any."/>
<conf name="javadoc" visibility="public" description="this configuration contains the javadoc artifact of this module, if any."/>
<conf name="optional" visibility="public" description="contains all optional dependencies"/>
</configurations>
<publications>
</publications>
</ivy-module>
| {
"content_hash": "6349662468e839e5c17bc188b40288fa",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 245,
"avg_line_length": 89,
"alnum_prop": 0.7756683456024797,
"repo_name": "pkoryzna/zipkin",
"id": "fac8c9f629e72d0709c11bccdbf55c1012dd6f95",
"size": "2581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".ivy2/cache/org.sonatype.forge/forge-parent/ivy-6.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "151299"
},
{
"name": "JavaScript",
"bytes": "1146946"
},
{
"name": "Ruby",
"bytes": "21133"
},
{
"name": "Scala",
"bytes": "1521413"
},
{
"name": "Shell",
"bytes": "2599"
},
{
"name": "XSLT",
"bytes": "473154"
}
],
"symlink_target": ""
} |
require File.expand_path(File.dirname(__FILE__) + '/../../test_helper')
class ThemeFileTest < ThemeTestCase
include ThemeTestHelper
def setup
super
@theme = Theme.find_by_name 'a theme'
@site = @theme.site
@theme.files.destroy_all
end
def expect_valid_file(file, type, path)
file.should be_kind_of(type)
file.should be_valid
file.path.should be_file
file.path.should == path
end
test "instantiates a valid Theme::Preview for a file images/preview.png" do
expect_valid_file(uploaded_preview, Theme::Preview, "#{@theme.path}/images/preview.png")
end
test "instantiates a valid Theme::Template for a valid template extension" do
expect_valid_file(uploaded_template, Theme::Template, "#{@theme.path}/templates/foo/bar/template.html.erb")
end
test "instantiates a valid Theme::Image for a valid asset extension" do
expect_valid_file(uploaded_image, Theme::Image, "#{@theme.path}/images/rails.png")
end
test "instantiates a valid Theme::Image for .ico" do
expect_valid_file(uploaded_icon, Theme::Image, "#{@theme.path}/images/favicon.ico")
end
test "instantiates a valid Theme::Javascript for a valid asset extension" do
expect_valid_file(uploaded_javascript, Theme::Javascript, "#{@theme.path}/javascripts/effects.js")
end
test "instantiates a valid Theme::Stylesheet for a valid asset extension" do
expect_valid_file(uploaded_stylesheet, Theme::Stylesheet, "#{@theme.path}/stylesheets/styles.css")
end
test "destroys the attachment" do
file = uploaded_template
file.destroy
file.path.should_not be_file
end
test "it expires theme asset cache directory for stylesheets when stylesheet is saved" do
stylesheet = uploaded_stylesheet
mock(stylesheet).expire_asset_cache!
stylesheet.save
end
test "it expires theme asset cache directory for javascripts when javascript is saved" do
javascript = uploaded_javascript
mock(javascript).expire_asset_cache!
javascript.save
end
# VALIDATIONS
test "is invalid if :directory/:name is not unique per theme" do
existing = uploaded_image
file = @theme.files.build :name => existing.name, :directory => existing.directory, :data => image_fixture
file.should_not be_valid
file.errors.on('name').should =~ /has already been taken/
end
test "is invalid if the extension is not registered for any type" do
file = Theme::File.new :name => 'invalid.doc', :data => image_fixture
file.should_not be_valid
file.errors.on('data').should =~ /not a valid file type/
end
test "is invalid if directory contains dots" do
file = Theme::File.new :base_path => '../invalid.png', :data => image_fixture
file.should_not be_valid
file.errors.on('data').should =~ /may not contain consecutive dots/
end
test "is invalid if name starts with non-word character" do
file = Theme::File.new(:base_path => '__MACOSX/._event.html.erb')
file.should_not be_valid
file.errors.invalid?('name').should be_true
end
test "is invalid if directory starts with non-word character" do
file = Theme::File.new(:base_path => '.hidden/evil.html.erb')
file.should_not be_valid
file.errors.invalid?('directory').should be_true
end
# CLASS METHODS
test "type_for returns Theme::Template for valid template extensions" do
Theme::Template.valid_extensions.each do |extension|
Theme::File.type_for("", "foo#{extension}").should == "Theme::Template"
end
end
test "type_for returns Theme::Image for valid image extensions" do
Theme::Image.valid_extensions.each do |extension|
Theme::File.type_for("", "foo.#{extension}").should == "Theme::Image"
end
end
test "type_for returns Theme::Javascript for .js" do
Theme::File.type_for("", "foo.js").should == "Theme::Javascript"
end
test "type_for returns Theme::Stylesheet for .js" do
Theme::File.type_for("", "foo.js").should == "Theme::Javascript"
end
test "type_for returns Theme::Preview for a file images/preview.png" do
Theme::File.type_for("images", "preview.png").should == "Theme::Preview"
end
# INSTANCE METHODS
test "base_path returns the path relative to the theme directory" do
uploaded_template.base_path.should == 'templates/foo/bar/template.html.erb'
end
test "changing the directory attribute also moves the file on the disk" do
template = uploaded_template
template.clear_changes!
template.update_attributes!(:directory => 'templates/baz')
expect_valid_file(template, Theme::Template, "#{@theme.path}/templates/baz/template.html.erb")
end
test "changing the name attribute also changes the data_file_name and renames the file on the disk" do
template = uploaded_template
template.clear_changes!
template.update_attributes(:base_path => 'templates/baz/renamed.html.erb')
expect_valid_file(template, Theme::Template, "#{@theme.path}/templates/baz/renamed.html.erb")
end
test "appends an integer to basename to ensure a unique filename if the file exists" do
dirname = "#{Theme.root_dir}/sites/site-#{@site.id}/themes/#{@theme.theme_id}/images"
FileUtils.mkdir_p dirname
FileUtils.copy image_fixture.path, "#{dirname}/rails.png"
uploaded_image.path.should == "#{dirname}/rails.1.png"
uploaded_image.path.should == "#{dirname}/rails.2.png"
end
end
| {
"content_hash": "497db8211e1882f13655bba9902b3b47",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 111,
"avg_line_length": 36.2972972972973,
"alnum_prop": 0.7038346984363366,
"repo_name": "svenfuchs/adva_cms",
"id": "8b6e1900f3e57b1303c07d52c94f0dbff922a4e2",
"size": "5372",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "engines/adva_themes/test/unit/models/theme_file_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "44086"
},
{
"name": "CSS",
"bytes": "283599"
},
{
"name": "ColdFusion",
"bytes": "126937"
},
{
"name": "JavaScript",
"bytes": "5183403"
},
{
"name": "Lasso",
"bytes": "18060"
},
{
"name": "PHP",
"bytes": "90203"
},
{
"name": "Perl",
"bytes": "35153"
},
{
"name": "Python",
"bytes": "39177"
},
{
"name": "Ruby",
"bytes": "1991380"
}
],
"symlink_target": ""
} |
CCMarker automatically marks targets for crowd control according to party make up and abilities
Version: 1.4
Author: sshen81
License: MIT
--]]
-- Local objects
local CCMarker = {};
local CCMarkerButton;
CCMarker_isMarking = false;
CCMarker_UseRepentance = false;
CCMarker_UseWyvern = false;
CCMarker_Callback = {};
CCMARKER_CREDITS = "CCMarker - by Helmet (Uther US). /ccmarker to display help";
CCMARKER_HELP = "/ccmarker mark - turns on/off marking\n/ccmarker targets - sends the party icon list over chat channel\n/ccmarker show - turns on/off the CCMarker button\n/ccmarker repentance on|off - enables Paladin's Repentance\n/ccmarker wyvern on|off - enables Hunter's Wyvern Sting";
CCMARKER_TOOLTIP_HELP = "Left click to toggle crowd control marking\nRight click (hold) and drag to move this button";
-- Constants
SPELL_BANISH = "Banish";
SPELL_BIND = "Bind";
SPELL_FEAR = "Fear";
SPELL_HEX = "Hex";
SPELL_HIBERNATE = "Hibernate";
SPELL_POLYMORPH = "Polymorph";
SPELL_REPENTANCE = "Repentance";
SPELL_SAP = "Sap";
SPELL_SHACKLE = "Shackle";
SPELL_TRAP = "Trap";
SPELL_WYVERN = "Wyvern Sting";
--[[
Party unit table. Stores the party members and their values.
Dynamically adds players to the partyMembers table
]]--
CCMarker_partyMembers = {}
--[[
Creature Type table. This is a separate table because it contains a
prioritized list of CC spells associated with a creature type
]]--
CCMarker_ccTable = {
["Beast"] = { SPELL_SAP, SPELL_HIBERNATE, SPELL_POLYMORPH, SPELL_HEX, SPELL_TRAP, SPELL_FEAR, SPELL_WYVERN },
["Demon"] = { SPELL_SAP, SPELL_BANISH, SPELL_TRAP, SPELL_REPENTANCE, SPELL_FEAR, SPELL_WYVERN },
["Dragonkin"] = { SPELL_SAP, SPELL_HIBERNATE, SPELL_TRAP, SPELL_REPENTANCE, SPELL_FEAR, SPELL_WYVERN },
["Elemental"] = { SPELL_BANISH, SPELL_BIND, SPELL_TRAP, SPELL_FEAR, SPELL_WYVERN },
["Giant"] = { SPELL_REPENTANCE, SPELL_TRAP, SPELL_FEAR, SPELL_WYVERN },
["Humanoid"] = { SPELL_SAP, SPELL_POLYMORPH, SPELL_HEX, SPELL_TRAP, SPELL_REPENTANCE, SPELL_FEAR, SPELL_WYVERN },
["Undead"] = { SPELL_SHACKLE, SPELL_TRAP, SPELL_REPENTANCE, SPELL_FEAR, SPELL_WYVERN },
};
-- Spell table for each class
CCMarker_spellTable = {
["Druid"] = {SPELL_HIBERNATE},
["Hunter"] = {SPELL_TRAP, SPELL_WYVERN},
["Mage"] = {SPELL_POLYMORPH},
["Paladin"] = {SPELL_REPENTANCE},
["Priest"] = {SPELL_SHACKLE},
["Rogue"] = {SPELL_SAP},
["Shaman"] = {SPELL_HEX, SPELL_BIND},
["Warlock"] = {SPELL_BANISH, SPELL_FEAR},
};
-- Target icons
CCMarker_targetIconsTable = {
'{star}',
'{circle}',
'{diamond}',
'{triangle}',
'{moon}',
'{square}',
'{cross}'
};
-------------------------------------------------------------------
-- Events
-------------------------------------------------------------------
function CCMarker_OnLoad(self)
DEFAULT_CHAT_FRAME:AddMessage("|cffffff33"..CCMARKER_CREDITS.."|r");
self:RegisterEvent("PARTY_MEMBERS_CHANGED");
self:RegisterEvent("PARTY_MEMBERS_ENABLE");
self:RegisterEvent("PARTY_MEMBERS_DISABLE");
self:RegisterEvent("PLAYER_TARGET_CHANGED");
SlashCmdList["CCMARKER"] = function(msg)
CCMarker_SlashHandler(msg);
end
SLASH_CCMARKER1 = "/ccmarker";
CCMarker_CreateLayout();
CCMarker_UpdateParty();
end
function CCMarker_OnEvent(self, event, arg1, arg2, arg3)
if event == "PARTY_MEMBERS_CHANGED" or event == "PARTY_MEMBERS_ENABLE" or event == "PARTY_MEMBERS_DISABLE" then
CCMarker_UpdateParty()
elseif event == "PLAYER_TARGET_CHANGED" and CCMarker_isMarking then
CCMarker_MarkTarget()
end
end
function CCMarker_TooltipShow(self)
GameTooltip_SetDefaultAnchor(GameTooltip, self);
GameTooltip:SetText(CCMARKER_TOOLTIP_HELP);
GameTooltip:Show();
end
-------------------------------------------------------------------
-- Marking Related Functions
-------------------------------------------------------------------
--[[
Toggles Marking. When marking is turned off, we set all the party's spells
as available for the next round of marking
]]--
function CCMarker_MarkToggle()
if CCMarker_isMarking then
CCMarker_isMarking = false;
CCMarkerButton:SetBackdropColor(1,1,1);
-- Clear out the party's assignment list
for memberName,partyMemberData in pairs(CCMarker_partyMembers) do
for spellName,spellData in pairs(partyMemberData["SPELLS"]) do
spellData["ASSIGNED"] = false;
end
end
else
CCMarker_isMarking = true;
CCMarkerButton:SetBackdropColor(0,1,0);
CCMarker_MarkTarget();
end
end
--[[
The function that actually marks a target. It performs the following logical steps:
1. Get the target's creature type.
2. Loop through table comparing creature type with known applicable CC abilities
3. Loop through the party table to see if there is someone with that ability that is not already assigned for CC
]]--
function CCMarker_MarkTarget()
if UnitExists("target") and UnitCanAttack("player", "target") then
targetType = UnitCreatureType("target");
for ccTableType,ccTableData in pairs(CCMarker_ccTable) do
if ccTableType == targetType then
--print("Targetted a CC-able: "..targetType);
-- Use ipairs() as this table is ordered by priority
for i,ccSpellName in ipairs(ccTableData) do
--print("Looking for someone who can "..ccSpellName)
for memberName,partyMemberData in pairs(CCMarker_partyMembers) do
-- Check that this party member has an available spell table key matching the spell we're looking for
for spellName,spellData in pairs(partyMemberData["SPELLS"]) do
if spellName == ccSpellName and not spellData["ASSIGNED"] then
--print("Found "..memberName.." who can "..spellName)
-- If there's a way to get the INDEX off of the KEY in a table, then this
-- loop can be removed.
for targetIconNumber,IconName in ipairs(CCMarker_targetIconsTable) do
if IconName == spellData["ICON"] then
-- Set the appropriate icon on the target
SetRaidTarget("target",targetIconNumber)
-- Mark this spell as assigned for CC so it does not attempt to assign again
spellData["ASSIGNED"] = true
return
end
end
end
end
end
end
end
end
end
end
-------------------------------------------------------------------
-- Party Composition Related Functions
-------------------------------------------------------------------
--[[
This function will generate the CCMarker_partyMembers table which contains a complete list of
the party members and CC abilities. This is the table which will be looked up against
to see what CC capabilities can be assigned when targetting.
We try to assign icons at this point to avoid switching them as much as possible during
]]--
function CCMarker_UpdateParty()
local toonClass, toonName, toonRealm;
local partyIndex = 1;
local partyString;
local iconTable = {
'{cross}',
'{square}',
'{moon}',
'{triangle}',
'{diamond}',
'{circle}',
'{star}'
};
-- Clear out the party units table
table.wipe(CCMarker_partyMembers);
-- Fill the party table
for partyIndex = 1,GetNumPartyMembers() do
partyString = "party"..partyIndex;
-- Get this party member's name & class
toonClass = UnitClass(partyString);
toonName, toonRealm = UnitName(partyString);
-- Don't add in Offline party members or classes which are not in the spell table
if UnitIsConnected(partyString) and toonClass and toonName and CCMarker_spellTable[toonClass] then
if not CCMarker_partyMembers[toonName] then
CCMarker_partyMembers[toonName] = { ["CLASS"] = toonClass, ["SPELLS"] = {} };
end
-- Creates party unit's spell table based on a look up
for i,spellName in ipairs(CCMarker_spellTable[toonClass]) do
--[[
Adds the name of the spell to the table, assigns it an icon and marks it as available to use.
If in some corner case scneario we run out of icons, then this is dropped from the list. This
would only happen if there were many party members with multiple CC abilities. In which case,
there's plenty of CC to go around - no need to assign them all.
]]--
if #iconTable > 0 then
if not CCMarker_partyMembers[toonName]["SPELLS"][spellName] then
-- Paladins and Hunters require a special check
if toonClass == "Paladin" then
if CCMarker_UseRepentance then
CCMarker_partyMembers[toonName]["SPELLS"][spellName] = {["ICON"] = iconTable[#iconTable], ["ASSIGNED"] = false};
table.remove(iconTable);
end
elseif toonClass == "Hunter" and spellName == SPELL_WYVERN then
if CCMarker_UseWyvern then
CCMarker_partyMembers[toonName]["SPELLS"][spellName] = {["ICON"] = iconTable[#iconTable], ["ASSIGNED"] = false};
table.remove(iconTable);
end
else
CCMarker_partyMembers[toonName]["SPELLS"][spellName] = {["ICON"] = iconTable[#iconTable], ["ASSIGNED"] = false};
table.remove(iconTable);
end
end
end
end
end
end
-- Add the player
toonClass = UnitClass("player");
toonName, toonRealm = UnitName("player");
if not CCMarker_partyMembers[toonName] then
CCMarker_partyMembers[toonName] = { ["CLASS"] = toonClass, ["SPELLS"] = {} };
end
-- Creates party unit's spell table based on a look up
for i,spellName in ipairs(CCMarker_spellTable[toonClass]) do
--[[
Adds the name of the spell to the table, assigns it an icon and marks it as available to use.
If in some corner case scneario we run out of icons, then this is dropped from the list. This
would only happen if there were many party members with multiple CC abilities. In which case,
there's plenty of CC to go around - no need to assign them all.
]]--
if #iconTable > 0 then
if not CCMarker_partyMembers[toonName]["SPELLS"][spellName] then
-- Paladins and Hunters require a special check
if toonClass == "Paladin" then
if CCMarker_UseRepentance then
CCMarker_partyMembers[toonName]["SPELLS"][spellName] = {["ICON"] = iconTable[#iconTable], ["ASSIGNED"] = false};
table.remove(iconTable);
end
elseif toonClass == "Hunter" and spellName == SPELL_WYVERN then
if CCMarker_UseWyvern then
CCMarker_partyMembers[toonName]["SPELLS"][spellName] = {["ICON"] = iconTable[#iconTable], ["ASSIGNED"] = false};
table.remove(iconTable);
end
else
CCMarker_partyMembers[toonName]["SPELLS"][spellName] = {["ICON"] = iconTable[#iconTable], ["ASSIGNED"] = false};
table.remove(iconTable);
end
end
end
end
end
-------------------------------------------------------------------
-- UI Functions
-------------------------------------------------------------------
function CCMarker_SlashHandler(msg)
local command, rest = msg:match("^(%S*)%s*(.-)$");
if command == "mark" then
CCMarker_MarkToggle();
elseif command == "show" then
if CCMarkerButton:IsShown() then
CCMarkerButton:Hide();
else
CCMarkerButton:Show();
end
elseif command == "targets" then
local channel;
if GetNumPartyMembers() > 0 then
channel = "PARTY";
else
channel = "SAY";
end
for memberName,partyMemberData in pairs(CCMarker_partyMembers) do
for spellName,spellData in pairs(partyMemberData["SPELLS"]) do
--if spellData["ASSIGNED"] then
SendChatMessage(memberName.."-"..spellName.."-"..spellData["ICON"], channel);
--end
end
end
elseif command == "repentance" then
if rest == "on" then
DEFAULT_CHAT_FRAME:AddMessage("|cffffff33".."Repentance Enabled".."|r");
CCMarker_UseRepentance = true;
else
DEFAULT_CHAT_FRAME:AddMessage("|cffffff33".."Repentance Disabled".."|r");
CCMarker_UseRepentance = false;
end
CCMarker_UpdateParty();
elseif command == "wyvern" then
if rest == "on" then
DEFAULT_CHAT_FRAME:AddMessage("|cffffff33".."Wyvern Sting Enabled".."|r");
CCMarker_UseWyvern = true;
else
DEFAULT_CHAT_FRAME:AddMessage("|cffffff33".."Wyvern Sting Disabled".."|r");
CCMarker_UseWyvern = false;
end
CCMarker_UpdateParty();
else
DEFAULT_CHAT_FRAME:AddMessage("|cffffff33"..CCMARKER_HELP.."|r");
end
end
function CCMarker_CreateLayout()
CCMarkerHeader = _G["CCMarkerFrame"];
CCMarkerButton = CreateFrame("Button", "CCButton", CCMarkerHeader, "SecureActionButtonTemplate, CCMarkerButtonTemplate");
CCMarkerButton:SetScript("OnClick", function()
CCMarker_MarkToggle();
end)
CCMarker_UpdateLayout();
end
function CCMarker_UpdateLayout()
local point = "TOPLEFT";
local pointOpposite = "BOTTOMLEFT";
CCMarkerButton:SetPoint(point, CCMarkerHeader, "CENTER", ox, oy);
CCMarkerButton:Show();
end
| {
"content_hash": "7327410f59264227311ffadd53da3ab4",
"timestamp": "",
"source": "github",
"line_count": 359,
"max_line_length": 289,
"avg_line_length": 39.448467966573816,
"alnum_prop": 0.5931365626323966,
"repo_name": "sshen81/CCMarker",
"id": "8db2bfd4941f92629596b67c3d67fc7be38a378f",
"size": "14168",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CCMarker.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "14168"
},
{
"name": "TeX",
"bytes": "269"
}
],
"symlink_target": ""
} |
class AddCommunities < ActiveRecord::Migration[4.2]
def change
create_table "communities", force: true do |t|
t.string "name"
t.timestamps
end
add_column :people, :community_id, :integer
end
end
| {
"content_hash": "6fce02875b93f271556eb3624b2f1224",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 51,
"avg_line_length": 22.5,
"alnum_prop": 0.6622222222222223,
"repo_name": "ministryofjustice/peoplefinder",
"id": "37d8aae7bbb9f69e4b354e8bb8f2300e5d6f7676",
"size": "294",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "db/migrate/20141030110921_add_communities.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2993"
},
{
"name": "CoffeeScript",
"bytes": "2195"
},
{
"name": "Dockerfile",
"bytes": "1574"
},
{
"name": "HTML",
"bytes": "394390"
},
{
"name": "Haml",
"bytes": "62158"
},
{
"name": "JavaScript",
"bytes": "36833"
},
{
"name": "Procfile",
"bytes": "89"
},
{
"name": "Python",
"bytes": "5159"
},
{
"name": "Ruby",
"bytes": "757642"
},
{
"name": "SCSS",
"bytes": "36543"
},
{
"name": "Shell",
"bytes": "11684"
}
],
"symlink_target": ""
} |
using namespace std;
class Lista {
private:
pnodo primero;
pnodo actual;
bool f_lista_vacia(){
return (this->primero==NULL);
}
void f_primero(){
this->actual = this->primero;
}
void f_siguiente(){
this->actual = this->actual->Siguiente;
}
void f_ultimo(){
f_primero();
if (f_lista_vacia()){
while (this->actual->Siguiente){
f_siguiente();
}
}
}
public:
~Lista() {
pnodo aux;
while (this->primero){
aux = this->primero;
this->primero = this->primero->Siguiente;
delete aux;
}
this->actual = NULL;
}
Lista() {
this->actual = NULL;
this->primero = NULL;
}
//agregar un nuevo elemento a la lista
void insertar(char* nombre, char* ape,fecha_ f, float S){
trabajador Trabaja = new Trabajador(nombre,ape,f,S);
pnodo nuevo = new Nodo(Trabaja);
if (this->f_lista_vacia())
this->primero = nuevo;
else
this->actual->Siguiente =nuevo;
this->actual = nuevo;
}
void Mostrar(){
pnodo aux;
aux = this->primero;
while (aux){
cout<<"Nombre Apellidos Sueldo "<<endl;
cout << aux->Valor->nombre<<" "<<aux->Valor->apellidos<<" "<<aux->Valor->sueldo <<endl;
//aux->Valor->MostrarNombres();
//aux->Valor->MostrarFechaNac();
aux = aux->Siguiente;
}
}
//encargada de mostrar lo buscado con search
void Buscar(char *nombre, char *apellidos){
pnodo aux = search(nombre,apellidos);
cout<<aux->Valor->nombre<<" "<<aux->Valor->apellidos;
}
pnodo search(char *nombre, char *apellidos){
pnodo aux;
bool encontrado = false;
if(this->f_lista_vacia()){
aux = NULL;
}else{
aux = this->primero;
while(aux && !encontrado){
if(aux->Valor->nombre == nombre && aux->Valor->apellidos == apellidos){
encontrado = true;
}else{
aux = aux->Siguiente;
}
}
}
return aux;
}
pnodo search_before(pnodo valor){
pnodo aux ;
bool encontrado = false;
aux = this->primero;
while(aux && !encontrado){
if(aux->Siguiente == valor){
encontrado = true;
}else{
aux = aux->Siguiente;
}
}
return aux;
}
void delet(char *nombre, char *apellidos){
if(!this->f_lista_vacia()){
//buscar el objeto con el valor deseado
pnodo aux = search(nombre,apellidos);
//saber el objeto a borar no es el priero
pnodo aux_anterior;
if(aux != this->primero){
aux_anterior = search_before( aux );
aux_anterior->Siguiente = aux->Siguiente;
delete aux;
}else{
this->primero = aux->Siguiente;
}
//buscarenterior
}else{
cout << "La lista esta vacia";
}
}
};
#endif //LISTA_LISTA_H
| {
"content_hash": "a6482cab9a53a32713c424fad572025d",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 106,
"avg_line_length": 25.59375,
"alnum_prop": 0.4816849816849817,
"repo_name": "hitokiri/listas-c-",
"id": "436db5697cd50c66516887e9508c15ab834584aa",
"size": "3400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lista(parcial1-progra3)/Lista.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "96461"
},
{
"name": "CMake",
"bytes": "2111"
}
],
"symlink_target": ""
} |
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace CodeTiger.CodeAnalysis.Analyzers.Reliability
{
/// <summary>
/// Analyzes code related to threading for potential reliability issues.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ThreadingReliabilityAnalyzer : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor ThreadResetAbortShouldNotBeUsedDescriptor
= new DiagnosticDescriptor("CT2005", "Thread.ResetAbort should not be used.",
"Thread.ResetAbort should not be used.", "CodeTiger.Reliability", DiagnosticSeverity.Warning,
true);
internal static readonly DiagnosticDescriptor
ThreadSynchronizationShouldNotBeDoneUsingAPubliclyAccessibleObjectDescriptor
= new DiagnosticDescriptor("CT2006",
"Thread synchronization should not be done using a publicly accessible object.",
"Thread synchronization should not be done using a publicly accessible object.",
"CodeTiger.Reliability", DiagnosticSeverity.Warning, true);
/// <summary>
/// Gets a set of descriptors for the diagnostics that this analyzer is capable of producing.
/// </summary>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(ThreadResetAbortShouldNotBeUsedDescriptor,
ThreadSynchronizationShouldNotBeDoneUsingAPubliclyAccessibleObjectDescriptor);
}
}
/// <summary>
/// Registers actions in an analysis context.
/// </summary>
/// <param name="context">The context to register actions in.</param>
/// <remarks>This method should only be called once, at the start of a session.</remarks>
public override void Initialize(AnalysisContext context)
{
Guard.ArgumentIsNotNull(nameof(context), context);
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSemanticModelAction(AnalyzeThreadResetAbortUsage);
context.RegisterSemanticModelAction(AnalyzeThreadSynchronizationObjects);
}
private static void AnalyzeThreadResetAbortUsage(SemanticModelAnalysisContext context)
{
var threadType = context.SemanticModel.Compilation?.GetTypeByMetadataName("System.Threading.Thread");
if (threadType == null)
{
return;
}
var resetAbortSymbols = threadType.GetMembers("ResetAbort");
if (resetAbortSymbols.IsDefaultOrEmpty)
{
return;
}
var root = context.SemanticModel.SyntaxTree.GetRoot(context.CancellationToken);
foreach (var invocation in root.DescendantNodes().OfType<InvocationExpressionSyntax>())
{
var invokedSymbol = context.SemanticModel
.GetSymbolInfo(invocation.Expression, context.CancellationToken).Symbol
?? context.SemanticModel
.GetDeclaredSymbol(invocation.Expression, context.CancellationToken);
if (resetAbortSymbols.Any(x => x.Equals(invokedSymbol)))
{
context.ReportDiagnostic(Diagnostic.Create(ThreadResetAbortShouldNotBeUsedDescriptor,
invocation.Expression.GetLocation()));
}
}
}
private static void AnalyzeThreadSynchronizationObjects(SemanticModelAnalysisContext context)
{
var root = context.SemanticModel.SyntaxTree.GetRoot(context.CancellationToken);
foreach (var node in root.DescendantNodes())
{
SyntaxNode lockObjectNode;
switch (node.Kind())
{
case SyntaxKind.LockStatement:
lockObjectNode = ((LockStatementSyntax)node).Expression;
break;
case SyntaxKind.InvocationExpression:
// TODO: Expand this to work with thread synchronization classes (Monitor, etc.)
lockObjectNode = null;
break;
default:
lockObjectNode = null;
break;
}
if (lockObjectNode != null)
{
if (IsPubliclyAccessible(context, lockObjectNode))
{
context.ReportDiagnostic(Diagnostic.Create(
ThreadSynchronizationShouldNotBeDoneUsingAPubliclyAccessibleObjectDescriptor,
lockObjectNode.GetLocation()));
}
}
}
}
private static bool IsPubliclyAccessible(SemanticModelAnalysisContext context, SyntaxNode node)
{
if (node.Kind() == SyntaxKind.ThisExpression || node.Kind() == SyntaxKind.BaseExpression)
{
return true;
}
if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression
|| node.Kind() == SyntaxKind.PointerMemberAccessExpression)
{
var memberAccessExpression = (MemberAccessExpressionSyntax)node;
if (!IsPubliclyAccessible(context, memberAccessExpression.Expression))
{
return false;
}
}
return context.SemanticModel.GetSymbolInfo(node, context.CancellationToken).Symbol
?.DeclaredAccessibility == Accessibility.Public;
}
}
}
| {
"content_hash": "42e806f5f01aea9bbadcb05fdad3a1d7",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 113,
"avg_line_length": 41.74305555555556,
"alnum_prop": 0.6068873731492265,
"repo_name": "csdahlberg/CodeTiger.CodeAnalysis",
"id": "3aaefb31846ecd7595dc16aa50c04bca52f7eb21",
"size": "6013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CodeTiger.CodeAnalysis/Analyzers/Reliability/ThreadingReliabilityAnalyzer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "837923"
},
{
"name": "PowerShell",
"bytes": "6167"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Diplodia acanthophylli Kalymb.
### Remarks
null | {
"content_hash": "393065d58d64061b02827dbb9712f3bd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 30,
"avg_line_length": 10.384615384615385,
"alnum_prop": 0.7185185185185186,
"repo_name": "mdoering/backbone",
"id": "c7390d62cb414bb64f0442f3cb9f3a665a58ab1c",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Botryosphaeriales/Botryosphaeriaceae/Diplodia/Diplodia acanthophylli/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System.Xml.Linq;
using Hydra.Framework;
using Hydra.Framework.Logging;
namespace Hydra.Framework.Data
{
/// <summary>
/// Provides for conversion and population to and from an XElement.
/// Allows an object instance to be converted to XML and perhaps serialized.
/// </summary>
public interface IXmlConvertible
{
/// <summary>
/// Populates the instance from the values in the specified element.
/// This is the reverse process of <see cref="ToXElement"/>.
/// </summary>
/// <param name="element">The element.</param>
void FromXElement(XElement element);
/// <summary>
/// Convert to an XElement. This is the reverse process of <see cref="FromXElement"/>.
/// </summary>
/// <returns>An element representing the current object instance.</returns>
XElement ToXElement();
}
}
| {
"content_hash": "71c0a9f9846589eb892e012704cf3b83",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 88,
"avg_line_length": 30.14814814814815,
"alnum_prop": 0.7039312039312039,
"repo_name": "andywiddess/Hydra",
"id": "36f925a4149cbc0c8d2457806b661fe0db37dbf0",
"size": "816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "1/Framework/Data/IXmlConvertible.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "10373404"
},
{
"name": "XSLT",
"bytes": "12550"
}
],
"symlink_target": ""
} |
'use strict';
var dash = require('../../drawing/attributes').dash;
var extendFlat = require('../../../lib/extend').extendFlat;
module.exports = {
newshape: {
line: {
color: {
valType: 'color',
editType: 'none',
role: 'info',
description: [
'Sets the line color.',
'By default uses either dark grey or white',
'to increase contrast with background color.'
].join(' ')
},
width: {
valType: 'number',
min: 0,
dflt: 4,
role: 'info',
editType: 'none',
description: 'Sets the line width (in px).'
},
dash: extendFlat({}, dash, {
dflt: 'solid',
editType: 'none'
}),
role: 'info',
editType: 'none'
},
fillcolor: {
valType: 'color',
dflt: 'rgba(0,0,0,0)',
role: 'info',
editType: 'none',
description: [
'Sets the color filling new shapes\' interior.',
'Please note that if using a fillcolor with alpha greater than half,',
'drag inside the active shape starts moving the shape underneath,',
'otherwise a new shape could be started over.'
].join(' ')
},
fillrule: {
valType: 'enumerated',
values: ['evenodd', 'nonzero'],
dflt: 'evenodd',
role: 'info',
editType: 'none',
description: [
'Determines the path\'s interior.',
'For more info please visit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule'
].join(' ')
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 1,
role: 'info',
editType: 'none',
description: 'Sets the opacity of new shapes.'
},
layer: {
valType: 'enumerated',
values: ['below', 'above'],
dflt: 'above',
role: 'info',
editType: 'none',
description: 'Specifies whether new shapes are drawn below or above traces.'
},
drawdirection: {
valType: 'enumerated',
role: 'info',
values: ['ortho', 'horizontal', 'vertical', 'diagonal'],
dflt: 'diagonal',
editType: 'none',
description: [
'When `dragmode` is set to *drawrect*, *drawline* or *drawcircle*',
'this limits the drag to be horizontal, vertical or diagonal.',
'Using *diagonal* there is no limit e.g. in drawing lines in any direction.',
'*ortho* limits the draw to be either horizontal or vertical.',
'*horizontal* allows horizontal extend.',
'*vertical* allows vertical extend.'
].join(' ')
},
editType: 'none'
},
activeshape: {
fillcolor: {
valType: 'color',
dflt: 'rgb(255,0,255)',
role: 'style',
editType: 'none',
description: 'Sets the color filling the active shape\' interior.'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.5,
role: 'info',
editType: 'none',
description: 'Sets the opacity of the active shape.'
},
editType: 'none'
}
};
| {
"content_hash": "8834de02c8007e655eef0eb694017ef2",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 113,
"avg_line_length": 32.45614035087719,
"alnum_prop": 0.4481081081081081,
"repo_name": "aburato/plotly.js",
"id": "90d6cb810e564932f35b2c27d66e32c55e531959",
"size": "3891",
"binary": false,
"copies": "1",
"ref": "refs/heads/ion-build-1.56",
"path": "src/components/shapes/draw_newshape/attributes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9607"
},
{
"name": "HTML",
"bytes": "2358"
},
{
"name": "JavaScript",
"bytes": "3137736"
}
],
"symlink_target": ""
} |
FROM balenalib/orange-pi-zero-alpine:3.10-build
ENV NODE_VERSION 14.15.4
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 ha.pool.sks-keyservers.net --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 "9fc6c438cd4a893873c6bfa99e80a785e102123890506781c6f320c17928f4e7 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.10 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.15.4, 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": "27918f46d09745d6afad42dff65edf14",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 699,
"avg_line_length": 65.33333333333333,
"alnum_prop": 0.7112244897959183,
"repo_name": "nghiant2710/base-images",
"id": "af4861bc09cefe12e2797d383b15bca1d0b80766",
"size": "2961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/orange-pi-zero/alpine/3.10/14.15.4/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
package org.apache.pdfbox.examples.interactive.form;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceCharacteristicsDictionary;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
/**
* Add a border to an existing field.
*
* This sample adds a border to a field.
*
* This sample builds on the form generated by @link CreateSimpleForm so you need to run that first.
*
*/
public final class AddBorderToField
{
private AddBorderToField()
{
}
public static void main(String[] args) throws IOException
{
// Load the PDF document created by SimpleForm.java
PDDocument document = PDDocument.load(new File("target/SimpleForm.pdf"));
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
// Get the field and the widget associated to it.
// Note: there might be multiple widgets
PDField field = acroForm.getField("SampleField");
PDAnnotationWidget widget = field.getWidgets().get(0);
// Create the definition for a green border
PDAppearanceCharacteristicsDictionary fieldAppearance =
new PDAppearanceCharacteristicsDictionary(new COSDictionary());
PDColor green = new PDColor(new float[] { 0, 1, 0 }, PDDeviceRGB.INSTANCE);
fieldAppearance.setBorderColour(green);
// Set the information to be used by the widget which is responsible
// for the visual style of the form field.
widget.setAppearanceCharacteristics(fieldAppearance);
document.save("target/AddBorderToField.pdf");
document.close();
}
}
| {
"content_hash": "c1dbfd689fb45e1a1274299fa97d0619",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 100,
"avg_line_length": 37.236363636363635,
"alnum_prop": 0.71728515625,
"repo_name": "mathieufortin01/pdfbox",
"id": "79acaf222724670b98e03aa1f7d0a5f5d437cebf",
"size": "2850",
"binary": false,
"copies": "4",
"ref": "refs/heads/trunk",
"path": "examples/src/main/java/org/apache/pdfbox/examples/interactive/form/AddBorderToField.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "61531"
},
{
"name": "Java",
"bytes": "6653793"
}
],
"symlink_target": ""
} |
package org.opentides.util;
import static org.junit.Assert.*;
import junit.framework.Assert;
import org.junit.Test;
/**
* @author allantan
*
*/
public class ValidatorUtilTest {
/**
* Test method for {@link org.opentides.util.ValidatorUtil#isEmail(java.lang.String)}.
*/
@Test
public void testIsEmail() {
Assert.assertTrue(ValidatorUtil.isEmail("allan@ideyatech.com"));
Assert.assertTrue(ValidatorUtil.isEmail("ab.test@ic.com"));
Assert.assertTrue(ValidatorUtil.isEmail("ab.test@bing-gom.com"));
Assert.assertTrue(ValidatorUtil.isEmail("a@b.com"));
Assert.assertFalse(ValidatorUtil.isEmail("com"));
Assert.assertFalse(ValidatorUtil.isEmail("a@boo"));
}
/**
* Test method for {@link org.opentides.util.ValidatorUtil#isPhoneNumber(java.lang.String)}.
*/
@Test
public void testIsPhoneNumber() {
Assert.assertTrue(ValidatorUtil.isPhoneNumber("120-234-1234"));
Assert.assertTrue(ValidatorUtil.isPhoneNumber("12"));
Assert.assertTrue(ValidatorUtil.isPhoneNumber("123-456"));
Assert.assertFalse(ValidatorUtil.isPhoneNumber("a1234-3"));
Assert.assertFalse(ValidatorUtil.isPhoneNumber("0.12.4556"));
}
/**
* Test method for {@link org.opentides.util.ValidatorUtil#isNumeric(java.lang.String)}.
*/
@Test
public void testIsNumeric() {
Assert.assertTrue(ValidatorUtil.isNumeric("12345678"));
Assert.assertTrue(ValidatorUtil.isNumeric("12"));
Assert.assertTrue(ValidatorUtil.isNumeric("0123"));
Assert.assertFalse(ValidatorUtil.isNumeric("a1234-3"));
Assert.assertFalse(ValidatorUtil.isNumeric("0.12.4556"));
}
/**
* Test method for {@link org.opentides.util.ValidatorUtil#isValidDateRange(java.util.Date, java.util.Date, java.lang.String)}.
*/
@Test
public void testIsValidDateRange() {
}
}
| {
"content_hash": "a48f39195afa3d82db1afc2eb9996e05",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 128,
"avg_line_length": 28.338709677419356,
"alnum_prop": 0.7381900967558338,
"repo_name": "Letractively/open-tides",
"id": "72404cedef6cd88a0c262f9bfee8737124483609",
"size": "2564",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/org/opentides/util/ValidatorUtilTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10185"
},
{
"name": "Java",
"bytes": "973733"
},
{
"name": "JavaScript",
"bytes": "351620"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.fs.shell.find;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.io.IOException;
import java.util.Deque;
import org.apache.hadoop.fs.shell.PathData;
import org.apache.hadoop.fs.shell.find.Expression;
import org.apache.hadoop.fs.shell.find.FilterExpression;
import org.apache.hadoop.fs.shell.find.FindOptions;
import org.apache.hadoop.fs.shell.find.Result;
import org.junit.Before;
import org.junit.Test;
public class TestFilterExpression extends TestExpression {
private Expression expr;
private FilterExpression test;
@Before
public void setup() {
expr = mock(Expression.class);
test = new FilterExpression(expr){};
}
@Test
public void expression() throws IOException {
assertEquals(expr, test.expression);
}
@Test
public void initialise() throws IOException {
FindOptions options = mock(FindOptions.class);
test.initialise(options);
verify(expr).initialise(options);
verifyNoMoreInteractions(expr);
}
@Test
public void apply() throws IOException {
PathData item = mock(PathData.class);
when(expr.apply(item)).thenReturn(Result.PASS).thenReturn(Result.FAIL);
assertEquals(Result.PASS, test.apply(item));
assertEquals(Result.FAIL, test.apply(item));
verify(expr, times(2)).apply(item);
verifyNoMoreInteractions(expr);
}
@Test
public void finish() throws IOException {
test.finish();
verify(expr).finish();
verifyNoMoreInteractions(expr);
}
@Test
public void getUsage() {
String[] usage = new String[]{"Usage 1", "Usage 2", "Usage 3"};
when(expr.getUsage()).thenReturn(usage);
assertArrayEquals(usage, test.getUsage());
verify(expr).getUsage();
verifyNoMoreInteractions(expr);
}
@Test
public void getHelp() {
String[] help = new String[]{"Help 1", "Help 2", "Help 3"};
when(expr.getHelp()).thenReturn(help);
assertArrayEquals(help, test.getHelp());
verify(expr).getHelp();
verifyNoMoreInteractions(expr);
}
@Test
public void isAction() {
when(expr.isAction()).thenReturn(true).thenReturn(false);
assertTrue(test.isAction());
assertFalse(test.isAction());
verify(expr, times(2)).isAction();
verifyNoMoreInteractions(expr);
}
@Test
public void isOperator() {
when(expr.isAction()).thenReturn(true).thenReturn(false);
assertTrue(test.isAction());
assertFalse(test.isAction());
verify(expr, times(2)).isAction();
verifyNoMoreInteractions(expr);
}
@Test
public void getPrecedence() {
int precedence = 12345;
when(expr.getPrecedence()).thenReturn(precedence);
assertEquals(precedence, test.getPrecedence());
verify(expr).getPrecedence();
verifyNoMoreInteractions(expr);
}
@Test
public void addChildren() {
@SuppressWarnings("unchecked") Deque<Expression> expressions = mock(Deque.class);
test.addChildren(expressions);
verify(expr).addChildren(expressions);
verifyNoMoreInteractions(expr);
}
@Test
public void addArguments() {
@SuppressWarnings("unchecked") Deque<String> args = mock(Deque.class);
test.addArguments(args);
verify(expr).addArguments(args);
verifyNoMoreInteractions(expr);
}
}
| {
"content_hash": "6a8ef7b20b8e57423d698b2f437e5b70",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 85,
"avg_line_length": 27.934959349593495,
"alnum_prop": 0.7086728754365541,
"repo_name": "cloudera/search",
"id": "d6985b3aa9c696a53995f34a09bb4b18753ad435",
"size": "4242",
"binary": false,
"copies": "1",
"ref": "refs/heads/cdh5-1.0.0_5.2.0",
"path": "search-mr/src/test/java/org/apache/hadoop/fs/shell/find/TestFilterExpression.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "535060"
}
],
"symlink_target": ""
} |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Sync\V1\Service;
use Twilio\Deserialize;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;
/**
* PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
*
* @property string sid
* @property string uniqueName
* @property string accountSid
* @property string serviceSid
* @property string url
* @property array links
* @property \DateTime dateCreated
* @property \DateTime dateUpdated
* @property string createdBy
*/
class SyncStreamInstance extends InstanceResource {
protected $_streamMessages = null;
/**
* Initialize the SyncStreamInstance
*
* @param \Twilio\Version $version Version that contains the resource
* @param mixed[] $payload The response payload
* @param string $serviceSid Service Instance SID.
* @param string $sid Stream SID or unique name.
* @return \Twilio\Rest\Sync\V1\Service\SyncStreamInstance
*/
public function __construct(Version $version, array $payload, $serviceSid, $sid = null) {
parent::__construct($version);
// Marshaled Properties
$this->properties = array(
'sid' => Values::array_get($payload, 'sid'),
'uniqueName' => Values::array_get($payload, 'unique_name'),
'accountSid' => Values::array_get($payload, 'account_sid'),
'serviceSid' => Values::array_get($payload, 'service_sid'),
'url' => Values::array_get($payload, 'url'),
'links' => Values::array_get($payload, 'links'),
'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
'createdBy' => Values::array_get($payload, 'created_by'),
);
$this->solution = array(
'serviceSid' => $serviceSid,
'sid' => $sid ?: $this->properties['sid'],
);
}
/**
* Generate an instance context for the instance, the context is capable of
* performing various actions. All instance actions are proxied to the context
*
* @return \Twilio\Rest\Sync\V1\Service\SyncStreamContext Context for this
* SyncStreamInstance
*/
protected function proxy() {
if (!$this->context) {
$this->context = new SyncStreamContext(
$this->version,
$this->solution['serviceSid'],
$this->solution['sid']
);
}
return $this->context;
}
/**
* Fetch a SyncStreamInstance
*
* @return SyncStreamInstance Fetched SyncStreamInstance
*/
public function fetch() {
return $this->proxy()->fetch();
}
/**
* Deletes the SyncStreamInstance
*
* @return boolean True if delete succeeds, false otherwise
*/
public function delete() {
return $this->proxy()->delete();
}
/**
* Access the streamMessages
*
* @return \Twilio\Rest\Sync\V1\Service\SyncStream\StreamMessageList
*/
protected function getStreamMessages() {
return $this->proxy()->streamMessages;
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get($name) {
if (array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (property_exists($this, '_' . $name)) {
$method = 'get' . ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Sync.V1.SyncStreamInstance ' . implode(' ', $context) . ']';
}
} | {
"content_hash": "2a179733b31b5648d9faa6dbfe1ba339",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 104,
"avg_line_length": 30.573426573426573,
"alnum_prop": 0.581427264409881,
"repo_name": "ShreyaR13/Twilio-SMS-Project-Part-1",
"id": "443ee7822a648b6782175482386923b923081c46",
"size": "4372",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "twilio-php-master/Twilio/Rest/Sync/V1/Service/SyncStreamInstance.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "8892"
},
{
"name": "PHP",
"bytes": "5825218"
},
{
"name": "Python",
"bytes": "9796"
},
{
"name": "Shell",
"bytes": "333"
}
],
"symlink_target": ""
} |
<?php
namespace Squid\MySql\Command;
interface IWithColumns
{
/**
* @param array $columns
* @return static
*/
public function column(...$columns);
/**
* @param string|array $columns
* @param string|bool $table
* @return static
*/
public function columns($columns, $table = false);
/**
* @param string|array $columns
* @param bool|array $bind
* @return static
*/
public function columnsExp($columns, $bind = []);
/**
* @param string $column
* @param string $alias
* @return static
*/
public function columnAs($column, $alias);
/**
* @param string $column
* @param string $alias
* @param array|bool $bind
* @return static
*/
public function columnAsExp($column, $alias, $bind = []);
} | {
"content_hash": "15402a2f331416d17382315675bb7299",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 58,
"avg_line_length": 18.097560975609756,
"alnum_prop": 0.6307277628032345,
"repo_name": "Oktopost/Squid",
"id": "2dd8d3ce94730f6269fcf8150639ef2d4c2aad33",
"size": "742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Squid/MySql/Command/IWithColumns.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "620"
},
{
"name": "PHP",
"bytes": "532336"
}
],
"symlink_target": ""
} |
<template name='recipyDetails'>
{{#each recipyList}}
{{> recipyDescription}}
{{/each}}
</template>
<template name='recipyDescription'>
<div class='page-header'>
<h1>{{title}}</h1>
</div>
<div class='comment pre lead mainText'>{{#markdown}}{{comment}}{{/markdown}}</div>
<div class='ingrediences pre mainText'>{{#markdown}}{{ingrediences}}{{/markdown}}</div>
<div class='description pre mainText'>{{#markdown}}{{description}}{{/markdown}}</div>
<div class='recipyBy mainText'>Recept av {{username}}</div>
<div class='tag-display mainText'>{{tags}}</div>
{{#if currentUser}}
<a href='/editRecipy/{{slug}}' class='btn btn-warning editRecipyBtn'><i class="glyphicon glyphicon-edit"></i>Ändra</a>
{{/if}}
</template> | {
"content_hash": "1a4630fea859e085c20dddf6ab13525d",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 120,
"avg_line_length": 38.36842105263158,
"alnum_prop": 0.6707818930041153,
"repo_name": "hfogelberg/fogelmat",
"id": "70cb7c5af4c5f75ef088fe5bfccb270f9300f4e3",
"size": "730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/templates/recipy.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4946"
},
{
"name": "CoffeeScript",
"bytes": "10188"
},
{
"name": "HTML",
"bytes": "8305"
}
],
"symlink_target": ""
} |
using Azure.Core.Pipeline;
namespace Azure.ResourceManager.DataMigration
{
internal static class ProviderConstants
{
public static string DefaultProviderNamespace { get; } = ClientDiagnostics.GetResourceProviderNamespace(typeof(ProviderConstants).Assembly);
}
}
| {
"content_hash": "f21d1cc1dcfd159b9e843a7f694a2ad8",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 148,
"avg_line_length": 31.444444444444443,
"alnum_prop": 0.7809187279151943,
"repo_name": "Azure/azure-sdk-for-net",
"id": "78a736ffae2440fd53493087f7ec16da8e3d9913",
"size": "421",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/datamigration/Azure.ResourceManager.DataMigration/src/Generated/ProviderConstants.cs",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
BrickBotServoDriver::BrickBotServoDriver(int leftMotorPin, int rightMotorPin) {
leftMotor = new Servo();
leftMotor->attach(leftMotorPin);
leftMotor->write(BB_MOTOR_STOP);
rightMotor = new Servo();
rightMotor->attach(rightMotorPin);
rightMotor->write(BB_MOTOR_STOP);
resetMotorCalibration();
}
uint8_t BrickBotServoDriver::getMotorSpeed(int motor) {
Servo *servo = (motor == BB_MOTOR_LEFT) ? leftMotor : rightMotor;
return servo->read();
}
void BrickBotServoDriver::setMotorValue(int motor, int spd) {
Servo *servo = (motor == BB_MOTOR_LEFT) ? leftMotor : rightMotor;
// If this is a switch from forward/backward then send the
// stop signal and set a delay
if ((spd > BB_MOTOR_STOP && currentSpeed[motor] < BB_MOTOR_STOP) ||
(spd < BB_MOTOR_STOP && currentSpeed[motor] > BB_MOTOR_STOP)) {
servo->write(BB_MOTOR_STOP);
delay(50);
}
// write to the appropriate motor
servo->write(spd);
currentSpeed[motor] = spd;
} | {
"content_hash": "eebd6be502aa3ee146b65d4f776b8685",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 79,
"avg_line_length": 31.242424242424242,
"alnum_prop": 0.6527643064985451,
"repo_name": "syoung-smallwisdom/BrickBot_Arduino",
"id": "677838199d8f1e03d86dc62f32bf252c870a522d",
"size": "1225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BrickBotServoDriver.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "328"
},
{
"name": "C++",
"bytes": "74072"
}
],
"symlink_target": ""
} |
package com.streamsets.pipeline.stage.processor.fieldmask;
import com.google.common.annotations.VisibleForTesting;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.base.OnRecordErrorException;
import com.streamsets.pipeline.api.base.SingleLaneRecordProcessor;
import com.streamsets.pipeline.api.el.ELEval;
import com.streamsets.pipeline.api.el.ELVars;
import com.streamsets.pipeline.lib.util.FieldPathExpressionUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FieldMaskProcessor extends SingleLaneRecordProcessor {
private static final Logger LOG = LoggerFactory.getLogger(FieldMaskProcessor.class);
private static final String FIXED_LENGTH_MASK = "xxxxxxxxxx";
private static final char NON_MASK_CHAR = '#';
private static final char MASK_CHAR = 'x';
/**
* All configurations as they were specified by user
*/
private final List<FieldMaskConfig> allFieldMaskConfigs;
/**
* Configurations for which it makes sense to use - potentially a subset of all configurations
*/
private final List<FieldMaskConfig> activeFieldMaskConfigs;
private Map<String, Set<Integer>> regexToGroupsToShowMap = new HashMap<>();
private Map<String, Pattern> regExToPatternMap = new HashMap<>();
private ELEval fieldPathEval;
private ELVars fieldPathVars;
public FieldMaskProcessor(List<FieldMaskConfig> fieldMaskConfigs) {
this.allFieldMaskConfigs = fieldMaskConfigs;
this.activeFieldMaskConfigs = new LinkedList<>();
}
@Override
protected List<ConfigIssue> init() {
List<ConfigIssue> issues = super.init();
activeFieldMaskConfigs.clear();
for(FieldMaskConfig fieldMaskConfig : allFieldMaskConfigs) {
// Skip configurations with empty fields
if(!fieldMaskConfig.fields.isEmpty()) {
activeFieldMaskConfigs.add(fieldMaskConfig);
}
if(fieldMaskConfig.maskType == MaskType.REGEX) {
Pattern p = Pattern.compile(fieldMaskConfig.regex);
int maxGroupCount = p.matcher("").groupCount();
if(maxGroupCount == 0) {
issues.add(getContext().createConfigIssue(Groups.MASKING.name(), "groupsToShow", Errors.MASK_03,
fieldMaskConfig.regex));
} else {
regExToPatternMap.put(fieldMaskConfig.regex, p);
if (fieldMaskConfig.groupsToShow == null || fieldMaskConfig.groupsToShow.trim().isEmpty()) {
issues.add(getContext().createConfigIssue(Groups.MASKING.name(), "groupsToShow", Errors.MASK_02));
return issues;
} else {
String[] groupsToShowString = fieldMaskConfig.groupsToShow.split(",");
Set<Integer> groups = new HashSet<>();
for (String groupString : groupsToShowString) {
try {
int groupToShow = Integer.parseInt(groupString.trim());
if (groupToShow <= 0 || groupToShow > maxGroupCount) {
issues.add(getContext().createConfigIssue(Groups.MASKING.name(), "groupsToShow", Errors.MASK_01,
groupToShow, fieldMaskConfig.regex, maxGroupCount));
}
groups.add(groupToShow);
} catch (NumberFormatException e) {
issues.add(getContext().createConfigIssue(Groups.MASKING.name(), "groupsToShow", Errors.MASK_01, groupString
, fieldMaskConfig.regex, maxGroupCount, e.toString(), e));
}
}
regexToGroupsToShowMap.put(fieldMaskConfig.regex, groups);
}
}
}
}
fieldPathEval = getContext().createELEval("fields");
fieldPathVars = getContext().createELVars();
return issues;
}
@Override
protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException {
Set<String> fieldPaths = record.getEscapedFieldPaths();
List<String> nonStringFields = new ArrayList<>();
// For each individual configuration entry
for(FieldMaskConfig fieldMaskConfig : activeFieldMaskConfigs) {
// For each configured field expression
for (String toMask : fieldMaskConfig.fields) {
// Find all actual fields that matches given configured expression
for (String matchingFieldPath : FieldPathExpressionUtil.evaluateMatchingFieldPaths(
toMask,
fieldPathEval,
fieldPathVars,
record,
fieldPaths
)) {
if (record.has(matchingFieldPath)) {
Field field = record.get(matchingFieldPath);
if (field.getType() != Field.Type.STRING) {
nonStringFields.add(matchingFieldPath);
} else {
if (field.getValue() != null) {
Field newField = Field.create(maskField(field, fieldMaskConfig));
record.set(matchingFieldPath, newField);
}
}
}
}
}
}
if (nonStringFields.isEmpty()) {
batchMaker.addRecord(record);
} else {
throw new OnRecordErrorException(Errors.MASK_00, StringUtils.join(nonStringFields, ", "), record.getHeader().getSourceId());
}
}
private String maskField(Field field, FieldMaskConfig fieldMaskConfig) {
if(fieldMaskConfig.maskType == MaskType.FIXED_LENGTH) {
return fixedLengthMask();
} else if (fieldMaskConfig.maskType == MaskType.VARIABLE_LENGTH) {
return variableLengthMask(field.getValueAsString());
} else if (fieldMaskConfig.maskType == MaskType.CUSTOM) {
return mask(field.getValueAsString(), fieldMaskConfig.mask);
} else if (fieldMaskConfig.maskType == MaskType.REGEX) {
return regExMask(field, fieldMaskConfig);
}
//Should not happen
return null;
}
@VisibleForTesting
String regExMask(Field field, FieldMaskConfig fieldMaskConfig) {
String value = field.getValueAsString();
Matcher matcher = regExToPatternMap.get(fieldMaskConfig.regex).matcher(value);
if(matcher.matches()) {
int groupCount = matcher.groupCount();
//create a masked string of the same length as the original string
StringBuilder resultString = new StringBuilder();
for(int i = 0; i < value.length(); i++) {
resultString.append(MASK_CHAR);
}
//for each group that needs to be shown, replace the masked string with the original string characters at those
//positions
Set<Integer> groupsToShow = regexToGroupsToShowMap.get(fieldMaskConfig.regex);
if(groupsToShow != null && !groupsToShow.isEmpty()) {
for (int i = 1; i <= groupCount; i++) {
if (groupsToShow.contains(i)) {
resultString.replace(matcher.start(i), matcher.end(i), matcher.group(i));
}
}
}
return resultString.toString();
}
return field.getValueAsString();
}
@VisibleForTesting
String mask(String toMask, String mask) {
int index = 0;
StringBuilder masked = new StringBuilder();
for (int i = 0; i < mask.length() && index < toMask.length(); i++) {
char c = mask.charAt(i);
if (c == NON_MASK_CHAR) {
masked.append(toMask.charAt(index));
index++;
} else {
//We do not care whether it is a MASK_CHAR/something else, we append the character.
masked.append(c);
index++;
}
}
return masked.toString();
}
@VisibleForTesting
String fixedLengthMask() {
return FIXED_LENGTH_MASK;
}
@VisibleForTesting
String variableLengthMask(String toMask) {
StringBuilder masked = new StringBuilder();
for (int i = 0; i < toMask.length(); i++) {
masked.append(MASK_CHAR);
}
return masked.toString();
}
}
| {
"content_hash": "50d4b70bae992eabafdd967187af7ec7",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 130,
"avg_line_length": 37.666666666666664,
"alnum_prop": 0.6689517636794217,
"repo_name": "streamsets/datacollector",
"id": "4708b579705518cee30cd949bd4887fba0a9906e",
"size": "8621",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "basic-lib/src/main/java/com/streamsets/pipeline/stage/processor/fieldmask/FieldMaskProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "101291"
},
{
"name": "CSS",
"bytes": "125357"
},
{
"name": "Groovy",
"bytes": "27033"
},
{
"name": "HTML",
"bytes": "558399"
},
{
"name": "Java",
"bytes": "23349126"
},
{
"name": "JavaScript",
"bytes": "1126994"
},
{
"name": "Python",
"bytes": "26996"
},
{
"name": "Scala",
"bytes": "6646"
},
{
"name": "Shell",
"bytes": "30118"
},
{
"name": "TSQL",
"bytes": "3632"
}
],
"symlink_target": ""
} |
package org.leguan.testproject.language.java;
import java.util.Date;
public class ClassWithMethods {
private String privateMethod() {
return "";
}
public boolean publicMethod (final String param) {
return false;
}
protected Date protectedMethod () {
return null;
}
Object packagePrivateMethod () {
return null;
}
public static String staticMethod () {
return "";
}
}
| {
"content_hash": "847e5a37ec61f3fa08002238694a587a",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 52,
"avg_line_length": 15.923076923076923,
"alnum_prop": 0.6714975845410628,
"repo_name": "moley/leguan",
"id": "2c5951dd02deacdc1d3a2a5e740b08ca2656fad9",
"size": "414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "leguan-testprojects/testprojectJava/src/main/java/org/leguan/testproject/language/java/ClassWithMethods.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20530"
},
{
"name": "HTML",
"bytes": "35444"
},
{
"name": "Java",
"bytes": "2096474"
},
{
"name": "JavaScript",
"bytes": "1240"
},
{
"name": "Shell",
"bytes": "1844"
},
{
"name": "TypeScript",
"bytes": "71940"
}
],
"symlink_target": ""
} |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', ],
[TestAction.create_volume, 'volume1', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume1'],
[TestAction.create_volume, 'volume2', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume2'],
[TestAction.create_volume, 'volume3', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume3'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot1'],
[TestAction.stop_vm, 'vm1'],
[TestAction.use_volume_snapshot, 'vm1-snapshot1'],
[TestAction.start_vm, 'vm1'],
[TestAction.create_data_vol_template_from_volume, 'volume1', 'volume1-image1'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot5'],
[TestAction.create_volume_backup, 'vm1-root', 'vm1-root-backup1'],
[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot9'],
[TestAction.resize_volume, 'vm1', 5*1024*1024],
[TestAction.delete_volume_snapshot, 'volume3-snapshot1'],
[TestAction.create_volume_backup, 'vm1-root', 'vm1-root-backup2'],
[TestAction.delete_vm_snapshot, 'vm1-snapshot1'],
])
'''
The final status:
Running:['vm1']
Stopped:[]
Enadbled:['vm1-snapshot5', 'volume1-snapshot5', 'volume2-snapshot5', 'volume3-snapshot5', 'vm1-snapshot9', 'volume1-snapshot9', 'volume2-snapshot9', 'volume3-snapshot9', 'vm1-root-backup1', 'vm1-root-backup2', 'volume1-image1']
attached:['volume1', 'volume2', 'volume3']
Detached:[]
Deleted:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1']
Expunged:[]
Ha:[]
Group:
vm_snap2:['vm1-snapshot5', 'volume1-snapshot5', 'volume2-snapshot5', 'volume3-snapshot5']---vm1volume1_volume2_volume3
vm_snap3:['vm1-snapshot9', 'volume1-snapshot9', 'volume2-snapshot9', 'volume3-snapshot9']---vm1volume1_volume2_volume3
'''
| {
"content_hash": "b9c912b62ff755b8f991e3a3f0e09aa0",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 227,
"avg_line_length": 44.04651162790697,
"alnum_prop": 0.7117212249208026,
"repo_name": "zstackio/zstack-woodpecker",
"id": "053d9b2de409354d9cf4cf0e638817587135fc51",
"size": "1894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "integrationtest/vm/multihosts/vm_snapshots/paths/local_path50.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2356"
},
{
"name": "Go",
"bytes": "49822"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Puppet",
"bytes": "875"
},
{
"name": "Python",
"bytes": "13070596"
},
{
"name": "Shell",
"bytes": "177861"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.aezo.springboot.druid</groupId>
<artifactId>db-druid</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>db-druid</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.4.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.4.RELEASE</version>
<configuration>
<mainClass>cn.aezo.springboot.druid.dbdruid.DbDruidApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "73c52445359a1c84f77f1cf53ad1a217",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 109,
"avg_line_length": 36.16981132075472,
"alnum_prop": 0.5414710485133021,
"repo_name": "oldinaction/springboot",
"id": "1727ab9ec2aafe555c7dfeab449792fa78ae06ed",
"size": "3834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db-druid/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "627"
},
{
"name": "HTML",
"bytes": "25734"
},
{
"name": "Inno Setup",
"bytes": "2049"
},
{
"name": "Java",
"bytes": "296818"
},
{
"name": "JavaScript",
"bytes": "78"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="135"
android:endColor="@color/Blue"
android:startColor="@color/DarkBlue"
android:type="linear" />
<padding
android:top="5dp"
android:right="5dp"
android:left="5dp"
android:bottom="5dp" />
<corners
android:bottomRightRadius="45dip"
android:bottomLeftRadius="45dip"
android:topRightRadius="45dip"
android:topLeftRadius="45dip" />
</shape> | {
"content_hash": "adb1917a7e0cae1bd3d99cc92a7ebf7e",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 65,
"avg_line_length": 28.904761904761905,
"alnum_prop": 0.6177924217462932,
"repo_name": "wmhameed/Yahala-Messenger",
"id": "6af0cf44789615868688f747ac725be3e83fde3c",
"size": "607",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/round_button_send.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "30594"
},
{
"name": "C",
"bytes": "3526101"
},
{
"name": "C++",
"bytes": "260854"
},
{
"name": "HTML",
"bytes": "338"
},
{
"name": "Java",
"bytes": "3537235"
},
{
"name": "Makefile",
"bytes": "6481"
},
{
"name": "Objective-C",
"bytes": "95275"
},
{
"name": "Perl",
"bytes": "8945"
}
],
"symlink_target": ""
} |
FROM lyft/envoy:latest
ARG enable_ratings
ARG star_color
ENV ENABLE_RATINGS ${enable_ratings:-false}
ENV STAR_COLOR ${star_color:-black}
RUN mkdir /opt/microservices
ADD ./reviews /opt/microservices
ADD ./start_service.sh /usr/local/bin/start_service.sh
RUN chmod u+x /usr/local/bin/start_service.sh
ENTRYPOINT /usr/local/bin/start_service.sh
| {
"content_hash": "97c0381021a1ac6a6eec15b7f68ccf1e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 54,
"avg_line_length": 28.75,
"alnum_prop": 0.7797101449275362,
"repo_name": "kimikowang/istio_vms",
"id": "04ed8e9bbe31cdf9e379935bdcfdd57b1c360bd2",
"size": "345",
"binary": false,
"copies": "1",
"ref": "refs/heads/k8s_client_go",
"path": "registry/client/test/platform/vms/test/cf/bookinfo/apps/reviews/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "1265719"
},
{
"name": "HTML",
"bytes": "17657"
},
{
"name": "Makefile",
"bytes": "17705"
},
{
"name": "Python",
"bytes": "4912"
},
{
"name": "Ruby",
"bytes": "3748"
},
{
"name": "Shell",
"bytes": "99583"
}
],
"symlink_target": ""
} |
"""Algorithms for Privacy-Preserving Machine Learning in JAX."""
from jax_privacy.src import accounting
from jax_privacy.src import training
| {
"content_hash": "32a1319239c3869c1cc66996b7113ac3",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 64,
"avg_line_length": 35.5,
"alnum_prop": 0.8028169014084507,
"repo_name": "deepmind/jax_privacy",
"id": "e77b098ede75f1bffea876c9a62192aef9fe8845",
"size": "752",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "jax_privacy/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "210177"
},
{
"name": "Shell",
"bytes": "2187"
},
{
"name": "TeX",
"bytes": "279"
}
],
"symlink_target": ""
} |
package example.sos.messaging.orders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.hypermedia.DiscoveredResource;
import org.springframework.cloud.client.hypermedia.RemoteResource;
import org.springframework.context.annotation.Bean;
/**
* @author Oliver Gierke
*/
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
RemoteResource productResource() {
ServiceInstance service = new DefaultServiceInstance("stores", "localhost", 6060, false);
return new DiscoveredResource(() -> service, traverson -> traverson.follow("product"));
}
}
| {
"content_hash": "761e909fc4e15003f5bc21122faa0879",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 91,
"avg_line_length": 30.82758620689655,
"alnum_prop": 0.8087248322147651,
"repo_name": "olivergierke/sos",
"id": "5639fe71eb1b4e33b0ec2d46cc2602210546ba63",
"size": "1509",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "30-messaging-sos/sos-messaging-orders/src/main/java/example/sos/messaging/orders/OrderApplication.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "157211"
}
],
"symlink_target": ""
} |
<?php
/**
* FormGeneratorTest form.
*
* @package form
* @subpackage FormGeneratorTest
* @version SVN: $Id: FormGeneratorTestForm.class.php 23810 2010-11-12 11:07:44Z Kris.Wallsmith $
*/
class FormGeneratorTestForm extends BaseFormGeneratorTestForm
{
public function configure()
{
}
} | {
"content_hash": "97f0cc2548185fdb558de37567a35bce",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 100,
"avg_line_length": 20.133333333333333,
"alnum_prop": 0.7185430463576159,
"repo_name": "italinux/Authentication",
"id": "fac41ffbf71d6c55497c15882da201abd9aba071",
"size": "302",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/test/functional/fixtures/lib/form/doctrine/FormGeneratorTestForm.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "721"
},
{
"name": "PHP",
"bytes": "219653"
}
],
"symlink_target": ""
} |
/* This function controls the cursor movement for placing ships,
* and returns the selected location.
* It has its own function so that it can account for the size and
* orientation of the ships that are being placed.
*/
#include "lcd_image.h"
#include "Images.h"
#ifndef __CURSOR__H
#define __CURSOR__H
// Joystick pins:
#define VERT 0 // Analog input A0 - vertical
#define HORIZ 1 // Analog input A1 - horizontal
#define SEL 9 // Digital input pin 9 for the joystick button
#define Button1 3 // Digital input pin 3 for the button
void Initialize_Cursor();
extern Adafruit_ST7735 tft;
extern lcd_image_t Images[];
void HorizontalRedraw(int size, int8_t* Array, int loc);
void VerticalRedraw(int size, int8_t* Array, int loc);
int Cursor(int size, bool* Orientation, int8_t* Array);
#define unit 12 // This is because one block on board is going to be
// 12x12 pixels
#endif
| {
"content_hash": "affe5bb9579c14f9c8ad6fd2747ba285",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 69,
"avg_line_length": 29.483870967741936,
"alnum_prop": 0.7100656455142232,
"repo_name": "DLukeNelson/Arduino-Battleship",
"id": "999bd8016fd79a985bb705a33c32dcd3a471f758",
"size": "914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Arduino-Battleship/Cursor.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2823"
},
{
"name": "C++",
"bytes": "40920"
},
{
"name": "Makefile",
"bytes": "1093"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace Mono.Debugging.Client
{
public class UsageCounter
{
readonly Dictionary<string, int> stats = new Dictionary<string, int> ();
public UsageCounter ()
{
}
public bool HasUsageStats {
get { return stats.Count > 0; }
}
public void IncrementUsage (string action)
{
stats.TryGetValue (action, out var value);
stats[action] = value + 1;
}
public void Serialize (Dictionary<string, object> metadata)
{
foreach (var kvp in stats)
metadata[kvp.Key] = kvp.Value;
}
}
}
| {
"content_hash": "ee9d9bb7fe64e9bafaabd5099db28475",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 74,
"avg_line_length": 18.93103448275862,
"alnum_prop": 0.6775956284153005,
"repo_name": "Unity-Technologies/debugger-libs",
"id": "b469ddf15dfb97584120dda07969ba1a13f71fb9",
"size": "1753",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Mono.Debugging/Mono.Debugging.Client/UsageCounter.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2170970"
},
{
"name": "Makefile",
"bytes": "173"
},
{
"name": "Shell",
"bytes": "319"
}
],
"symlink_target": ""
} |
package main
import (
"bytes"
"fmt"
"net"
"sync/atomic"
"github.com/uber-go/tally/v4/m3"
customtransport "github.com/uber-go/tally/v4/m3/customtransports"
m3thrift "github.com/uber-go/tally/v4/m3/thrift/v1"
"github.com/uber-go/tally/v4/thirdparty/github.com/apache/thrift/lib/go/thrift"
)
type batchCallback func(batch *m3thrift.MetricBatch)
type localM3Server struct {
Service *localM3Service
Addr string
protocol m3.Protocol
processor thrift.TProcessor
conn *net.UDPConn
closed int32
}
func newLocalM3Server(
listenAddr string,
protocol m3.Protocol,
fn batchCallback,
) (*localM3Server, error) {
udpAddr, err := net.ResolveUDPAddr("udp", listenAddr)
if err != nil {
return nil, err
}
service := newLocalM3Service(fn)
processor := m3thrift.NewM3Processor(service)
conn, err := net.ListenUDP(udpAddr.Network(), udpAddr)
if err != nil {
return nil, err
}
return &localM3Server{
Service: service,
Addr: conn.LocalAddr().String(),
conn: conn,
protocol: protocol,
processor: processor,
}, nil
}
func (f *localM3Server) Serve() error {
readBuf := make([]byte, 65536)
for {
n, err := f.conn.Read(readBuf)
if err != nil {
if atomic.LoadInt32(&f.closed) == 0 {
return fmt.Errorf("failed to read: %v", err)
}
return nil
}
trans, _ := customtransport.NewTBufferedReadTransport(bytes.NewBuffer(readBuf[0:n]))
var proto thrift.TProtocol
if f.protocol == m3.Compact {
proto = thrift.NewTCompactProtocol(trans)
} else {
proto = thrift.NewTBinaryProtocolTransport(trans)
}
if _, err = f.processor.Process(proto, proto); err != nil {
fmt.Println("Error processing thrift metric:", err)
}
}
}
func (f *localM3Server) Close() error {
atomic.AddInt32(&f.closed, 1)
return f.conn.Close()
}
type localM3Service struct {
fn batchCallback
}
func newLocalM3Service(fn batchCallback) *localM3Service {
return &localM3Service{fn: fn}
}
func (m *localM3Service) EmitMetricBatch(batch *m3thrift.MetricBatch) (err error) {
m.fn(batch)
return thrift.NewTTransportException(thrift.END_OF_FILE, "complete")
}
| {
"content_hash": "59a7717ef7df689c226827d30a420ede",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 86,
"avg_line_length": 22.945652173913043,
"alnum_prop": 0.7034580767408811,
"repo_name": "uber-go/tally",
"id": "e7571e997c7ac9da322bdfdf0a6e42e9018257a0",
"size": "3233",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "m3/example/local_server.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "323202"
},
{
"name": "Makefile",
"bytes": "3260"
},
{
"name": "Shell",
"bytes": "292"
},
{
"name": "Thrift",
"bytes": "1792"
}
],
"symlink_target": ""
} |
brew update
brew install node
if test ! $(which spoof)
then
sudo npm install spoof -g
fi
| {
"content_hash": "001163c07f7bb8a1c1d04cea113cc63f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 27,
"avg_line_length": 15.166666666666666,
"alnum_prop": 0.7362637362637363,
"repo_name": "evanriley/dotfiles",
"id": "a79127c78e4f96e47f4c7ba00d36d458f956e9a9",
"size": "91",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node/install.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "1932"
},
{
"name": "CoffeeScript",
"bytes": "78"
},
{
"name": "Emacs Lisp",
"bytes": "13618"
},
{
"name": "Ruby",
"bytes": "18054"
},
{
"name": "Shell",
"bytes": "24566"
},
{
"name": "Vim script",
"bytes": "54900"
}
],
"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("T14.4.SubstrCount")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("T14.4.SubstrCount")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("99f6f629-7fc5-408e-aa79-26c4ce928440")]
// 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": "1861b2d93d7b9bcf9979dd9239d30ac2",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.083333333333336,
"alnum_prop": 0.744136460554371,
"repo_name": "studware/Ange-Git",
"id": "8058d64f3f82af67ba3b46cdd4801bd1d3b806f4",
"size": "1410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MyTelerikAcademyHomeWorks/CSharp1/HW14.StringsAndTextProcessing/T14.4.SubstrCount/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1833657"
},
{
"name": "CSS",
"bytes": "52022"
},
{
"name": "HTML",
"bytes": "48849"
},
{
"name": "JavaScript",
"bytes": "6247"
},
{
"name": "PLSQL",
"bytes": "6610"
},
{
"name": "PowerShell",
"bytes": "332"
},
{
"name": "XSLT",
"bytes": "2371"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.lambda.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.lambda.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.SdkHttpUtils;
import com.amazonaws.protocol.json.*;
/**
* CreateEventSourceMappingRequest Marshaller
*/
public class CreateEventSourceMappingRequestMarshaller
implements
Marshaller<Request<CreateEventSourceMappingRequest>, CreateEventSourceMappingRequest> {
private static final String DEFAULT_CONTENT_TYPE = "application/x-amz-json-1.1";
private final SdkJsonProtocolFactory protocolFactory;
public CreateEventSourceMappingRequestMarshaller(
SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<CreateEventSourceMappingRequest> marshall(
CreateEventSourceMappingRequest createEventSourceMappingRequest) {
if (createEventSourceMappingRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<CreateEventSourceMappingRequest> request = new DefaultRequest<CreateEventSourceMappingRequest>(
createEventSourceMappingRequest, "AWSLambda");
request.setHttpMethod(HttpMethodName.POST);
String uriResourcePath = "/2015-03-31/event-source-mappings/";
request.setResourcePath(uriResourcePath);
try {
final StructuredJsonGenerator jsonGenerator = protocolFactory
.createGenerator();
jsonGenerator.writeStartObject();
if (createEventSourceMappingRequest.getEventSourceArn() != null) {
jsonGenerator.writeFieldName("EventSourceArn").writeValue(
createEventSourceMappingRequest.getEventSourceArn());
}
if (createEventSourceMappingRequest.getFunctionName() != null) {
jsonGenerator.writeFieldName("FunctionName").writeValue(
createEventSourceMappingRequest.getFunctionName());
}
if (createEventSourceMappingRequest.getEnabled() != null) {
jsonGenerator.writeFieldName("Enabled").writeValue(
createEventSourceMappingRequest.getEnabled());
}
if (createEventSourceMappingRequest.getBatchSize() != null) {
jsonGenerator.writeFieldName("BatchSize").writeValue(
createEventSourceMappingRequest.getBatchSize());
}
if (createEventSourceMappingRequest.getStartingPosition() != null) {
jsonGenerator.writeFieldName("StartingPosition").writeValue(
createEventSourceMappingRequest.getStartingPosition());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
if (!request.getHeaders().containsKey("Content-Type")) {
request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
}
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| {
"content_hash": "b90d0b12676d4936752832fdcf36baf3",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 111,
"avg_line_length": 38.83177570093458,
"alnum_prop": 0.6876052948255115,
"repo_name": "flofreud/aws-sdk-java",
"id": "ec9322059dc630f08496dd2a566546afc9259f5d",
"size": "4742",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/transform/CreateEventSourceMappingRequestMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "126417"
},
{
"name": "Java",
"bytes": "113826096"
},
{
"name": "Scilab",
"bytes": "3561"
}
],
"symlink_target": ""
} |
package io.luna.game.model.mob;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Range;
import io.luna.Luna;
import io.luna.game.event.impl.SkillChangeEvent;
import io.luna.game.plugin.PluginManager;
import java.util.function.Function;
import java.util.stream.IntStream;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A model representing a skill within a skill set.
*
* @author lare96 <http://github.org/lare96>
*/
public final class Skill {
/**
* An immutable list of the names of all skills.
*/
public static final ImmutableList<String> NAMES = ImmutableList.of(
"Attack", "Defence", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic",
"Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing",
"Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting"
);
/**
* The combat skill identifiers.
*/
public static final Range<Integer> COMBAT_IDS = Range.closed(0, 6);
/**
* An immutable map of names to identifiers.
*/
public static final ImmutableMap<String, Integer> NAME_TO_ID;
/**
* The Attack identifier.
*/
public static final int ATTACK = 0;
/**
* The Defence identifier.
*/
public static final int DEFENCE = 1;
/**
* The Strength identifier.
*/
public static final int STRENGTH = 2;
/**
* The Hitpoints identifier.
*/
public static final int HITPOINTS = 3;
/**
* The Ranged identifier.
*/
public static final int RANGED = 4;
/**
* The Prayer identifier.
*/
public static final int PRAYER = 5;
/**
* The Magic identifier.
*/
public static final int MAGIC = 6;
/**
* The Cooking identifier.
*/
public static final int COOKING = 7;
/**
* The Woodcutting identifier.
*/
public static final int WOODCUTTING = 8;
/**
* The Fletching identifier.
*/
public static final int FLETCHING = 9;
/**
* The Fishing identifier.
*/
public static final int FISHING = 10;
/**
* The Firemaking identifier.
*/
public static final int FIREMAKING = 11;
/**
* The Crafting identifier.
*/
public static final int CRAFTING = 12;
/**
* The Smithing identifier.
*/
public static final int SMITHING = 13;
/**
* The Mining identifier.
*/
public static final int MINING = 14;
/**
* The Herblore identifier.
*/
public static final int HERBLORE = 15;
/**
* The Agility identifier.
*/
public static final int AGILITY = 16;
/**
* The Thieving identifier.
*/
public static final int THIEVING = 17;
/**
* The Slayer identifier.
*/
public static final int SLAYER = 18;
/**
* The Farming identifier.
*/
public static final int FARMING = 19;
/**
* The Runecrafting identifier.
*/
public static final int RUNECRAFTING = 20;
/**
* Retrieves the name of a skill by its identifier.
*
* @param id The identifier.
* @return The skill name.
*/
public static String getName(int id) {
return NAMES.get(id);
}
/**
* Retrieves the identifier of a skill by its name.
*
* @param name The skill name.
* @return The identifier.
*/
public static int getId(String name) {
return NAME_TO_ID.get(name);
}
/**
* Determines if a skill is a factor in combat level calculations.
*
* @param id The skill identifier.
* @return {@code true} if the identifier is a combat skill.
*/
public static boolean isCombatSkill(int id) {
return COMBAT_IDS.contains(id);
}
static {
// Build and set [name -> identifier] cache.
NAME_TO_ID = IntStream.range(0, NAMES.size()).boxed()
.collect(ImmutableMap.toImmutableMap(NAMES::get, Function.identity()));
}
/**
* The skill set.
*/
private transient final SkillSet set;
/**
* The skill identifier.
*/
private transient final int id;
/**
* The static (experience based) skill level. Cached to avoid potentially expensive {@link SkillSet#levelForExperience(int)} calls.
*/
private transient int staticLevel = -1;
/**
* The dynamic skill level.
*/
private int level = 1;
/**
* The attained experience.
*/
private double experience;
/**
* Creates a new {@link Skill}.
*
* @param id The skill identifier.
* @param set The skill set.
*/
public Skill(int id, SkillSet set) {
this.id = id;
this.set = set;
if (id == HITPOINTS) {
level = 10;
experience = 1300;
}
}
@Override
public String toString() {
return getName();
}
/**
* Restores depleted or buffed skills.
*/
private void restoreSkills() {
if (!set.isRestoring()) {
if (level != staticLevel) {
var world = set.getMob().getWorld();
world.schedule(new SkillRestorationTask(set));
}
}
}
/**
* Adds experience to this skill.
*
* @param amount The amount of experience to add.
*/
public void addExperience(double amount) {
checkArgument(amount > 0, "amount <= 0");
amount = amount * Luna.settings().experienceMultiplier();
setExperience(experience + amount);
}
/**
* Notifies plugins of any level or experience changes.
*
* @param oldExperience The old experience amount.
* @param oldStaticLevel The old static level.
* @param oldLevel The old dynamic level.
*/
private void notifyListeners(double oldExperience, int oldStaticLevel, int oldLevel) {
if (set.isFiringEvents()) {
Mob mob = set.getMob();
PluginManager plugins = mob.getPlugins();
plugins.post(new SkillChangeEvent(mob, oldExperience, oldStaticLevel, oldLevel, id));
}
}
/**
* @return The name of this skill.
*/
public String getName() {
return NAMES.get(id);
}
/**
* @return The skill identifier.
*/
public int getId() {
return id;
}
/**
* @return The static (experience based) skill level.
*/
public int getStaticLevel() {
if (staticLevel == -1) {
// The value hasn't been computed yet, do it now.
staticLevel = SkillSet.levelForExperience((int) experience);
}
return staticLevel;
}
/**
* @return The dynamic skill level.
*/
public int getLevel() {
return level;
}
/**
* Sets the dynamic skill level.
*
* @param newLevel The new level.
*/
public void setLevel(int newLevel) {
if (newLevel < 0) {
newLevel = 0;
}
int oldLevel = level;
level = newLevel;
if (oldLevel == level) {
return;
}
restoreSkills();
notifyListeners(experience, getStaticLevel(), oldLevel);
}
/**
* Increases the dynamic skill level by {@code amount}.
*
* @param amount The amount to increase by.
* @param exceedStaticLevel If the bound should be set higher than the static level, or at the
* static level.
*/
public void addLevels(int amount, boolean exceedStaticLevel) {
int bound = exceedStaticLevel ? getStaticLevel() + amount : getStaticLevel();
int newAmount = getLevel() + amount;
newAmount = Math.min(newAmount, bound);
setLevel(newAmount);
}
/**
* Decreases the dynamic skill level by {@code amount}.
*/
public void removeLevels(int amount) {
int newAmount = getLevel() - amount;
newAmount = Math.max(newAmount, 0);
setLevel(newAmount);
}
/**
* @return The attained experience.
*/
public double getExperience() {
return experience;
}
/**
* Sets the attained experience.
*
* @param newExperience The new experience value.
*/
public void setExperience(double newExperience) {
if (newExperience < 0) {
newExperience = 0;
} else if (newExperience > SkillSet.MAXIMUM_EXPERIENCE) {
newExperience = SkillSet.MAXIMUM_EXPERIENCE;
}
if (experience == newExperience) {
return;
}
int oldStaticLevel = getStaticLevel();
double oldExperience = experience;
experience = newExperience;
staticLevel = -1;
notifyListeners(oldExperience, oldStaticLevel, level);
}
}
| {
"content_hash": "20b08fa6c647366798ace73fdd189802",
"timestamp": "",
"source": "github",
"line_count": 369,
"max_line_length": 135,
"avg_line_length": 24.11111111111111,
"alnum_prop": 0.5785096099808924,
"repo_name": "lare96/luna",
"id": "a57536613910aacd3360d8c76a6405c5d268ef50",
"size": "8897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/luna/game/model/mob/Skill.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "129"
},
{
"name": "Java",
"bytes": "651745"
},
{
"name": "Scala",
"bytes": "84292"
}
],
"symlink_target": ""
} |
module Azure::Web::Mgmt::V2015_08_01
module Models
#
# SSL-enabled hostname.
#
class HostNameSslState
include MsRestAzure
# @return [String] Hostname.
attr_accessor :name
# @return [SslState] SSL type. Possible values include: 'Disabled',
# 'SniEnabled', 'IpBasedEnabled'
attr_accessor :ssl_state
# @return [String] Virtual IP address assigned to the hostname if IP
# based SSL is enabled.
attr_accessor :virtual_ip
# @return [String] SSL certificate thumbprint.
attr_accessor :thumbprint
# @return [Boolean] Set to <code>true</code> to update existing hostname.
attr_accessor :to_update
# @return [HostType] Indicates whether the hostname is a standard or
# repository hostname. Possible values include: 'Standard', 'Repository'
attr_accessor :host_type
#
# Mapper for HostNameSslState class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'HostNameSslState',
type: {
name: 'Composite',
class_name: 'HostNameSslState',
model_properties: {
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
ssl_state: {
client_side_validation: true,
required: false,
serialized_name: 'sslState',
type: {
name: 'Enum',
module: 'SslState'
}
},
virtual_ip: {
client_side_validation: true,
required: false,
serialized_name: 'virtualIP',
type: {
name: 'String'
}
},
thumbprint: {
client_side_validation: true,
required: false,
serialized_name: 'thumbprint',
type: {
name: 'String'
}
},
to_update: {
client_side_validation: true,
required: false,
serialized_name: 'toUpdate',
type: {
name: 'Boolean'
}
},
host_type: {
client_side_validation: true,
required: false,
serialized_name: 'hostType',
type: {
name: 'Enum',
module: 'HostType'
}
}
}
}
}
end
end
end
end
| {
"content_hash": "8abee9cf8ecc52190636025f6682f765",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 79,
"avg_line_length": 28.455445544554454,
"alnum_prop": 0.4603340292275574,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "13278f450306880db426a19b94b622e9f59c2f4f",
"size": "3038",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_web/lib/2015-08-01/generated/azure_mgmt_web/models/host_name_ssl_state.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
package com.lightbend.lagom.internal.testkit
import akka.Done
import akka.actor.ActorRef
import akka.stream.Materializer
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Keep
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source
import scala.concurrent.Future
import scala.language.higherKinds
private[lagom] class InternalSubscriberStub[Payload, Message[_]](
groupId: String,
topicBuffer: ActorRef
)(implicit materializer: Materializer) {
def mostOnceSource: Source[Message[Payload], _] = {
Source
.actorRef[Message[Payload]](1024, OverflowStrategy.fail)
.prependMat(Source.empty)(subscribeToBuffer)
}
def leastOnce(flow: Flow[Message[Payload], Done, _]): Future[Done] = {
mostOnceSource
.via(flow)
.toMat(Sink.ignore)(Keep.right[Any, Future[Done]])
.run()
}
private def subscribeToBuffer[R](ref: ActorRef, t: R) = {
topicBuffer.tell(TopicBufferActor.SubscribeToBuffer(groupId, ref), ActorRef.noSender)
t
}
}
| {
"content_hash": "3663370aad7080d5f6ada15430e348f9",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 89,
"avg_line_length": 26.82051282051282,
"alnum_prop": 0.7418738049713193,
"repo_name": "TimMoore/lagom",
"id": "89329953b81278b05c75eb5017e5c096c65f2005",
"size": "1122",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "testkit/core/src/main/scala/com/lightbend/lagom/internal/testkit/InternalSubscriberStub.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "348"
},
{
"name": "HTML",
"bytes": "559"
},
{
"name": "Java",
"bytes": "914966"
},
{
"name": "JavaScript",
"bytes": "48"
},
{
"name": "Perl",
"bytes": "1102"
},
{
"name": "Roff",
"bytes": "6976"
},
{
"name": "Scala",
"bytes": "1907646"
},
{
"name": "Shell",
"bytes": "8127"
}
],
"symlink_target": ""
} |
var S3FS = require('s3fs')
var crypto = require('crypto')
function S3Storage (opts) {
if (!opts.bucket) throw new Error('bucket is required')
if (!opts.secretAccessKey) throw new Error('secretAccessKey is required')
if (!opts.accessKeyId) throw new Error('accessKeyId is required')
if (!opts.region) throw new Error('region is required')
if (!opts.dirname) throw new Error('dirname is required')
this.options = opts
this.s3fs = new S3FS(opts.bucket, opts)
}
S3Storage.prototype._handleFile = function (req, file, cb) {
var fileName = file.originalname.slice(0, -4) + file.originalname.slice(-4);
// var fileName = crypto.randomBytes(20).toString('hex')
var filePath = this.options.dirname + '/' + fileName
var outStream = this.s3fs.createWriteStream(filePath)
file.stream.pipe(outStream)
outStream.on('error', cb)
outStream.on('finish', function () {
cb(null, { size: outStream.bytesWritten, key: filePath })
})
}
S3Storage.prototype._removeFile = function (req, file, cb) {
this.s3fs.unlink(file.key, cb)
}
module.exports = function (opts) {
return new S3Storage(opts)
}
| {
"content_hash": "ead4efe160f9c451abdcbb28d7a83e50",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 78,
"avg_line_length": 31.914285714285715,
"alnum_prop": 0.7045658012533572,
"repo_name": "jasonleibowitz/dreambear-caption-creator",
"id": "6efe2d47f46616a29487e2d075990e15546dbb82",
"size": "1117",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/multer-s3/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4202"
}
],
"symlink_target": ""
} |
<div class="page-header">
<h1>
Code Samples
</h1>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Most of the projects I've worked on over the past few years can be seen at my <a href="http://github.com/waldenraines">Github Account</a> as everything I've been doing is open source.
What follows are some basic code samples of fun stuff I've been playing with recently.
</p>
<p>
More to come soon.
</p>
<ul class="nav nav-tabs">
<li role="presentation" ui-sref-active="active">
<a href="#" ui-sref="code.websocket">WebSocket</a>
</li>
</ul>
<div ui-view></div>
</div>
</div>
| {
"content_hash": "30926c386c4123bbe0ee461502d5cc2a",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 189,
"avg_line_length": 24.51851851851852,
"alnum_prop": 0.6027190332326284,
"repo_name": "waldenraines/waldenrainesdotcom",
"id": "fefc3d333e560b86d5911173b48a43cbc15038df",
"size": "662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/code/views/code.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "1174"
},
{
"name": "HTML",
"bytes": "24403"
},
{
"name": "JavaScript",
"bytes": "29625"
}
],
"symlink_target": ""
} |
package com.twitter.finagle.netty4.http.handler
import com.twitter.finagle.netty4.http.FinagleHttpObjectAggregator
import com.twitter.util.StorageUnit
import io.netty.handler.codec.http._
/**
* Aggregates fixed length http messages and emits [[FullHttpMessage]] downstream.
*
* Http message is considered fixed length if it has `Content-Length` header and
* `Transfer-Encoding` header is not `chunked` or if we can deduce actual content
* length to be 0 even if `Content-Length` header is not specified.
*
* Fixed length messages may arrive as a series of chunks (not to be confused with chunks
* as in `Transfer-Encoding: chunked`) from the upstream handlers in pipeline. To
* eventually build a [[com.twitter.finagle.http.Request]] object with content available
* as [[com.twitter.finagle.http.Request.content]] or
* [[com.twitter.finagle.http.Request.contentString]] all chunks must be stored in a
* temporary buffer and combined together into a [[FullHttpMessage]] as soon as the last
* chunk of the message is received.
*
* The `maxContentLength` determines when to aggregate chunks and when to bypass the
* message as is. Only sufficiently small messages (smaller than `maxContentLength`) are
* aggregated.
*
* Messages with `Transfer-Encoding: chunked` are always bypassed.
*/
private[http] class FixedLengthMessageAggregator(
maxContentLength: StorageUnit,
handleExpectContinue: Boolean = true)
extends FinagleHttpObjectAggregator(maxContentLength.inBytes.toInt, handleExpectContinue) {
require(maxContentLength.bytes >= 0)
override def isStartMessage(msg: HttpObject): Boolean = msg match {
case httpMsg: HttpMessage => shouldAggregate(httpMsg)
case _ => false
}
private[this] def shouldAggregate(msg: HttpMessage): Boolean = {
// We never dechunk 'Transfer-Encoding: chunked' messages
if (HttpUtil.isTransferEncodingChunked(msg)) false
else if (noContentResponse(msg)) true // No body so aggregate the LastHttpContent
else {
// We will dechunk a message if it has a content-length header that is less
// than or equal to the maxContentLength parameter.
val contentLength = HttpUtil.getContentLength(msg, -1L)
if (contentLength != -1L) contentLength <= maxContentLength.bytes
else { // No content-length header.
// Requests without a transfer-encoding or content-length header cannot have a body
// (see https://tools.ietf.org/html/rfc7230#section-3.3.3). Netty 4 will signal
// end-of-message for these requests with an immediate follow up LastHttpContent, so
// we aggregate it as to not end up with a chunked request and a Reader that will
// only signal EOF that folks are probably not handling anyway.
msg.isInstanceOf[HttpRequest]
}
}
}
private[this] def noContentResponse(msg: HttpMessage): Boolean = msg match {
case res: HttpResponse =>
res.status.code match {
case 101 =>
// The Hixie 76 websocket handshake response may have content
!((res.headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT)) &&
(res.headers.contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true)))
case code if code >= 100 && code < 200 => true
case 204 | 205 | 304 => true
case _ => false
}
case _ => false
}
}
| {
"content_hash": "b00006bd31c0f107a68125d10cd13952",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 95,
"avg_line_length": 44.25,
"alnum_prop": 0.7190008920606601,
"repo_name": "twitter/finagle",
"id": "0b9293c382af7d40817d541a2130cd2dd8b46257",
"size": "3363",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "finagle-netty4-http/src/main/scala/com/twitter/finagle/netty4/http/handler/FixedLengthMessageAggregator.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "6399"
},
{
"name": "Java",
"bytes": "246551"
},
{
"name": "Lua",
"bytes": "15246"
},
{
"name": "R",
"bytes": "4245"
},
{
"name": "Ruby",
"bytes": "25330"
},
{
"name": "Scala",
"bytes": "7880569"
},
{
"name": "Shell",
"bytes": "6056"
},
{
"name": "Starlark",
"bytes": "83521"
},
{
"name": "Thrift",
"bytes": "20340"
}
],
"symlink_target": ""
} |
"""
A set of request processors that return dictionaries to be merged into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.
These are referenced from the 'context_processors' option of the configuration
of a DjangoTemplates backend and used by RequestContext.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.middleware.csrf import get_token
from django.utils.encoding import smart_text
from django.utils.functional import SimpleLazyObject, lazy
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
return {'csrf_token': SimpleLazyObject(_get_val)}
def debug(request):
"""
Returns context variables helpful for debugging.
"""
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connection
# Return a lazy reference that computes connection.queries on access,
# to ensure it contains queries triggered after this function runs.
context_extras['sql_queries'] = lazy(lambda: connection.queries, list)
return context_extras
def i18n(request):
from django.utils import translation
return {
'LANGUAGES': settings.LANGUAGES,
'LANGUAGE_CODE': translation.get_language(),
'LANGUAGE_BIDI': translation.get_language_bidi(),
}
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def static(request):
"""
Adds static-related context variables to the context.
"""
return {'STATIC_URL': settings.STATIC_URL}
def media(request):
"""
Adds media-related context variables to the context.
"""
return {'MEDIA_URL': settings.MEDIA_URL}
def request(request):
return {'request': request}
| {
"content_hash": "fda25e450fa3ffdeb48af93d6234d32e",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 83,
"avg_line_length": 31.29113924050633,
"alnum_prop": 0.6678802588996764,
"repo_name": "yephper/django",
"id": "2ef4c1b8e6be820373191f514902c00859fad89c",
"size": "2472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "django/template/context_processors.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "1538"
},
{
"name": "CSS",
"bytes": "1697381"
},
{
"name": "HTML",
"bytes": "390772"
},
{
"name": "Java",
"bytes": "588"
},
{
"name": "JavaScript",
"bytes": "3172126"
},
{
"name": "Makefile",
"bytes": "134"
},
{
"name": "PHP",
"bytes": "19336"
},
{
"name": "Python",
"bytes": "13365273"
},
{
"name": "Shell",
"bytes": "837"
},
{
"name": "Smarty",
"bytes": "133"
}
],
"symlink_target": ""
} |
(function() {
'use strict';
angular
.module('module')
.directive('testDirective', testDirective);
testDirective.$inject = ['$rootScope'];
/* @ngInject */
function testDirective($rootScope) {
// Usage:
//
// Creates:
//
var directive = {
bindToController: true,
controller: TestController,
controllerAs: 'vm',
link: link,
restrict: 'A',
scope: {}
};
return directive;
function link(scope, element, attrs, controller) {
}
}
TestController.$inject = ['$rootScope'];
/* @ngInject */
function TestController($rootScope) {}
})(); | {
"content_hash": "c9e9cfce04b8afe6d9de460a81aa3fcc",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 58,
"avg_line_length": 20.742857142857144,
"alnum_prop": 0.5,
"repo_name": "siddharthJadhav/Library-management-system",
"id": "94a522f41b1593c2a2fcb853f64205e394403fdd",
"size": "726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/modules/login/login-profile.directive.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "898005"
},
{
"name": "HTML",
"bytes": "87128"
},
{
"name": "JavaScript",
"bytes": "162438"
}
],
"symlink_target": ""
} |
namespace MPIfR {
namespace LOFAR {
namespace Station {
//_CLASS LOFAR_Station_Beamformed_Writer_FFT0
class LOFAR_Station_Beamformed_Writer_FFT0 :
public LOFAR_Station_Beamformed_Writer_Base {
//_DESC full description of class
//_FILE files used and logical units used
//_LIMS design limitations
//_BUGS known bugs
//_CALL list of calls
//_KEYS
//_HIST DATE NAME PLACE INFO
//_END
// NAMESPACE ISSUES
public:
LOFAR_Station_Beamformed_Writer_FFT0(const char* const restrict filename_base_,
const char* const restrict station_name_,
const uint32_t reference_time_,
const uint_fast16_t CLOCK_SPEED_IN_MHz_,
const uint_fast32_t PHYSICAL_BEAMLET_OFFSET_,
const uint_fast16_t NUM_Beamlets_,
const uint_fast16_t NUM_Blocks_,
const LOFAR_raw_data_type_enum DATA_TYPE_,
const int32_t id_,
const uint_fast32_t NUM_OUTPUT_CHANNELS_,
const uint_fast16_t NUM_Output_Beamlets_,
const uint_fast32_t* const restrict Physical_Beamlets_Array_,
const uint_fast32_t* const restrict Physical_Subband_Array_,
const uint_fast32_t* const restrict RCUMODE_Array_,
const Real64_t* const restrict RightAscension_Array_,
const Real64_t* const restrict Declination_Array_,
const char* const * const restrict Epoch_Array_,
const char* const * const restrict SourceName_Array_,
const LOFAR_raw_data_type_enum data_type_process_,
const LOFAR_raw_data_type_enum data_type_out_,
const MPIfR::Numerical::MPIfR_NUMERICAL_WINDOWING_FUNCTION_TYPE_ENUM window_type_,
const Real64_t window_parameter_,
const Real64_t multiplier_
)
throw();
virtual ~LOFAR_Station_Beamformed_Writer_FFT0();
protected:
FILE* restrict fp_data;
uint_fast64_t num_raw_packet_commands_processed;
uint_fast64_t num_spectrum_points_processed;
uint_fast32_t initialized;
int_fast32_t status;
//
void* window_storage;
void* fft_in_storage;
void* fft_out_storage;
void* output_storage;
//
fftwf_plan plan_32;
fftw_plan plan_64;
#ifdef JMA_CODE_HAVE_NATIVE_80_BIT_FLOAT
fftwl_plan plan_80;
#endif // JMA_CODE_HAVE_NATIVE_80_BIT_FLOAT
#ifdef JMA_CODE_HAVE_NATIVE_128_BIT_FLOAT
fftwq_plan plan_128;
#endif // JMA_CODE_HAVE_NATIVE_128_BIT_FLOAT
//
LOFAR_Station_Beamformed_Valid_Real32_Writer* restrict valid_object;
const Real64_t WINDOW_PARAMETER;
const Real64_t SCALING_MULTIPLIER;
uint_fast64_t FFT_BUFFER_LENGTH_CHAR;
uint_fast64_t OUTPUT_BUFFER_LENGTH_CHAR;
uint_fast32_t samples_in_this_FFT;
uint_fast32_t valid_samples_in_this_FFT;
uint_fast32_t NUM_REALS_IN_FFT_BLOCK;
const uint_fast64_t NUM_REALS_IN_FULL_STORAGE_BUFFER;
const uint_fast16_t NUM_PARALLEL_BEAMLETS; // NUM_Output_Beamlets * NUM_RSP_BEAMLET_POLARIZATIONS
LOFAR_raw_data_type_enum processing_DATA_TYPE_REAL;
LOFAR_raw_data_type_enum processing_DATA_TYPE_COMPLEX;
LOFAR_raw_data_type_enum output_DATA_TYPE_REAL;
const MPIfR::Numerical::MPIfR_NUMERICAL_WINDOWING_FUNCTION_TYPE_ENUM window_TYPE;
virtual int_fast32_t do_work(LOFAR_Station_Beamformed_Writer_Base_Work_Enum work_code_copy) throw();
template<class Tin, class Tproc> int_fast32_t write_complex_to_fft_in() restrict throw()
{
for(uint_fast32_t packet=0; packet < current_num_packets; packet++) {
const Tin* const restrict data_in = reinterpret_cast<const Tin* const restrict>(current_data_packets[packet]->data_start_const());
Tproc* const restrict data_out = reinterpret_cast<Tproc* const restrict>(fft_in_storage);
uint_fast32_t sample_offset = 0;
while(sample_offset < NUM_Blocks) {
Tproc* restrict data_out_start = data_out + (samples_in_this_FFT<<1);
uint_fast32_t samples_to_copy = NUM_Blocks - sample_offset;
if(samples_in_this_FFT+samples_to_copy > NUM_OUTPUT_CHANNELS) {
samples_to_copy = NUM_OUTPUT_CHANNELS - samples_in_this_FFT;
}
uint_fast32_t reals_to_copy = samples_to_copy << 1;
for(uint_fast16_t beamlet=0; beamlet < NUM_Output_Beamlets; beamlet++) {
const Tin* restrict data_in_beamlet = data_in + (sample_offset<<1)
+ Beamlet_Offsets_Array[beamlet];
Tproc* restrict data_out_s = data_out_start;
for(uint_fast16_t r = 0; r < reals_to_copy; r+=2) {
data_out_s[r+0] = Tproc(data_in_beamlet->real());
data_out_s[r+1] = Tproc(data_in_beamlet->imag());
data_in_beamlet++;
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+0] = Tproc(data_in_beamlet->real());
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+1] = Tproc(data_in_beamlet->imag());
data_in_beamlet++;
}
data_out_start += size_t(NUM_REALS_IN_FFT_BLOCK)<<1;
}
samples_in_this_FFT += samples_to_copy;
sample_offset += samples_to_copy;
if(current_valid[packet]) {
valid_samples_in_this_FFT += samples_to_copy;
}
if(samples_in_this_FFT == NUM_OUTPUT_CHANNELS) {
int_fast32_t retcode = FFT_block();
if(retcode == 0) {
samples_in_this_FFT = 0;
valid_samples_in_this_FFT = 0;
}
else {
DEF_LOGGING_ERROR("WRITER %d failure while processing packet %u of %u\n", int(id), (unsigned int)(packet), (unsigned int)(current_num_packets));
return retcode;
}
}
}
}
return 0;
}
template<class Tin, class Tproc> int_fast32_t write_real_to_fft_in() restrict throw()
{
for(uint_fast32_t packet=0; packet < current_num_packets; packet++) {
const Tin* const restrict data_in = reinterpret_cast<const Tin* const restrict>(current_data_packets[packet]->data_start_const());
Tproc* const restrict data_out = reinterpret_cast<Tproc* const restrict>(fft_in_storage);
uint_fast32_t sample_offset = 0;
while(sample_offset < NUM_Blocks) {
Tproc* restrict data_out_start = data_out + (samples_in_this_FFT<<1);
uint_fast32_t samples_to_copy = NUM_Blocks - sample_offset;
if(samples_in_this_FFT+samples_to_copy > NUM_OUTPUT_CHANNELS) {
samples_to_copy = NUM_OUTPUT_CHANNELS - samples_in_this_FFT;
}
uint_fast32_t reals_to_copy = samples_to_copy << 1;
for(uint_fast16_t beamlet=0; beamlet < NUM_Output_Beamlets; beamlet++) {
const Tin* restrict data_in_beamlet = data_in + (sample_offset<<2)
+ (Beamlet_Offsets_Array[beamlet]<<1);
Tproc* restrict data_out_s = data_out_start;
for(uint_fast16_t r = 0; r < reals_to_copy; r+=2) {
data_out_s[r+0] = Tproc(*data_in_beamlet++);
data_out_s[r+1] = Tproc(*data_in_beamlet++);
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+0] = Tproc(*data_in_beamlet++);
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+1] = Tproc(*data_in_beamlet++);
}
data_out_start += size_t(NUM_REALS_IN_FFT_BLOCK)<<1;
}
samples_in_this_FFT += samples_to_copy;
sample_offset += samples_to_copy;
if(current_valid[packet]) {
valid_samples_in_this_FFT += samples_to_copy;
}
if(samples_in_this_FFT == NUM_OUTPUT_CHANNELS) {
int_fast32_t retcode = FFT_block();
if(retcode == 0) {
samples_in_this_FFT = 0;
valid_samples_in_this_FFT = 0;
}
else {
DEF_LOGGING_ERROR("WRITER %d failure while processing packet %u of %u\n", int(id), (unsigned int)(packet), (unsigned int)(current_num_packets));
return retcode;
}
}
}
}
return 0;
}
template<class Tin, class Tproc> int_fast32_t write_complex_to_fft_in_partial(const uint_fast32_t NUM_ACTUAL_BLOCKS) restrict throw()
{
const Tin* const restrict data_in = reinterpret_cast<const Tin* const restrict>(current_data_packets[0]->data_start_const());
Tproc* const restrict data_out = reinterpret_cast<Tproc* const restrict>(fft_in_storage);
uint_fast32_t sample_offset = 0;
while(sample_offset < NUM_ACTUAL_BLOCKS) {
Tproc* restrict data_out_start = data_out + (samples_in_this_FFT<<1);
uint_fast32_t samples_to_copy = NUM_ACTUAL_BLOCKS - sample_offset;
if(samples_in_this_FFT+samples_to_copy > NUM_OUTPUT_CHANNELS) {
samples_to_copy = NUM_OUTPUT_CHANNELS - samples_in_this_FFT;
}
uint_fast32_t reals_to_copy = samples_to_copy << 1;
for(uint_fast16_t beamlet=0; beamlet < NUM_Output_Beamlets; beamlet++) {
const Tin* restrict data_in_beamlet = data_in + (sample_offset<<1)
+ Beamlet_Offsets_Array[beamlet];
Tproc* restrict data_out_s = data_out_start;
for(uint_fast16_t r = 0; r < reals_to_copy; r+=2) {
data_out_s[r+0] = Tproc(data_in_beamlet->real());
data_out_s[r+1] = Tproc(data_in_beamlet->imag());
data_in_beamlet++;
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+0] = Tproc(data_in_beamlet->real());
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+1] = Tproc(data_in_beamlet->imag());
data_in_beamlet++;
}
data_out_start += size_t(NUM_REALS_IN_FFT_BLOCK)<<1;
}
samples_in_this_FFT += samples_to_copy;
sample_offset += samples_to_copy;
if(current_valid[0]) {
valid_samples_in_this_FFT += samples_to_copy;
}
if(samples_in_this_FFT == NUM_OUTPUT_CHANNELS) {
int_fast32_t retcode = FFT_block();
if(retcode == 0) {
samples_in_this_FFT = 0;
valid_samples_in_this_FFT = 0;
}
else {
DEF_LOGGING_ERROR("WRITER %d failure while processing packet %u of %u\n", int(id), (unsigned int)(0), (unsigned int)(current_num_packets));
return retcode;
}
}
}
return 0;
}
template<class Tin, class Tproc> int_fast32_t write_real_to_fft_in_partial(const uint_fast32_t NUM_ACTUAL_BLOCKS) restrict throw()
{
const Tin* const restrict data_in = reinterpret_cast<const Tin* const restrict>(current_data_packets[0]->data_start_const());
Tproc* const restrict data_out = reinterpret_cast<Tproc* const restrict>(fft_in_storage);
uint_fast32_t sample_offset = 0;
while(sample_offset < NUM_ACTUAL_BLOCKS) {
Tproc* restrict data_out_start = data_out + (samples_in_this_FFT<<1);
uint_fast32_t samples_to_copy = NUM_ACTUAL_BLOCKS - sample_offset;
if(samples_in_this_FFT+samples_to_copy > NUM_OUTPUT_CHANNELS) {
samples_to_copy = NUM_OUTPUT_CHANNELS - samples_in_this_FFT;
}
uint_fast32_t reals_to_copy = samples_to_copy << 1;
for(uint_fast16_t beamlet=0; beamlet < NUM_Output_Beamlets; beamlet++) {
const Tin* restrict data_in_beamlet = data_in + (sample_offset<<2)
+ (Beamlet_Offsets_Array[beamlet]<<1);
Tproc* restrict data_out_s = data_out_start;
for(uint_fast16_t r = 0; r < reals_to_copy; r+=2) {
data_out_s[r+0] = Tproc(*data_in_beamlet++);
data_out_s[r+1] = Tproc(*data_in_beamlet++);
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+0] = Tproc(*data_in_beamlet++);
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+1] = Tproc(*data_in_beamlet++);
}
data_out_start += size_t(NUM_REALS_IN_FFT_BLOCK)<<1;
}
samples_in_this_FFT += samples_to_copy;
sample_offset += samples_to_copy;
if(current_valid[0]) {
valid_samples_in_this_FFT += samples_to_copy;
}
if(samples_in_this_FFT == NUM_OUTPUT_CHANNELS) {
int_fast32_t retcode = FFT_block();
if(retcode == 0) {
samples_in_this_FFT = 0;
valid_samples_in_this_FFT = 0;
}
else {
DEF_LOGGING_ERROR("WRITER %d failure while processing packet %u of %u\n", int(id), (unsigned int)(0), (unsigned int)(current_num_packets));
return retcode;
}
}
}
return 0;
}
template<class Tproc> int_fast32_t write_real_to_fft_in_flush(uint_fast32_t* const restrict num_flushed) restrict throw()
{
// End of data, flush FFT buffer out
*num_flushed = 0;
if(samples_in_this_FFT == 0) {
// FFT buffer empty already
return 0;
}
Tproc* const restrict data_out = reinterpret_cast<Tproc* const restrict>(fft_in_storage);
Tproc* restrict data_out_start = data_out + (samples_in_this_FFT<<1);
uint_fast32_t samples_to_copy = NUM_OUTPUT_CHANNELS - samples_in_this_FFT;
uint_fast32_t reals_to_copy = samples_to_copy << 1;
Tproc ZERO(0);
for(uint_fast16_t beamlet=0; beamlet < NUM_Output_Beamlets; beamlet++) {
Tproc* restrict data_out_s = data_out_start;
for(uint_fast16_t r = 0; r < reals_to_copy; r+=2) {
data_out_s[r+0] = ZERO;
data_out_s[r+1] = ZERO;
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+0] = ZERO;
data_out_s[NUM_REALS_IN_FFT_BLOCK+r+1] = ZERO;
}
data_out_start += size_t(NUM_REALS_IN_FFT_BLOCK)<<1;
}
samples_in_this_FFT += samples_to_copy;
int_fast32_t retcode = FFT_block();
if(retcode == 0) {
samples_in_this_FFT = 0;
valid_samples_in_this_FFT = 0;
}
else {
DEF_LOGGING_ERROR("WRITER %d failure while processing packet %u of %u\n", int(id), (unsigned int)(0), (unsigned int)(current_num_packets));
return retcode;
}
*num_flushed = samples_to_copy;
return 0;
}
private:
static uint16_t VERSION() throw() {return uint16_t(MPIfR_LOFAR_STATION_SOFTWARE_VERSION);}
static uint16_t WRITER_TYPE() throw() {return uint16_t(LOFAR_DOFF_FFT0_OUT);}
int_fast32_t check_input_parameters() restrict throw();
int_fast32_t set_up_work_buffer_areas() restrict throw();
int_fast32_t set_up_FFT_window() restrict throw();
int_fast32_t set_up_FFTW3() restrict throw();
int_fast32_t open_standard_files() restrict throw();
int_fast32_t shut_down_FFTW3() restrict throw();
int_fast32_t thread_constructor() restrict;
int_fast32_t thread_destructor() restrict;
int_fast32_t close_output_files() throw();
int_fast32_t report_file_error(const char* const restrict msg) const throw();
int_fast32_t write_header_init() throw();
int_fast32_t write_header_start() throw();
int_fast32_t write_header_end() throw();
int_fast32_t write_standard_packets() throw();
int_fast32_t write_partial_packet() throw();
int_fast32_t write_FFT_flush() throw();
int_fast32_t FFT_block() throw();
int_fast32_t dump_FFT_to_output() throw();
// prevent copying
LOFAR_Station_Beamformed_Writer_FFT0(const LOFAR_Station_Beamformed_Writer_FFT0& a);
LOFAR_Station_Beamformed_Writer_FFT0& operator=(const LOFAR_Station_Beamformed_Writer_FFT0& a);
};
// CLASS FUNCTIONS
// HELPER FUNCTIONS
} // end namespace Station
} // end namespace LOFAR
} // end namespace MPIfR
#endif // LOFAR_Station_Beamformed_Writer_FFT0_H
| {
"content_hash": "93781e343852f27c26bf1d03c7f516d8",
"timestamp": "",
"source": "github",
"line_count": 405,
"max_line_length": 168,
"avg_line_length": 42.953086419753085,
"alnum_prop": 0.5398942285582893,
"repo_name": "AHorneffer/lump-lofar-und-mpifr-pulsare",
"id": "54e6dad2d85ad43bb2f7be2d4a98debb0ca42249",
"size": "19695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lump/src/lump/LOFAR_Station_Beamformed_Writer_FFT0.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9516"
},
{
"name": "C++",
"bytes": "2434961"
},
{
"name": "Makefile",
"bytes": "33040"
},
{
"name": "Python",
"bytes": "198357"
},
{
"name": "Shell",
"bytes": "113867"
}
],
"symlink_target": ""
} |
package colossal.pipe.formats;
import java.io.IOException;
import java.util.*;
import org.apache.avro.*;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.reflect.ReflectData;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonToClass {
private static ObjectMapper m = new ObjectMapper();
public static void jsonToObject(String line, Object receiver, Schema schema, Map<String,Class<?>> hints) throws IOException {
JsonNode rootNode = m.readTree(line);
if (!rootNode.isObject()) {
throw new IllegalArgumentException("only accepts a single JSON object as the root");
}
clear(receiver);
setFromNode(rootNode, receiver, schema, line, hints);
}
private static void clear(Object receiver) {
// TODO Auto-generated method stub
}
private static void setFromNode(JsonNode node, Object r, Schema schema, String container, Map<String,Class<?>> hints) {
schema = getObject(schema);
Iterator<JsonNode> it = node.getElements();
Iterator<String> itn = node.getFieldNames();
while (it.hasNext()) {
JsonNode child = it.next();
String name = replaceInvalidNameChars(itn.next());
Field field = schema.getField(name);
if (field == null) {
System.err.println("Warning: skipping unmapped field "+name+" contained in "+container);
continue;
}
Schema childSchema = field.schema();
//ReflectData.get().
java.lang.reflect.Field f = getField(r, name);
Object childObj;
try {
childObj = f.get(r);
}
catch (Exception e) {
throw new RuntimeException(e);
}
if (childObj==null) {
Class<?> fieldType = f.getType();
if (fieldType.isArray()) {
childObj = new Object[0];
} else if (Collection.class.isAssignableFrom(fieldType)) {
childObj = new ArrayList();
//fieldType = hints.get(path+"."+name);
} else {
try {
childObj = fieldType.newInstance();
}
catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// parseField(node, child)
// setField
//
// if (child.isArray()) {
// setFromArrayNode(child, f.get(r), childSchema, name);
// }
// else if (child.isObject()) {
// setFromNode(child, f.get(r), childSchema, name);
// }
// else if (child.isInt()) {
// int intVal = child.getIntValue();
// if (f.getType()==Integer.class || f.getType()==Integer.TYPE) {
// f.set(r, intVal);
// } else if (f.getType()==Long.class || f.getType()==Long.TYPE) {
// f.set(r, (long)intVal);
// } else if (f.getType()==Float.class || f.getType()==Float.TYPE) {
// f.set(r, (float)intVal);
// } else if (f.getType()==Double.class || f.getType()==Double.TYPE) {
// f.set(name, (double)intVal);
// } else {
// throw new IllegalArgumentException("Can't store an int in field "+name);
// }
// }
// else if (child.isLong()) {
// long longVal = child.getLongValue();
// if (f.getType()==Integer.class || f.getType()==Integer.TYPE) {
// f.set(r, (int)longVal);
// } else if (f.getType()==Long.class || f.getType()==Long.TYPE) {
// f.set(r, longVal);
// } else if (f.getType()==Float.class || f.getType()==Float.TYPE) {
// f.set(r, (float)longVal);
// } else if (f.getType()==Double.class || f.getType()==Double.TYPE) {
// f.set(name, (double)longVal);
// } else {
// throw new IllegalArgumentException("Can't store a long in field "+name);
// }
// }
// else if (child.isBinary()) {
// try {
// f.set(r, child.getBinaryValue());
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// else if (child.isBoolean()) {
// f.set(r, child.getBooleanValue());
// }
// else if (child.isDouble()) {
// double val = child.getDoubleValue();
// if (f.getType()==Float.class || f.getType()==Float.TYPE) {
// f.set(r, (float)val);
// } else if (f.getType()==Double.class || f.getType()==Double.TYPE) {
// f.set(name, (double)val);
// } else {
// throw new IllegalArgumentException("Can't store a double in field "+name);
// }
// }
// else if (child.isTextual()) {
// f.set(name, child.getTextValue());
// }
}
}
private static java.lang.reflect.Field getField(Object r, String name) {
// TODO Auto-generated method stub
return null;
}
// private static GenericArray<Object> setFromArrayNode(JsonNode node, Object r, Schema schema, String container) {
// schema = getArray(schema);
// if (schema == null) {
// throw new IllegalArgumentException("can't parse array for schema "+schema);
// }
// Schema childSchema = schema.getElementType();
// for (int i=0; i<node.size(); i++) {
// JsonNode child = node.get(i);
// childSchema.
// if (child.isArray()) {
// Schema elType = schema.getElementType();
// //elType.
// GenericArray<Object> o = setFromArrayNode(child, childSchema, container);
// r.add(o);
// }
// else if (child.isObject()) {
// GenericRecord o = recordFromNode(child, childSchema, container);
// r.add(o);
// }
// else if (child.isInt()) {
// if (acceptsInt(childSchema)) {
// r.add(child.getIntValue());
// } else if (acceptsLong(childSchema)) {
// r.add((long)child.getIntValue());
// } else if (acceptsFloat(childSchema)) {
// r.add((float)child.getIntValue());
// } else if (acceptsDouble(childSchema)) {
// r.add((double)child.getIntValue());
// } else {
// System.err.println("Can't store an int in field "+childSchema);
// }
// }
// else if (child.isLong()) {
// if (acceptsLong(childSchema)) {
// r.add((long)child.getLongValue());
// } else if (acceptsFloat(childSchema)) {
// r.add((float)child.getLongValue());
// } else if (acceptsDouble(childSchema)) {
// r.add((double)child.getLongValue());
// } else {
// System.err.println("Can't store a long in field "+childSchema);
// }
// }
// else if (child.isBinary()) {
// try {
// r.add(child.getBinaryValue());
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// else if (child.isBoolean()) {
// r.add(child.getBooleanValue());
// }
// else if (child.isDouble()) {
// if (acceptsDouble(childSchema)) {
// r.add(child.getDoubleValue());
// } else if (acceptsFloat(childSchema)) {
// r.add((float)child.getDoubleValue());
// } else {
// System.err.println("Can't store a double in field "+childSchema);
// }
// }
// else if (child.isTextual()) {
// r.add(new org.apache.avro.util.Utf8(child.getTextValue()));
// }
// }
// return r;
// }
private static Schema getObject(Schema schema) {
if (schema.getType() == Schema.Type.RECORD) return schema;
if (schema.getType() == Schema.Type.UNION) {
for (Schema s : schema.getTypes()) {
if (s.getType() == Schema.Type.RECORD) {
return s;
}
}
}
return null;
}
private static Schema getArray(Schema schema) {
if (schema.getType() == Schema.Type.ARRAY) return schema;
while (schema.getType() == Type.UNION) {
List<Schema> schemas = schema.getTypes();
Schema found = null;
// dumb parser that won't accept complex union abiguities
for (Schema inner : schemas) {
if (inner.getType() == Type.ARRAY) {
return inner;
} else if (inner.getType() == Type.UNION) {
found = inner;
}
}
if (found == null) {
return null;
}
schema = found;
}
return null;
}
private static boolean accepts(Schema childSchema, Schema.Type type) {
if (childSchema.getType() == type) return true;
if (childSchema.getType() == Schema.Type.UNION) {
for (Schema s : childSchema.getTypes()) {
if (s.getType() == type) {
return true;
}
}
}
return false;
}
private static boolean acceptsFloat(Schema childSchema) {
return accepts(childSchema, Schema.Type.FLOAT);
}
private static boolean acceptsDouble(Schema childSchema) {
return accepts(childSchema, Schema.Type.DOUBLE);
}
private static boolean acceptsLong(Schema childSchema) {
return accepts(childSchema, Schema.Type.LONG);
}
private static boolean acceptsInt(Schema childSchema) {
return accepts(childSchema, Schema.Type.INT);
}
// hand-written for speed - regexps are 100x slower
static String replaceInvalidNameChars(String name) {
int len = name.length();
// scan for first invalid char
int i=0;
for (; i<len; i++) {
char ch = name.charAt(i);
if (!(ch>='a' && ch<='z' || ch>='A' && ch<='Z' || ch>='0' && ch <= '9' || ch == '_'))
break;
}
if (i == len) return name;
StringBuilder copy = new StringBuilder(len);
copy.append(name, 0, i);
copy.append('_');
i++;
for (; i<len; i++) {
char ch = name.charAt(i);
if (ch>='a' && ch<='z' || ch>='A' && ch<='Z' || ch>='0' && ch <= '9' || ch == '_') {
copy.append(ch);
} else {
copy.append('_');
}
}
return copy.toString();
}
}
| {
"content_hash": "da37fc295011a168528c47947a541ebb",
"timestamp": "",
"source": "github",
"line_count": 304,
"max_line_length": 129,
"avg_line_length": 39.31907894736842,
"alnum_prop": 0.4706768175353468,
"repo_name": "ThinkBigAnalytics/colossal-pipe",
"id": "2813ff1112784e802a606a2df13728b381957509",
"size": "12623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/colossal/pipe/formats/JsonToClass.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1574"
},
{
"name": "Java",
"bytes": "148928"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.androiddeviceprovisioning.v1.model;
/**
* Encapsulates hardware and product IDs to identify a manufactured device. To understand
* requirements on identifier sets, read [Identifiers](https://developers.google.com/zero-
* touch/guides/identifiers).
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Android Device Provisioning Partner API. For a
* detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class DeviceIdentifier extends com.google.api.client.json.GenericJson {
/**
* An identifier provided by OEMs, carried through the production and sales process. Only
* applicable to Chrome OS devices.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String chromeOsAttestedDeviceId;
/**
* The type of the device
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String deviceType;
/**
* The device’s IMEI number. Validated on input.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String imei;
/**
* The device manufacturer’s name. Matches the device's built-in value returned from
* `android.os.Build.MANUFACTURER`. Allowed values are listed in [Android manufacturers](/zero-
* touch/resources/manufacturer-names#manufacturers-names).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String manufacturer;
/**
* The device’s MEID number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String meid;
/**
* The device model's name. Allowed values are listed in [Android models](/zero-touch/resources
* /manufacturer-names#model-names) and [Chrome OS
* models](https://support.google.com/chrome/a/answer/10130175?hl=en#identify_compatible).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String model;
/**
* The manufacturer's serial number for the device. This value might not be unique across
* different device models.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String serialNumber;
/**
* An identifier provided by OEMs, carried through the production and sales process. Only
* applicable to Chrome OS devices.
* @return value or {@code null} for none
*/
public java.lang.String getChromeOsAttestedDeviceId() {
return chromeOsAttestedDeviceId;
}
/**
* An identifier provided by OEMs, carried through the production and sales process. Only
* applicable to Chrome OS devices.
* @param chromeOsAttestedDeviceId chromeOsAttestedDeviceId or {@code null} for none
*/
public DeviceIdentifier setChromeOsAttestedDeviceId(java.lang.String chromeOsAttestedDeviceId) {
this.chromeOsAttestedDeviceId = chromeOsAttestedDeviceId;
return this;
}
/**
* The type of the device
* @return value or {@code null} for none
*/
public java.lang.String getDeviceType() {
return deviceType;
}
/**
* The type of the device
* @param deviceType deviceType or {@code null} for none
*/
public DeviceIdentifier setDeviceType(java.lang.String deviceType) {
this.deviceType = deviceType;
return this;
}
/**
* The device’s IMEI number. Validated on input.
* @return value or {@code null} for none
*/
public java.lang.String getImei() {
return imei;
}
/**
* The device’s IMEI number. Validated on input.
* @param imei imei or {@code null} for none
*/
public DeviceIdentifier setImei(java.lang.String imei) {
this.imei = imei;
return this;
}
/**
* The device manufacturer’s name. Matches the device's built-in value returned from
* `android.os.Build.MANUFACTURER`. Allowed values are listed in [Android manufacturers](/zero-
* touch/resources/manufacturer-names#manufacturers-names).
* @return value or {@code null} for none
*/
public java.lang.String getManufacturer() {
return manufacturer;
}
/**
* The device manufacturer’s name. Matches the device's built-in value returned from
* `android.os.Build.MANUFACTURER`. Allowed values are listed in [Android manufacturers](/zero-
* touch/resources/manufacturer-names#manufacturers-names).
* @param manufacturer manufacturer or {@code null} for none
*/
public DeviceIdentifier setManufacturer(java.lang.String manufacturer) {
this.manufacturer = manufacturer;
return this;
}
/**
* The device’s MEID number.
* @return value or {@code null} for none
*/
public java.lang.String getMeid() {
return meid;
}
/**
* The device’s MEID number.
* @param meid meid or {@code null} for none
*/
public DeviceIdentifier setMeid(java.lang.String meid) {
this.meid = meid;
return this;
}
/**
* The device model's name. Allowed values are listed in [Android models](/zero-touch/resources
* /manufacturer-names#model-names) and [Chrome OS
* models](https://support.google.com/chrome/a/answer/10130175?hl=en#identify_compatible).
* @return value or {@code null} for none
*/
public java.lang.String getModel() {
return model;
}
/**
* The device model's name. Allowed values are listed in [Android models](/zero-touch/resources
* /manufacturer-names#model-names) and [Chrome OS
* models](https://support.google.com/chrome/a/answer/10130175?hl=en#identify_compatible).
* @param model model or {@code null} for none
*/
public DeviceIdentifier setModel(java.lang.String model) {
this.model = model;
return this;
}
/**
* The manufacturer's serial number for the device. This value might not be unique across
* different device models.
* @return value or {@code null} for none
*/
public java.lang.String getSerialNumber() {
return serialNumber;
}
/**
* The manufacturer's serial number for the device. This value might not be unique across
* different device models.
* @param serialNumber serialNumber or {@code null} for none
*/
public DeviceIdentifier setSerialNumber(java.lang.String serialNumber) {
this.serialNumber = serialNumber;
return this;
}
@Override
public DeviceIdentifier set(String fieldName, Object value) {
return (DeviceIdentifier) super.set(fieldName, value);
}
@Override
public DeviceIdentifier clone() {
return (DeviceIdentifier) super.clone();
}
}
| {
"content_hash": "e4b66bbcdde6621200fda38e74451575",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 182,
"avg_line_length": 32.35064935064935,
"alnum_prop": 0.7058744814666131,
"repo_name": "googleapis/google-api-java-client-services",
"id": "caf85d2615b174e93ce8e273d116e6589625b237",
"size": "7491",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "clients/google-api-services-androiddeviceprovisioning/v1/2.0.0/com/google/api/services/androiddeviceprovisioning/v1/model/DeviceIdentifier.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Code Coverage for D:\appli\wamp\www\centrale_referencement\src/CentraleReferencementBundle/Repository/DepartementsRepository.php</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../../css/bootstrap.min.css" rel="stylesheet">
<link href="../../css/style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="../../js/html5shiv.min.js"></script>
<script src="../../js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li><a href="../../index.html">D:\appli\wamp\www\centrale_referencement\src</a></li>
<li><a href="../index.html">CentraleReferencementBundle</a></li>
<li><a href="index.html">Repository</a></li>
<li class="active">DepartementsRepository.php</li>
</ol>
</div>
</div>
</div>
</header>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<td> </td>
<td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td>
</tr>
<tr>
<td> </td>
<td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
<td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td>
<td colspan="3"><div align="center"><strong>Lines</strong></div></td>
</tr>
</thead>
<tbody>
<tr>
<td class="">Total</td>
<td class=" big"></td>
<td class=" small"><div align="right">n/a</div></td>
<td class=" small"><div align="right">0 / 0</div></td>
<td class=" big"></td>
<td class=" small"><div align="right">n/a</div></td>
<td class=" small"><div align="right">0 / 0</div></td>
<td class=" small"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></td>
<td class=" big"></td>
<td class=" small"><div align="right">n/a</div></td>
<td class=" small"><div align="right">0 / 0</div></td>
</tr>
<tr>
<td class="">DepartementsRepository</td>
<td class=" big"></td>
<td class=" small"><div align="right">n/a</div></td>
<td class=" small"><div align="right">0 / 0</div></td>
<td class=" big"></td>
<td class=" small"><div align="right">n/a</div></td>
<td class=" small"><div align="right">0 / 0</div></td>
<td class=" small">0</td>
<td class=" big"></td>
<td class=" small"><div align="right">n/a</div></td>
<td class=" small"><div align="right">0 / 0</div></td>
</tr>
</tbody>
</table>
<table id="code" class="table table-borderless table-condensed">
<tbody>
<tr><td><div align="right"><a name="1"></a><a href="#1">1</a></div></td><td class="codeLine"><span class="default"><?php</span></td></tr>
<tr><td><div align="right"><a name="2"></a><a href="#2">2</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="3"></a><a href="#3">3</a></div></td><td class="codeLine"><span class="keyword">namespace</span><span class="default"> </span><span class="default">CentraleReferencementBundle</span><span class="default">\</span><span class="default">Repository</span><span class="keyword">;</span></td></tr>
<tr><td><div align="right"><a name="4"></a><a href="#4">4</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="5"></a><a href="#5">5</a></div></td><td class="codeLine"><span class="comment">/**</span></td></tr>
<tr><td><div align="right"><a name="6"></a><a href="#6">6</a></div></td><td class="codeLine"><span class="comment"> * DepartementsRepository</span></td></tr>
<tr><td><div align="right"><a name="7"></a><a href="#7">7</a></div></td><td class="codeLine"><span class="comment"> *</span></td></tr>
<tr><td><div align="right"><a name="8"></a><a href="#8">8</a></div></td><td class="codeLine"><span class="comment"> * This class was generated by the Doctrine ORM. Add your own custom</span></td></tr>
<tr><td><div align="right"><a name="9"></a><a href="#9">9</a></div></td><td class="codeLine"><span class="comment"> * repository methods below.</span></td></tr>
<tr><td><div align="right"><a name="10"></a><a href="#10">10</a></div></td><td class="codeLine"><span class="comment"> */</span></td></tr>
<tr><td><div align="right"><a name="11"></a><a href="#11">11</a></div></td><td class="codeLine"><span class="keyword">class</span><span class="default"> </span><span class="default">DepartementsRepository</span><span class="default"> </span><span class="keyword">extends</span><span class="default"> </span><span class="default">\</span><span class="default">Doctrine</span><span class="default">\</span><span class="default">ORM</span><span class="default">\</span><span class="default">EntityRepository</span></td></tr>
<tr><td><div align="right"><a name="12"></a><a href="#12">12</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr>
<tr><td><div align="right"><a name="13"></a><a href="#13">13</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr>
</tbody>
</table>
<footer>
<hr/>
<h4>Legend</h4>
<p>
<span class="success"><strong>Executed</strong></span>
<span class="danger"><strong>Not Executed</strong></span>
<span class="warning"><strong>Dead Code</strong></span>
</p>
<p>
<small>Generated by <a href="https://github.com/sebastianbergmann/php-code-coverage" target="_top">php-code-coverage 5.0.0</a> using <a href="https://secure.php.net/" target="_top">PHP 7.0.4</a> with <a href="https://xdebug.org/">Xdebug 2.4.0</a> and <a href="https://phpunit.de/">PHPUnit 6.0.5</a> at Tue Feb 7 8:45:37 UTC 2017.</small>
</p>
<a title="Back to the top" id="toplink" href="#"><span class="glyphicon glyphicon-arrow-up"></span></a>
</footer>
</div>
<script src="../../js/jquery.min.js" type="text/javascript"></script>
<script src="../../js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../js/holder.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var $window = $(window)
, $top_link = $('#toplink')
, $body = $('body, html')
, offset = $('#code').offset().top;
$top_link.hide().click(function(event) {
event.preventDefault();
$body.animate({scrollTop:0}, 800);
});
$window.scroll(function() {
if($window.scrollTop() > offset) {
$top_link.fadeIn();
} else {
$top_link.fadeOut();
}
}).scroll();
$('.popin').popover({trigger: 'hover'});
});
</script>
</body>
</html>
| {
"content_hash": "54cccfec5dd2cad4c8a5c90f1bd3724b",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 541,
"avg_line_length": 51.592592592592595,
"alnum_prop": 0.588226848528356,
"repo_name": "ViraxDev/centrale_referencement",
"id": "b23caf97491d89e98167d2b79a8d989ea34a582b",
"size": "6965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "coverage/CentraleReferencementBundle/Repository/DepartementsRepository.php.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2391"
},
{
"name": "CSS",
"bytes": "859006"
},
{
"name": "HTML",
"bytes": "3791407"
},
{
"name": "JavaScript",
"bytes": "3562512"
},
{
"name": "PHP",
"bytes": "430233"
}
],
"symlink_target": ""
} |
FROM node:6.10.0-alpine
ENV PATH /root/.yarn/bin:${PATH}
ENV YARN_VERSION 0.21.3
RUN \
apk add --no-cache --update --virtual .build-deps bash curl gnupg tar && \
curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version ${YARN_VERSION} && \
apk del .build-deps
WORKDIR /app
COPY ./package.json ./yarn.lock /app/
RUN yarn
COPY . /app/
RUN \
yarn build -- --env production && \
rm -rf ./node_modules && \
yarn --production && \
rm -rf $(yarn cache dir)
EXPOSE 8080
CMD ["yarn", "start"]
| {
"content_hash": "680f4598417850d429403c728dbcaa1b",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 88,
"avg_line_length": 21.375,
"alnum_prop": 0.6276803118908382,
"repo_name": "baberutv/baberutv",
"id": "9c854bcedf5082fe5d0daa31c23f0866b4d48640",
"size": "513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1370"
},
{
"name": "JavaScript",
"bytes": "16130"
},
{
"name": "Shell",
"bytes": "750"
}
],
"symlink_target": ""
} |
<?php
namespace Applisun\CompteBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
class DefaultController extends Controller
{
public function indexAction()
{
$user = $this->getUser();
if (!$user instanceof \Applisun\CompteBundle\Entity\User)
{
return $this->render('ApplisunCompteBundle:Default:index.html.twig');
}
else{
$comptes = $user->getComptes();
return $this->render('ApplisunCompteBundle:Default:index.html.twig', array('nom' => $user->getUsername(), 'comptes' => $comptes));
}
}
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render('ApplisunCompteBundle:Default:login.html.twig', array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
}
public function testAction()
{
return $this->render('ApplisunCompteBundle:Default:test.html.twig');
}
}
| {
"content_hash": "6041396b9b8a788b7f8d4666219f79c5",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 142,
"avg_line_length": 33.702127659574465,
"alnum_prop": 0.6174242424242424,
"repo_name": "frederic3476/compte",
"id": "fd6b22fdef721b6f0d6ba68da4bd40f2630648c4",
"size": "1584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Applisun/CompteBundle/Controller/DefaultController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "Batchfile",
"bytes": "385"
},
{
"name": "CSS",
"bytes": "302656"
},
{
"name": "HTML",
"bytes": "177926"
},
{
"name": "JavaScript",
"bytes": "1529386"
},
{
"name": "PHP",
"bytes": "209623"
},
{
"name": "Shell",
"bytes": "617"
}
],
"symlink_target": ""
} |
exports = module.exports = function install() {
// TODO:
}
| {
"content_hash": "d7c240b81fb9d7168b112d20e0a7f43a",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 47,
"avg_line_length": 20.333333333333332,
"alnum_prop": 0.639344262295082,
"repo_name": "jaredhanson/tensile",
"id": "7a0ef73f3a073ed26e2be87edcb43e93786c5187",
"size": "61",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/cli/install.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "55282"
}
],
"symlink_target": ""
} |
local OptionParser = {}
function xlua.OptionParser(usage)
local self = {}
self.usage = usage
self.option_descriptions = {}
self.option_of = {}
for k,v in pairs(OptionParser) do
self[k] = v
end
self:option{"-h", "--help", action="store_true", dest="help",
help="show this help message and exit"}
return self
end
function OptionParser:fail(s) -- extension
io.stderr:write(s .. '\n')
self:help()
os.exit(1)
end
function OptionParser:option(optdesc)
self.option_descriptions[#self.option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
self.option_of[v] = optdesc
end
end
function OptionParser:parse(options)
local options = options or {}
local args = {}
-- set the default
for _,v in ipairs(self.option_descriptions) do
if v.default ~= nil and options[v.dest]==nil then
options[v.dest] = v.default
end
end
if not arg then
options.__main__ = false -- python like main
self.options = options
return options, args
end
options.__main__ = true -- python like main
-- expand options (e.g. "--input=file" -> "--input", "file")
local unpack = unpack or table.unpack
local arg = {unpack(arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
end
end
local i = 1
while i <= #arg do
local v = arg[i]
local optdesc = self.option_of[v]
if optdesc then
local default = optdesc.default
local action = optdesc.action
local val = default
if action == 'store' or action == nil then
i = i + 1
val = arg[i] or default
if not val then self:fail('option requires an argument ' .. v) end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
val = false
end
options[optdesc.dest] = val
else
if v:match('^%-') then self:fail('invalid option ' .. v) end
args[#args+1] = v
end
i = i + 1
end
for k,opt in pairs(self.option_of) do
if opt.req and not options[opt.dest] then
self:fail('option '.. k .. ' requires an argument ')
end
end
if options.help then
self:help()
os.exit()
end
-- set the default if nil
self.options = options
return options, args
end
function OptionParser:flags(optdesc)
local sflags = {}
local action = optdesc and optdesc.action
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
sflagend = ''
end
sflags[#sflags+1] = flag .. sflagend
end
return table.concat(sflags, ', ')
end
function OptionParser:help()
if arg[-1] then
io.stdout:write("Usage: " .. self.usage:gsub('%%prog', (arg[-1] .. ' ' .. arg[0])) .. "\n")
elseif arg[0] then
io.stdout:write("Usage: " .. self.usage:gsub('%%prog', arg[0]) .. "\n")
else
io.stdout:write("Usage: " .. self.usage:gsub('%%prog', 'THISPROG') .. "\n")
end
io.stdout:write("\n")
io.stdout:write("Options:\n")
pad = 0
for _,optdesc in ipairs(self.option_descriptions) do
pad = math.max(pad, #self:flags(optdesc))
end
for _,optdesc in ipairs(self.option_descriptions) do
local defstr = ''
if optdesc.req then
defstr = ' [REQUIRED]'
elseif optdesc.default then
defstr = ' [default = ' .. tostring(optdesc.default) .. ']'
end
io.stdout:write(" " .. self:flags(optdesc) ..
string.rep(' ', pad - #self:flags(optdesc)) ..
" " .. optdesc.help .. defstr .. "\n")
end
end
function OptionParser:tostring(generatefilename, params)
local str = ''
if not generatefilename then
str = '<'.. ((arg and arg[0]) or 'interpreted.lua'):gsub('.lua','') .. "> configuration:\n"
for k,v in pairs(self.options) do
str = str .. ' + ' .. k .. ' = ' .. tostring(v) .. '\n'
end
else
local first = true
for i,entry in ipairs(self.option_descriptions) do
local key = entry[1]
local match = true
if #params > 0 then
match = false
for i,param in ipairs(params) do
if key == param then match = true; break end
end
end
local val = self.options[entry.dest]
if val and match then
if first then
str = str .. key .. '=' .. tostring(val)
else
str = str .. ',' .. key .. '=' .. tostring(val)
end
first = false
end
end
str = str:gsub('/','|'):gsub(' ','_')
end
return str
end
function OptionParser:summarize(compact)
io.write(self:tostring(compact))
end
| {
"content_hash": "825842411501330a2cb23f6d1b0dc9ef",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 97,
"avg_line_length": 28.86857142857143,
"alnum_prop": 0.5540380047505938,
"repo_name": "torch/xlua",
"id": "facad43b65c800b91bc65da5c735b3053a657e07",
"size": "6084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OptionParser.lua",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CMake",
"bytes": "483"
},
{
"name": "Lua",
"bytes": "34753"
}
],
"symlink_target": ""
} |
#ifndef TextTrackRepresentation_h
#define TextTrackRepresentation_h
#if ENABLE(VIDEO_TRACK)
#include "PlatformLayer.h"
#include <wtf/Forward.h>
namespace WebCore {
class Image;
class IntRect;
class TextTrackRepresentationClient {
public:
virtual ~TextTrackRepresentationClient() { }
virtual RefPtr<Image> createTextTrackRepresentationImage() = 0;
virtual void textTrackRepresentationBoundsChanged(const IntRect&) = 0;
};
class TextTrackRepresentation {
public:
static std::unique_ptr<TextTrackRepresentation> create(TextTrackRepresentationClient&);
virtual ~TextTrackRepresentation() { }
virtual void update() = 0;
virtual PlatformLayer* platformLayer() = 0;
virtual void setContentScale(float) = 0;
virtual IntRect bounds() const = 0;
};
}
#endif
#endif // TextTrackRepresentation_h
| {
"content_hash": "b2282d1b4026393306b17dcb6d851366",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 91,
"avg_line_length": 20.85,
"alnum_prop": 0.7529976019184652,
"repo_name": "applesrc/WebCore",
"id": "72117048a26326d801f142283ad1d9f96609f847",
"size": "2188",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "platform/graphics/TextTrackRepresentation.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "1942"
},
{
"name": "C",
"bytes": "1389023"
},
{
"name": "C++",
"bytes": "42141769"
},
{
"name": "CMake",
"bytes": "254371"
},
{
"name": "CSS",
"bytes": "195888"
},
{
"name": "HTML",
"bytes": "2042"
},
{
"name": "JavaScript",
"bytes": "325391"
},
{
"name": "Makefile",
"bytes": "59092"
},
{
"name": "Objective-C",
"bytes": "927452"
},
{
"name": "Objective-C++",
"bytes": "3488469"
},
{
"name": "Perl",
"bytes": "646919"
},
{
"name": "Perl6",
"bytes": "79316"
},
{
"name": "Python",
"bytes": "37212"
},
{
"name": "Roff",
"bytes": "26536"
},
{
"name": "Shell",
"bytes": "356"
},
{
"name": "Yacc",
"bytes": "11721"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.