text
stringlengths 2
1.04M
| meta
dict |
---|---|
import Ember from 'ember-metal/core';
import { testBoth } from 'ember-metal/tests/props_helper';
import { addListener } from 'ember-metal/events';
import {
watch,
unwatch,
destroy
} from 'ember-metal/watching';
var willCount, didCount,
willKeys, didKeys,
originalLookup, lookup, Global;
QUnit.module('watch', {
setup() {
willCount = didCount = 0;
willKeys = [];
didKeys = [];
originalLookup = Ember.lookup;
Ember.lookup = lookup = {};
},
teardown() {
Ember.lookup = originalLookup;
}
});
function addListeners(obj, keyPath) {
addListener(obj, keyPath + ':before', function() {
willCount++;
willKeys.push(keyPath);
});
addListener(obj, keyPath + ':change', function() {
didCount++;
didKeys.push(keyPath);
});
}
testBoth('watching a computed property', function(get, set) {
var obj = {};
Ember.defineProperty(obj, 'foo', Ember.computed({
get: function() {
return this.__foo;
},
set: function(keyName, value) {
if (value !== undefined) {
this.__foo = value;
}
return this.__foo;
}
}));
addListeners(obj, 'foo');
watch(obj, 'foo');
set(obj, 'foo', 'bar');
equal(willCount, 1, 'should have invoked willCount');
equal(didCount, 1, 'should have invoked didCount');
});
testBoth('watching a regular defined property', function(get, set) {
var obj = { foo: 'baz' };
addListeners(obj, 'foo');
watch(obj, 'foo');
equal(get(obj, 'foo'), 'baz', 'should have original prop');
set(obj, 'foo', 'bar');
equal(willCount, 1, 'should have invoked willCount');
equal(didCount, 1, 'should have invoked didCount');
equal(get(obj, 'foo'), 'bar', 'should get new value');
equal(obj.foo, 'bar', 'property should be accessible on obj');
});
testBoth('watching a regular undefined property', function(get, set) {
var obj = { };
addListeners(obj, 'foo');
watch(obj, 'foo');
equal('foo' in obj, false, 'precond undefined');
set(obj, 'foo', 'bar');
equal(willCount, 1, 'should have invoked willCount');
equal(didCount, 1, 'should have invoked didCount');
equal(get(obj, 'foo'), 'bar', 'should get new value');
equal(obj.foo, 'bar', 'property should be accessible on obj');
});
testBoth('watches should inherit', function(get, set) {
var obj = { foo: 'baz' };
var objB = Object.create(obj);
addListeners(obj, 'foo');
watch(obj, 'foo');
equal(get(obj, 'foo'), 'baz', 'should have original prop');
set(obj, 'foo', 'bar');
set(objB, 'foo', 'baz');
equal(willCount, 2, 'should have invoked willCount once only');
equal(didCount, 2, 'should have invoked didCount once only');
});
QUnit.test('watching an object THEN defining it should work also', function() {
var obj = {};
addListeners(obj, 'foo');
watch(obj, 'foo');
Ember.defineProperty(obj, 'foo');
Ember.set(obj, 'foo', 'bar');
equal(Ember.get(obj, 'foo'), 'bar', 'should have set');
equal(willCount, 1, 'should have invoked willChange once');
equal(didCount, 1, 'should have invoked didChange once');
});
QUnit.test('watching a chain then defining the property', function () {
var obj = {};
var foo = { bar: 'bar' };
addListeners(obj, 'foo.bar');
addListeners(foo, 'bar');
watch(obj, 'foo.bar');
Ember.defineProperty(obj, 'foo', undefined, foo);
Ember.set(foo, 'bar', 'baz');
deepEqual(willKeys, ['foo.bar', 'bar'], 'should have invoked willChange with bar, foo.bar');
deepEqual(didKeys, ['foo.bar', 'bar'], 'should have invoked didChange with bar, foo.bar');
equal(willCount, 2, 'should have invoked willChange twice');
equal(didCount, 2, 'should have invoked didChange twice');
});
QUnit.test('watching a chain then defining the nested property', function () {
var bar = {};
var obj = { foo: bar };
var baz = { baz: 'baz' };
addListeners(obj, 'foo.bar.baz');
addListeners(baz, 'baz');
watch(obj, 'foo.bar.baz');
Ember.defineProperty(bar, 'bar', undefined, baz);
Ember.set(baz, 'baz', 'BOO');
deepEqual(willKeys, ['foo.bar.baz', 'baz'], 'should have invoked willChange with bar, foo.bar');
deepEqual(didKeys, ['foo.bar.baz', 'baz'], 'should have invoked didChange with bar, foo.bar');
equal(willCount, 2, 'should have invoked willChange twice');
equal(didCount, 2, 'should have invoked didChange twice');
});
testBoth('watching an object value then unwatching should restore old value', function(get, set) {
var obj = { foo: { bar: { baz: { biff: 'BIFF' } } } };
addListeners(obj, 'foo.bar.baz.biff');
watch(obj, 'foo.bar.baz.biff');
var foo = Ember.get(obj, 'foo');
equal(get(get(get(foo, 'bar'), 'baz'), 'biff'), 'BIFF', 'biff should exist');
unwatch(obj, 'foo.bar.baz.biff');
equal(get(get(get(foo, 'bar'), 'baz'), 'biff'), 'BIFF', 'biff should exist');
});
testBoth('watching a global object that does not yet exist should queue', function(get, set) {
lookup['Global'] = Global = null;
var obj = {};
addListeners(obj, 'Global.foo');
watch(obj, 'Global.foo'); // only works on global chained props
equal(willCount, 0, 'should not have fired yet');
equal(didCount, 0, 'should not have fired yet');
lookup['Global'] = Global = { foo: 'bar' };
addListeners(Global, 'foo');
watch.flushPending(); // this will also be invoked automatically on ready
equal(willCount, 0, 'should not have fired yet');
equal(didCount, 0, 'should not have fired yet');
set(Global, 'foo', 'baz');
// should fire twice because this is a chained property (once on key, once
// on path)
equal(willCount, 2, 'should be watching');
equal(didCount, 2, 'should be watching');
lookup['Global'] = Global = null; // reset
});
QUnit.test('when watching a global object, destroy should remove chain watchers from the global object', function() {
lookup['Global'] = Global = { foo: 'bar' };
var obj = {};
addListeners(obj, 'Global.foo');
watch(obj, 'Global.foo');
var meta_Global = Ember.meta(Global);
var chainNode = Ember.meta(obj).chains._chains.Global._chains.foo;
var index = meta_Global.chainWatchers.foo.indexOf(chainNode);
equal(meta_Global.watching.foo, 1, 'should be watching foo');
strictEqual(meta_Global.chainWatchers.foo[index], chainNode, 'should have chain watcher');
destroy(obj);
index = meta_Global.chainWatchers.foo.indexOf(chainNode);
equal(meta_Global.watching.foo, 0, 'should not be watching foo');
equal(index, -1, 'should not have chain watcher');
lookup['Global'] = Global = null; // reset
});
QUnit.test('when watching another object, destroy should remove chain watchers from the other object', function() {
var objA = {};
var objB = { foo: 'bar' };
objA.b = objB;
addListeners(objA, 'b.foo');
watch(objA, 'b.foo');
var meta_objB = Ember.meta(objB);
var chainNode = Ember.meta(objA).chains._chains.b._chains.foo;
var index = meta_objB.chainWatchers.foo.indexOf(chainNode);
equal(meta_objB.watching.foo, 1, 'should be watching foo');
strictEqual(meta_objB.chainWatchers.foo[index], chainNode, 'should have chain watcher');
destroy(objA);
index = meta_objB.chainWatchers.foo.indexOf(chainNode);
equal(meta_objB.watching.foo, 0, 'should not be watching foo');
equal(index, -1, 'should not have chain watcher');
});
// TESTS for length property
testBoth('watching "length" property on an object', function(get, set) {
var obj = { length: '26.2 miles' };
addListeners(obj, 'length');
watch(obj, 'length');
equal(get(obj, 'length'), '26.2 miles', 'should have original prop');
set(obj, 'length', '10k');
equal(willCount, 1, 'should have invoked willCount');
equal(didCount, 1, 'should have invoked didCount');
equal(get(obj, 'length'), '10k', 'should get new value');
equal(obj.length, '10k', 'property should be accessible on obj');
});
testBoth('watching "length" property on an array', function(get, set) {
var arr = [];
addListeners(arr, 'length');
watch(arr, 'length');
equal(get(arr, 'length'), 0, 'should have original prop');
set(arr, 'length', '10');
equal(willCount, 0, 'should NOT have invoked willCount');
equal(didCount, 0, 'should NOT have invoked didCount');
equal(get(arr, 'length'), 10, 'should get new value');
equal(arr.length, 10, 'property should be accessible on arr');
});
| {
"content_hash": "abb3ad48439bc41e75fd6a6d1d85d79b",
"timestamp": "",
"source": "github",
"line_count": 274,
"max_line_length": 117,
"avg_line_length": 30.145985401459853,
"alnum_prop": 0.6549636803874092,
"repo_name": "marcioj/ember.js",
"id": "c6aea444f39ed87e79ec39b00b0cf6fa4364da63",
"size": "8260",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "packages/ember-metal/tests/watching/watch_test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6962"
},
{
"name": "Handlebars",
"bytes": "1873"
},
{
"name": "JavaScript",
"bytes": "3276466"
},
{
"name": "Ruby",
"bytes": "6190"
},
{
"name": "Shell",
"bytes": "2469"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2013 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/decelerate_interpolator"
android:fromYDelta="-50%p" android:toYDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/><!-- From: file:/Users/Dani/Downloads/SDOS1/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/20.0.0/res/anim/abc_slide_in_top.xml --> | {
"content_hash": "f9a2fc7a834c4529d90654458a35063d",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 224,
"avg_line_length": 57.63157894736842,
"alnum_prop": 0.7223744292237443,
"repo_name": "Danmarjim/SDOS",
"id": "d74ed0808499022d47cb48c3f47ee6422bb7a247",
"size": "1095",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/build/intermediates/res/debug/anim/abc_slide_in_top.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3223"
},
{
"name": "HTML",
"bytes": "903"
},
{
"name": "Java",
"bytes": "402274"
}
],
"symlink_target": ""
} |
package com.google.common.testing;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.truth0.Truth.ASSERT;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Table;
import com.google.common.reflect.TypeToken;
import com.google.common.testing.NullPointerTester.Visibility;
import com.google.common.testing.anotherpackage.SomeClassThatDoesNotUseNullable;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Unit test for {@link NullPointerTester}.
*
* @author Kevin Bourrillion
* @author Mick Killianey
*/
public class NullPointerTesterTest extends TestCase {
/** Non-NPE RuntimeException. */
public static class FooException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
/**
* Class for testing all permutations of static/non-static one-argument
* methods using methodParameter().
*/
@SuppressWarnings("unused") // used by reflection
public static class OneArg {
public static void staticOneArgCorrectlyThrowsNpe(String s) {
checkNotNull(s); // expect NPE here on null
}
public static void staticOneArgThrowsOtherThanNpe(String s) {
throw new FooException(); // should catch as failure
}
public static void staticOneArgShouldThrowNpeButDoesnt(String s) {
// should catch as failure
}
public static void
staticOneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) {
// null? no problem
}
public static void
staticOneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) {
throw new FooException(); // ok, as long as it's not NullPointerException
}
public static void
staticOneArgNullableThrowsNPE(@Nullable String s) {
checkNotNull(s); // doesn't check if you said you'd accept null, but you don't
}
public void oneArgCorrectlyThrowsNpe(String s) {
checkNotNull(s); // expect NPE here on null
}
public void oneArgThrowsOtherThanNpe(String s) {
throw new FooException(); // should catch as failure
}
public void oneArgShouldThrowNpeButDoesnt(String s) {
// should catch as failure
}
public void oneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) {
// null? no problem
}
public void oneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) {
throw new FooException(); // ok, as long as it's not NullPointerException
}
public void oneArgNullableThrowsNPE(@Nullable String s) {
checkNotNull(s); // doesn't check if you said you'd accept null, but you don't
}
}
private static final String[] STATIC_ONE_ARG_METHODS_SHOULD_PASS = {
"staticOneArgCorrectlyThrowsNpe",
"staticOneArgNullableCorrectlyDoesNotThrowNPE",
"staticOneArgNullableCorrectlyThrowsOtherThanNPE",
"staticOneArgNullableThrowsNPE",
};
private static final String[] STATIC_ONE_ARG_METHODS_SHOULD_FAIL = {
"staticOneArgThrowsOtherThanNpe",
"staticOneArgShouldThrowNpeButDoesnt",
};
private static final String[] NONSTATIC_ONE_ARG_METHODS_SHOULD_PASS = {
"oneArgCorrectlyThrowsNpe",
"oneArgNullableCorrectlyDoesNotThrowNPE",
"oneArgNullableCorrectlyThrowsOtherThanNPE",
"oneArgNullableThrowsNPE",
};
private static final String[] NONSTATIC_ONE_ARG_METHODS_SHOULD_FAIL = {
"oneArgThrowsOtherThanNpe",
"oneArgShouldThrowNpeButDoesnt",
};
private static class ThrowsIae {
public static void christenPoodle(String name) {
checkArgument(name != null);
}
}
private static class ThrowsNpe {
public static void christenPoodle(String name) {
checkNotNull(name);
}
}
private static class ThrowsUoe {
public static void christenPoodle(String name) {
throw new UnsupportedOperationException();
}
}
private static class ThrowsSomethingElse {
public static void christenPoodle(String name) {
throw new RuntimeException();
}
}
public void testDontAcceptIae() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicStaticMethods(ThrowsNpe.class);
tester.testAllPublicStaticMethods(ThrowsUoe.class);
try {
tester.testAllPublicStaticMethods(ThrowsIae.class);
} catch (AssertionFailedError expected) {
return;
}
fail();
}
public void testStaticOneArgMethodsThatShouldPass() throws Exception {
for (String methodName : STATIC_ONE_ARG_METHODS_SHOULD_PASS) {
Method method = OneArg.class.getMethod(methodName, String.class);
try {
new NullPointerTester().testMethodParameter(new OneArg(), method, 0);
} catch (AssertionFailedError unexpected) {
fail("Should not have flagged method " + methodName);
}
}
}
public void testStaticOneArgMethodsThatShouldFail() throws Exception {
for (String methodName : STATIC_ONE_ARG_METHODS_SHOULD_FAIL) {
Method method = OneArg.class.getMethod(methodName, String.class);
boolean foundProblem = false;
try {
new NullPointerTester().testMethodParameter(new OneArg(), method, 0);
} catch (AssertionFailedError expected) {
foundProblem = true;
}
assertTrue("Should report error in method " + methodName, foundProblem);
}
}
public void testNonStaticOneArgMethodsThatShouldPass() throws Exception {
OneArg foo = new OneArg();
for (String methodName : NONSTATIC_ONE_ARG_METHODS_SHOULD_PASS) {
Method method = OneArg.class.getMethod(methodName, String.class);
try {
new NullPointerTester().testMethodParameter(foo, method, 0);
} catch (AssertionFailedError unexpected) {
fail("Should not have flagged method " + methodName);
}
}
}
public void testNonStaticOneArgMethodsThatShouldFail() throws Exception {
OneArg foo = new OneArg();
for (String methodName : NONSTATIC_ONE_ARG_METHODS_SHOULD_FAIL) {
Method method = OneArg.class.getMethod(methodName, String.class);
boolean foundProblem = false;
try {
new NullPointerTester().testMethodParameter(foo, method, 0);
} catch (AssertionFailedError expected) {
foundProblem = true;
}
assertTrue("Should report error in method " + methodName, foundProblem);
}
}
/**
* Class for testing all permutations of nullable/non-nullable two-argument
* methods using testMethod().
*
* normalNormal: two params, neither is Nullable
* nullableNormal: only first param is Nullable
* normalNullable: only second param is Nullable
* nullableNullable: both params are Nullable
*/
public static class TwoArg {
/** Action to take on a null param. */
public enum Action {
THROW_A_NPE {
@Override public void act() {
throw new NullPointerException();
}
},
THROW_OTHER {
@Override public void act() {
throw new FooException();
}
},
JUST_RETURN {
@Override public void act() {}
};
public abstract void act();
}
Action actionWhenFirstParamIsNull;
Action actionWhenSecondParamIsNull;
public TwoArg(
Action actionWhenFirstParamIsNull,
Action actionWhenSecondParamIsNull) {
this.actionWhenFirstParamIsNull = actionWhenFirstParamIsNull;
this.actionWhenSecondParamIsNull = actionWhenSecondParamIsNull;
}
/** Method that decides how to react to parameters. */
public void reactToNullParameters(Object first, Object second) {
if (first == null) {
actionWhenFirstParamIsNull.act();
}
if (second == null) {
actionWhenSecondParamIsNull.act();
}
}
/** Two-arg method with no Nullable params. */
public void normalNormal(String first, Integer second) {
reactToNullParameters(first, second);
}
/** Two-arg method with the second param Nullable. */
public void normalNullable(String first, @Nullable Integer second) {
reactToNullParameters(first, second);
}
/** Two-arg method with the first param Nullable. */
public void nullableNormal(@Nullable String first, Integer second) {
reactToNullParameters(first, second);
}
/** Two-arg method with the both params Nullable. */
public void nullableNullable(
@Nullable String first, @Nullable Integer second) {
reactToNullParameters(first, second);
}
/** To provide sanity during debugging. */
@Override public String toString() {
return String.format("Bar(%s, %s)",
actionWhenFirstParamIsNull, actionWhenSecondParamIsNull);
}
}
public void verifyBarPass(Method method, TwoArg bar) {
try {
new NullPointerTester().testMethod(bar, method);
} catch (AssertionFailedError incorrectError) {
String errorMessage = String.format(
"Should not have flagged method %s for %s", method.getName(), bar);
assertNull(errorMessage, incorrectError);
}
}
public void verifyBarFail(Method method, TwoArg bar) {
try {
new NullPointerTester().testMethod(bar, method);
} catch (AssertionFailedError expected) {
return; // good...we wanted a failure
}
String errorMessage = String.format(
"Should have flagged method %s for %s", method.getName(), bar);
fail(errorMessage);
}
public void testTwoArgNormalNormal() throws Exception {
Method method = TwoArg.class.getMethod(
"normalNormal", String.class, Integer.class);
for (TwoArg.Action first : TwoArg.Action.values()) {
for (TwoArg.Action second : TwoArg.Action.values()) {
TwoArg bar = new TwoArg(first, second);
if (first.equals(TwoArg.Action.THROW_A_NPE)
&& second.equals(TwoArg.Action.THROW_A_NPE)) {
verifyBarPass(method, bar); // require both params to throw NPE
} else {
verifyBarFail(method, bar);
}
}
}
}
public void testTwoArgNormalNullable() throws Exception {
Method method = TwoArg.class.getMethod(
"normalNullable", String.class, Integer.class);
for (TwoArg.Action first : TwoArg.Action.values()) {
for (TwoArg.Action second : TwoArg.Action.values()) {
TwoArg bar = new TwoArg(first, second);
if (first.equals(TwoArg.Action.THROW_A_NPE)) {
verifyBarPass(method, bar); // only pass if 1st param throws NPE
} else {
verifyBarFail(method, bar);
}
}
}
}
public void testTwoArgNullableNormal() throws Exception {
Method method = TwoArg.class.getMethod(
"nullableNormal", String.class, Integer.class);
for (TwoArg.Action first : TwoArg.Action.values()) {
for (TwoArg.Action second : TwoArg.Action.values()) {
TwoArg bar = new TwoArg(first, second);
if (second.equals(TwoArg.Action.THROW_A_NPE)) {
verifyBarPass(method, bar); // only pass if 2nd param throws NPE
} else {
verifyBarFail(method, bar);
}
}
}
}
public void testTwoArgNullableNullable() throws Exception {
Method method = TwoArg.class.getMethod(
"nullableNullable", String.class, Integer.class);
for (TwoArg.Action first : TwoArg.Action.values()) {
for (TwoArg.Action second : TwoArg.Action.values()) {
TwoArg bar = new TwoArg(first, second);
verifyBarPass(method, bar); // All args nullable: anything goes!
}
}
}
/*
* This next part consists of several sample classes that provide
* demonstrations of conditions that cause NullPointerTester
* to succeed/fail.
*/
/** Lots of well-behaved methods. */
@SuppressWarnings("unused") // used by reflection
private static class PassObject extends SomeClassThatDoesNotUseNullable {
public static void doThrow(Object arg) {
if (arg == null) {
throw new FooException();
}
}
public void noArg() {}
public void oneArg(String s) { checkNotNull(s); }
void packagePrivateOneArg(String s) { checkNotNull(s); }
protected void protectedOneArg(String s) { checkNotNull(s); }
public void oneNullableArg(@Nullable String s) {}
public void oneNullableArgThrows(@Nullable String s) { doThrow(s); }
public void twoArg(String s, Integer i) { checkNotNull(s); i.intValue(); }
public void twoMixedArgs(String s, @Nullable Integer i) { checkNotNull(s); }
public void twoMixedArgsThrows(String s, @Nullable Integer i) {
checkNotNull(s); doThrow(i);
}
public void twoMixedArgs(@Nullable Integer i, String s) { checkNotNull(s); }
public void twoMixedArgsThrows(@Nullable Integer i, String s) {
checkNotNull(s); doThrow(i);
}
public void twoNullableArgs(@Nullable String s,
@javax.annotation.Nullable Integer i) {}
public void twoNullableArgsThrowsFirstArg(
@Nullable String s, @Nullable Integer i) {
doThrow(s);
}
public void twoNullableArgsThrowsSecondArg(
@Nullable String s, @Nullable Integer i) {
doThrow(i);
}
public static void staticOneArg(String s) { checkNotNull(s); }
public static void staticOneNullableArg(@Nullable String s) {}
public static void staticOneNullableArgThrows(@Nullable String s) {
doThrow(s);
}
}
public void testGoodClass() {
shouldPass(new PassObject());
}
private static class FailOneArgDoesntThrowNPE extends PassObject {
@Override public void oneArg(String s) {
// Fail: missing NPE for s
}
}
public void testFailOneArgDoesntThrowNpe() {
shouldFail(new FailOneArgDoesntThrowNPE());
}
private static class FailOneArgThrowsWrongType extends PassObject {
@Override public void oneArg(String s) {
doThrow(s); // Fail: throwing non-NPE exception for null s
}
}
public void testFailOneArgThrowsWrongType() {
shouldFail(new FailOneArgThrowsWrongType());
}
private static class PassOneNullableArgThrowsNPE extends PassObject {
@Override public void oneNullableArg(@Nullable String s) {
checkNotNull(s); // ok to throw NPE
}
}
public void testPassOneNullableArgThrowsNPE() {
shouldPass(new PassOneNullableArgThrowsNPE());
}
private static class FailTwoArgsFirstArgDoesntThrowNPE extends PassObject {
@Override public void twoArg(String s, Integer i) {
// Fail: missing NPE for s
i.intValue();
}
}
public void testFailTwoArgsFirstArgDoesntThrowNPE() {
shouldFail(new FailTwoArgsFirstArgDoesntThrowNPE());
}
private static class FailTwoArgsFirstArgThrowsWrongType extends PassObject {
@Override public void twoArg(String s, Integer i) {
doThrow(s); // Fail: throwing non-NPE exception for null s
i.intValue();
}
}
public void testFailTwoArgsFirstArgThrowsWrongType() {
shouldFail(new FailTwoArgsFirstArgThrowsWrongType());
}
private static class FailTwoArgsSecondArgDoesntThrowNPE extends PassObject {
@Override public void twoArg(String s, Integer i) {
checkNotNull(s);
// Fail: missing NPE for i
}
}
public void testFailTwoArgsSecondArgDoesntThrowNPE() {
shouldFail(new FailTwoArgsSecondArgDoesntThrowNPE());
}
private static class FailTwoArgsSecondArgThrowsWrongType extends PassObject {
@Override public void twoArg(String s, Integer i) {
checkNotNull(s);
doThrow(i); // Fail: throwing non-NPE exception for null i
}
}
public void testFailTwoArgsSecondArgThrowsWrongType() {
shouldFail(new FailTwoArgsSecondArgThrowsWrongType());
}
private static class FailTwoMixedArgsFirstArgDoesntThrowNPE
extends PassObject {
@Override public void twoMixedArgs(String s, @Nullable Integer i) {
// Fail: missing NPE for s
}
}
public void testFailTwoMixedArgsFirstArgDoesntThrowNPE() {
shouldFail(new FailTwoMixedArgsFirstArgDoesntThrowNPE());
}
private static class FailTwoMixedArgsFirstArgThrowsWrongType
extends PassObject {
@Override public void twoMixedArgs(String s, @Nullable Integer i) {
doThrow(s); // Fail: throwing non-NPE exception for null s
}
}
public void testFailTwoMixedArgsFirstArgThrowsWrongType() {
shouldFail(new FailTwoMixedArgsFirstArgThrowsWrongType());
}
private static class PassTwoMixedArgsNullableArgThrowsNPE extends PassObject {
@Override public void twoMixedArgs(String s, @Nullable Integer i) {
checkNotNull(s);
i.intValue(); // ok to throw NPE?
}
}
public void testPassTwoMixedArgsNullableArgThrowsNPE() {
shouldPass(new PassTwoMixedArgsNullableArgThrowsNPE());
}
private static class PassTwoMixedArgSecondNullableArgThrowsOther
extends PassObject {
@Override public void twoMixedArgs(String s, @Nullable Integer i) {
checkNotNull(s);
doThrow(i); // ok to throw non-NPE exception for null i
}
}
public void testPassTwoMixedArgSecondNullableArgThrowsOther() {
shouldPass(new PassTwoMixedArgSecondNullableArgThrowsOther());
}
private static class FailTwoMixedArgsSecondArgDoesntThrowNPE
extends PassObject {
@Override public void twoMixedArgs(@Nullable Integer i, String s) {
// Fail: missing NPE for null s
}
}
public void testFailTwoMixedArgsSecondArgDoesntThrowNPE() {
shouldFail(new FailTwoMixedArgsSecondArgDoesntThrowNPE());
}
private static class FailTwoMixedArgsSecondArgThrowsWrongType
extends PassObject {
@Override public void twoMixedArgs(@Nullable Integer i, String s) {
doThrow(s); // Fail: throwing non-NPE exception for null s
}
}
public void testFailTwoMixedArgsSecondArgThrowsWrongType() {
shouldFail(new FailTwoMixedArgsSecondArgThrowsWrongType());
}
private static class PassTwoNullableArgsFirstThrowsNPE extends PassObject {
@Override public void twoNullableArgs(
@Nullable String s, @Nullable Integer i) {
checkNotNull(s); // ok to throw NPE?
}
}
public void testPassTwoNullableArgsFirstThrowsNPE() {
shouldPass(new PassTwoNullableArgsFirstThrowsNPE());
}
private static class PassTwoNullableArgsFirstThrowsOther extends PassObject {
@Override public void twoNullableArgs(
@Nullable String s, @Nullable Integer i) {
doThrow(s); // ok to throw non-NPE exception for null s
}
}
public void testPassTwoNullableArgsFirstThrowsOther() {
shouldPass(new PassTwoNullableArgsFirstThrowsOther());
}
private static class PassTwoNullableArgsSecondThrowsNPE extends PassObject {
@Override public void twoNullableArgs(
@Nullable String s, @Nullable Integer i) {
i.intValue(); // ok to throw NPE?
}
}
public void testPassTwoNullableArgsSecondThrowsNPE() {
shouldPass(new PassTwoNullableArgsSecondThrowsNPE());
}
private static class PassTwoNullableArgsSecondThrowsOther extends PassObject {
@Override public void twoNullableArgs(
@Nullable String s, @Nullable Integer i) {
doThrow(i); // ok to throw non-NPE exception for null i
}
}
public void testPassTwoNullableArgsSecondThrowsOther() {
shouldPass(new PassTwoNullableArgsSecondThrowsOther());
}
private static class PassTwoNullableArgsNeitherThrowsAnything
extends PassObject {
@Override public void twoNullableArgs(
@Nullable String s, @Nullable Integer i) {
// ok to do nothing
}
}
public void testPassTwoNullableArgsNeitherThrowsAnything() {
shouldPass(new PassTwoNullableArgsNeitherThrowsAnything());
}
@SuppressWarnings("unused") // for NullPointerTester
private static abstract class BaseClassThatFailsToThrow {
public void oneArg(String s) {}
}
private static class SubclassWithBadSuperclass
extends BaseClassThatFailsToThrow {}
public void testSubclassWithBadSuperclass() {
shouldFail(new SubclassWithBadSuperclass());
}
@SuppressWarnings("unused") // for NullPointerTester
private static abstract class BaseClassThatFailsToThrowForPackagePrivate {
void packagePrivateOneArg(String s) {}
}
private static class SubclassWithBadSuperclassForPackagePrivate
extends BaseClassThatFailsToThrowForPackagePrivate {}
public void testSubclassWithBadSuperclassForPackagePrivateMethod() {
shouldFail(
new SubclassWithBadSuperclassForPackagePrivate(), Visibility.PACKAGE);
}
@SuppressWarnings("unused") // for NullPointerTester
private static abstract class BaseClassThatFailsToThrowForProtected {
protected void protectedOneArg(String s) {}
}
private static class SubclassWithBadSuperclassForProtected
extends BaseClassThatFailsToThrowForProtected {}
public void testSubclassWithBadSuperclassForPackageProtectedMethod() {
shouldFail(
new SubclassWithBadSuperclassForProtected(), Visibility.PROTECTED);
}
private static class SubclassThatOverridesBadSuperclassMethod
extends BaseClassThatFailsToThrow {
@Override public void oneArg(@Nullable String s) {}
}
public void testSubclassThatOverridesBadSuperclassMethod() {
shouldPass(new SubclassThatOverridesBadSuperclassMethod());
}
@SuppressWarnings("unused") // for NullPointerTester
private static class SubclassOverridesTheWrongMethod
extends BaseClassThatFailsToThrow {
public void oneArg(@Nullable CharSequence s) {}
}
public void testSubclassOverridesTheWrongMethod() {
shouldFail(new SubclassOverridesTheWrongMethod());
}
@SuppressWarnings("unused") // for NullPointerTester
private static class ClassThatFailsToThrowForStatic {
static void staticOneArg(String s) {}
}
public void testClassThatFailsToThrowForStatic() {
shouldFail(ClassThatFailsToThrowForStatic.class);
}
private static class SubclassThatFailsToThrowForStatic
extends ClassThatFailsToThrowForStatic {}
public void testSubclassThatFailsToThrowForStatic() {
shouldFail(SubclassThatFailsToThrowForStatic.class);
}
private static class SubclassThatTriesToOverrideBadStaticMethod
extends ClassThatFailsToThrowForStatic {
static void staticOneArg(@Nullable String s) {}
}
public void testSubclassThatTriesToOverrideBadStaticMethod() {
shouldFail(SubclassThatTriesToOverrideBadStaticMethod.class);
}
private static final class HardToCreate {
private HardToCreate(HardToCreate x) {}
}
@SuppressWarnings("unused") // used by reflection
private static class CanCreateDefault {
public void foo(@Nullable HardToCreate ignored, String required) {
checkNotNull(required);
}
}
public void testCanCreateDefault() {
shouldPass(new CanCreateDefault());
}
@SuppressWarnings("unused") // used by reflection
private static class CannotCreateDefault {
public void foo(HardToCreate ignored, String required) {
checkNotNull(ignored);
checkNotNull(required);
}
}
public void testCannotCreateDefault() {
shouldFail(new CannotCreateDefault());
}
private static void shouldPass(Object instance, Visibility visibility) {
new NullPointerTester().testInstanceMethods(instance, visibility);
}
private static void shouldPass(Object instance) {
shouldPass(instance, Visibility.PACKAGE);
shouldPass(instance, Visibility.PROTECTED);
shouldPass(instance, Visibility.PUBLIC);
}
// TODO(cpovirk): eliminate surprising Object/Class overloading of shouldFail
private static void shouldFail(Object instance, Visibility visibility) {
try {
new NullPointerTester().testInstanceMethods(instance, visibility);
} catch (AssertionFailedError expected) {
return;
}
fail("Should detect problem in " + instance.getClass().getSimpleName());
}
private static void shouldFail(Object instance) {
shouldFail(instance, Visibility.PACKAGE);
shouldFail(instance, Visibility.PROTECTED);
shouldFail(instance, Visibility.PUBLIC);
}
private static void shouldFail(Class<?> cls, Visibility visibility) {
try {
new NullPointerTester().testStaticMethods(cls, visibility);
} catch (AssertionFailedError expected) {
return;
}
fail("Should detect problem in " + cls.getSimpleName());
}
private static void shouldFail(Class<?> cls) {
shouldFail(cls, Visibility.PACKAGE);
}
@SuppressWarnings("unused") // used by reflection
private static class PrivateClassWithPrivateConstructor {
private PrivateClassWithPrivateConstructor(@Nullable Integer argument) {}
}
public void testPrivateClass() {
NullPointerTester tester = new NullPointerTester();
for (Constructor<?> constructor
: PrivateClassWithPrivateConstructor.class.getDeclaredConstructors()) {
tester.testConstructor(constructor);
}
}
private interface Foo<T> {
void doSomething(T bar, Integer baz);
}
private static class StringFoo implements Foo<String> {
@Override public void doSomething(String bar, Integer baz) {
checkNotNull(bar);
checkNotNull(baz);
}
}
public void testBridgeMethodIgnored() {
new NullPointerTester().testAllPublicInstanceMethods(new StringFoo());
}
private static abstract class DefaultValueChecker {
private final Map<Integer, Object> arguments = Maps.newHashMap();
final DefaultValueChecker runTester() {
new NullPointerTester()
.testInstanceMethods(this, Visibility.PACKAGE);
return this;
}
final void assertNonNullValues(Object... expectedValues) {
assertEquals(expectedValues.length, arguments.size());
for (int i = 0; i < expectedValues.length; i++) {
assertEquals("Default value for parameter #" + i,
expectedValues[i], arguments.get(i));
}
}
final Object getDefaultParameterValue(int position) {
return arguments.get(position);
}
final void calledWith(Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
arguments.put(i, args[i]);
}
}
for (Object arg : args) {
checkNotNull(arg); // to fulfill null check
}
}
}
private enum Gender {
MALE, FEMALE
}
private static class AllDefaultValuesChecker extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkDefaultValuesForTheseTypes(
Gender gender,
Integer integer, int i,
String string, CharSequence charSequence,
List<String> list,
ImmutableList<Integer> immutableList,
Map<String, Integer> map,
ImmutableMap<String, String> immutableMap,
Set<String> set,
ImmutableSet<Integer> immutableSet,
SortedSet<Number> sortedSet,
ImmutableSortedSet<Number> immutableSortedSet,
Multiset<String> multiset,
ImmutableMultiset<Integer> immutableMultiset,
Multimap<String, Integer> multimap,
ImmutableMultimap<String, Integer> immutableMultimap,
Table<String, Integer, Exception> table,
ImmutableTable<Integer, String, Exception> immutableTable) {
calledWith(
gender,
integer, i,
string, charSequence,
list, immutableList,
map, immutableMap,
set, immutableSet,
sortedSet, immutableSortedSet,
multiset, immutableMultiset,
multimap, immutableMultimap,
table, immutableTable);
}
final void check() {
runTester().assertNonNullValues(
Gender.MALE,
Integer.valueOf(0), 0,
"", "",
ImmutableList.of(), ImmutableList.of(),
ImmutableMap.of(), ImmutableMap.of(),
ImmutableSet.of(), ImmutableSet.of(),
ImmutableSortedSet.of(), ImmutableSortedSet.of(),
ImmutableMultiset.of(), ImmutableMultiset.of(),
ImmutableMultimap.of(), ImmutableMultimap.of(),
ImmutableTable.of(), ImmutableTable.of());
}
}
public void testDefaultValues() {
new AllDefaultValuesChecker().check();
}
private static class ObjectArrayDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(Object[] array, String s) {
calledWith(array, s);
}
void check() {
runTester();
Object[] defaultArray = (Object[]) getDefaultParameterValue(0);
assertEquals(0, defaultArray.length);
}
}
public void testObjectArrayDefaultValue() {
new ObjectArrayDefaultValueChecker().check();
}
private static class StringArrayDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(String[] array, String s) {
calledWith(array, s);
}
void check() {
runTester();
String[] defaultArray = (String[]) getDefaultParameterValue(0);
assertEquals(0, defaultArray.length);
}
}
public void testStringArrayDefaultValue() {
new StringArrayDefaultValueChecker().check();
}
private static class IntArrayDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(int[] array, String s) {
calledWith(array, s);
}
void check() {
runTester();
int[] defaultArray = (int[]) getDefaultParameterValue(0);
assertEquals(0, defaultArray.length);
}
}
public void testIntArrayDefaultValue() {
new IntArrayDefaultValueChecker().check();
}
private enum EmptyEnum {}
private static class EmptyEnumDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(EmptyEnum object, String s) {
calledWith(object, s);
}
void check() {
try {
runTester();
} catch (AssertionError expected) {
return;
}
fail("Should have failed because enum has no constant");
}
}
public void testEmptyEnumDefaultValue() {
new EmptyEnumDefaultValueChecker().check();
}
private static class GenericClassTypeDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(Class<? extends List<?>> cls, String s) {
calledWith(cls, s);
}
void check() {
runTester();
Class<?> defaultClass = (Class<?>) getDefaultParameterValue(0);
assertEquals(List.class, defaultClass);
}
}
public void testGenericClassDefaultValue() {
new GenericClassTypeDefaultValueChecker().check();
}
private static class NonGenericClassTypeDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(@SuppressWarnings("rawtypes") Class cls, String s) {
calledWith(cls, s);
}
void check() {
runTester();
Class<?> defaultClass = (Class<?>) getDefaultParameterValue(0);
assertEquals(Object.class, defaultClass);
}
}
public void testNonGenericClassDefaultValue() {
new NonGenericClassTypeDefaultValueChecker().check();
}
private static class GenericTypeTokenDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(
TypeToken<? extends List<? super Number>> type, String s) {
calledWith(type, s);
}
void check() {
runTester();
TypeToken<?> defaultType = (TypeToken<?>) getDefaultParameterValue(0);
assertTrue(new TypeToken<List<? super Number>>() {}
.isAssignableFrom(defaultType));
}
}
public void testGenericTypeTokenDefaultValue() {
new GenericTypeTokenDefaultValueChecker().check();
}
private static class NonGenericTypeTokenDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(
@SuppressWarnings("rawtypes") TypeToken type, String s) {
calledWith(type, s);
}
void check() {
runTester();
TypeToken<?> defaultType = (TypeToken<?>) getDefaultParameterValue(0);
assertEquals(new TypeToken<Object>() {}, defaultType);
}
}
public void testNonGenericTypeTokenDefaultValue() {
new NonGenericTypeTokenDefaultValueChecker().check();
}
private interface FromTo<F, T> extends Function<F, T> {}
private static class GenericInterfaceDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(FromTo<String, Integer> f, String s) {
calledWith(f, s);
}
void check() {
runTester();
FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0);
assertEquals(0, defaultFunction.apply(null));
}
}
public void testGenericInterfaceDefaultValue() {
new GenericInterfaceDefaultValueChecker().check();
}
private interface NullRejectingFromTo<F, T> extends Function<F, T> {
@Override public abstract T apply(F from);
}
private static class NullRejectingInterfaceDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(NullRejectingFromTo<String, Integer> f, String s) {
calledWith(f, s);
}
void check() {
runTester();
NullRejectingFromTo<?, ?> defaultFunction = (NullRejectingFromTo<?, ?>)
getDefaultParameterValue(0);
assertNotNull(defaultFunction);
try {
defaultFunction.apply(null);
fail("Proxy Should have rejected null");
} catch (NullPointerException expected) {}
}
}
public void testNullRejectingInterfaceDefaultValue() {
new NullRejectingInterfaceDefaultValueChecker().check();
}
private static class MultipleInterfacesDefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public <T extends FromTo<String, Integer> & Supplier<Long>> void checkArray(
T f, String s) {
calledWith(f, s);
}
void check() {
runTester();
FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0);
assertEquals(0, defaultFunction.apply(null));
Supplier<?> defaultSupplier = (Supplier<?>) defaultFunction;
assertEquals(Long.valueOf(0), defaultSupplier.get());
}
}
public void testMultipleInterfacesDefaultValue() {
new MultipleInterfacesDefaultValueChecker().check();
}
private static class GenericInterface2DefaultValueChecker
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkArray(FromTo<String, FromTo<Integer, String>> f, String s) {
calledWith(f, s);
}
void check() {
runTester();
FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0);
FromTo<?, ?> returnValue = (FromTo<?, ?>) defaultFunction.apply(null);
assertEquals("", returnValue.apply(null));
}
}
public void tesGenericInterfaceReturnedByGenericMethod() {
new GenericInterface2DefaultValueChecker().check();
}
private static abstract class AbstractGenericDefaultValueChecker<T>
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
public void checkGeneric(T value, String s) {
calledWith(value, s);
}
}
private static class GenericDefaultValueResolvedToStringChecker
extends AbstractGenericDefaultValueChecker<String> {
void check() {
runTester();
assertEquals("", getDefaultParameterValue(0));
}
}
public void testGenericTypeResolvedForDefaultValue() {
new GenericDefaultValueResolvedToStringChecker().check();
}
private static abstract
class AbstractGenericDefaultValueForPackagePrivateMethodChecker<T>
extends DefaultValueChecker {
@SuppressWarnings("unused") // called by NullPointerTester
void checkGeneric(T value, String s) {
calledWith(value, s);
}
}
private static
class DefaultValueForPackagePrivateMethodResolvedToStringChecker
extends AbstractGenericDefaultValueForPackagePrivateMethodChecker<String>
{
void check() {
runTester();
assertEquals("", getDefaultParameterValue(0));
}
}
public void testDefaultValueResolvedForPackagePrivateMethod() {
new DefaultValueForPackagePrivateMethodResolvedToStringChecker().check();
}
private static class VisibilityMethods {
@SuppressWarnings("unused") // Called by reflection
private void privateMethod() {}
@SuppressWarnings("unused") // Called by reflection
void packagePrivateMethod() {}
@SuppressWarnings("unused") // Called by reflection
protected void protectedMethod() {}
@SuppressWarnings("unused") // Called by reflection
public void publicMethod() {}
}
public void testVisibility_public() throws Exception {
assertFalse(Visibility.PUBLIC.isVisible(
VisibilityMethods.class.getDeclaredMethod("privateMethod")));
assertFalse(Visibility.PUBLIC.isVisible(
VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod")));
assertFalse(Visibility.PUBLIC.isVisible(
VisibilityMethods.class.getDeclaredMethod("protectedMethod")));
assertTrue(Visibility.PUBLIC.isVisible(
VisibilityMethods.class.getDeclaredMethod("publicMethod")));
}
public void testVisibility_protected() throws Exception {
assertFalse(Visibility.PROTECTED.isVisible(
VisibilityMethods.class.getDeclaredMethod("privateMethod")));
assertFalse(Visibility.PROTECTED.isVisible(
VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod")));
assertTrue(Visibility.PROTECTED.isVisible(
VisibilityMethods.class.getDeclaredMethod("protectedMethod")));
assertTrue(Visibility.PROTECTED.isVisible(
VisibilityMethods.class.getDeclaredMethod("publicMethod")));
}
public void testVisibility_package() throws Exception {
assertFalse(Visibility.PACKAGE.isVisible(
VisibilityMethods.class.getDeclaredMethod("privateMethod")));
assertTrue(Visibility.PACKAGE.isVisible(
VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod")));
assertTrue(Visibility.PACKAGE.isVisible(
VisibilityMethods.class.getDeclaredMethod("protectedMethod")));
assertTrue(Visibility.PACKAGE.isVisible(
VisibilityMethods.class.getDeclaredMethod("publicMethod")));
}
private class Inner {
public Inner(String s) {
checkNotNull(s);
}
}
public void testNonStaticInnerClass() {
try {
new NullPointerTester().testAllPublicConstructors(Inner.class);
fail();
} catch (IllegalArgumentException expected) {
ASSERT.that(expected.getMessage()).contains("inner class");
}
}
}
| {
"content_hash": "4d0659f86ed1aeec162416eb443cbaf4",
"timestamp": "",
"source": "github",
"line_count": 1236,
"max_line_length": 84,
"avg_line_length": 32.050970873786405,
"alnum_prop": 0.7042029534267323,
"repo_name": "sensui/guava-libraries",
"id": "b051b1758538a4bdf8e3692759b84f8fc8778964",
"size": "40215",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "12917794"
},
{
"name": "Shell",
"bytes": "1443"
}
],
"symlink_target": ""
} |
import os
import sys
from utdirect.utils import setup_extra
# If you use an 'extra' folder with svn externals, uncomment the following lines:
#CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
#setup_extra(os.path.join(CURRENT_DIR, 'extra'))
import settings
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
try: #This should never be on the python path.
sys.path.remove(os.path.dirname(os.path.abspath(__file__)))
except:
pass
execute_from_command_line(sys.argv)
| {
"content_hash": "6b862ccd433a08086e10063394ddb7db",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 81,
"avg_line_length": 32.10526315789474,
"alnum_prop": 0.7016393442622951,
"repo_name": "jeffles/LI",
"id": "276060fd6e6f04dc1e3f2a462089afca05621c54",
"size": "632",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "manage.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "76593"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Resources;
// 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("Cirrious.Plugins.MethodBinding")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cirrious")]
[assembly: AssemblyProduct("Cirrious.Plugins.MethodBinding")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")] | {
"content_hash": "90d1753899c0e0ebf614c4e3bef9b957",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 83,
"avg_line_length": 37.17857142857143,
"alnum_prop": 0.7454370797310279,
"repo_name": "martijn00/MvvmCross-Plugins",
"id": "3229e459cc47414164dabe048ad4c6addbc6af0f",
"size": "1044",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "MethodBinding/MvvmCross.Plugins.MethodBinding/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5207"
},
{
"name": "C#",
"bytes": "763731"
},
{
"name": "Pascal",
"bytes": "11208"
},
{
"name": "PowerShell",
"bytes": "4320"
},
{
"name": "Puppet",
"bytes": "236"
}
],
"symlink_target": ""
} |
// fCraft is Copyright 2009-2012 Matvei Stefarov <[email protected]>
// original TorusDrawOperation written and contributed by M1_Abrams
using System;
using System.Collections.Generic;
namespace fCraft.Drawing {
public sealed class TorusDrawOperation : DrawOperation {
const float Bias = 0.5f;
Vector3I center;
int tubeR;
double bigR;
public override string Name {
get { return "Torus"; }
}
public TorusDrawOperation( Player player )
: base( player ) {
}
public override bool Prepare( Vector3I[] marks ) {
if( !base.Prepare( marks ) ) return false;
// center of the torus
center = marks[0];
Vector3I radiusVector = (marks[1] - center).Abs();
// tube radius is figured out from Z component of the mark vector
tubeR = radiusVector.Z;
// torus radius is figured out from length of vector's X-Y components
bigR = Math.Sqrt( radiusVector.X * radiusVector.X +
radiusVector.Y * radiusVector.Y + .5 );
// tube + torus radius, rounded up. This will be the maximum extend of the torus.
int combinedRadius = (int)Math.Ceiling( bigR + tubeR );
// vector from center of torus to the furthest-away point of the bounding box
Vector3I combinedRadiusVector = new Vector3I( combinedRadius, combinedRadius, tubeR + 1 );
// adjusted bounding box
Bounds = new BoundingBox( center - combinedRadiusVector, center + combinedRadiusVector );
BlocksTotalEstimate = (int)(2 * Math.PI * Math.PI * bigR * (tubeR * tubeR + Bias));
coordEnumerator = BlockEnumerator().GetEnumerator();
return true;
}
IEnumerator<Vector3I> coordEnumerator;
public override int DrawBatch( int maxBlocksToDraw ) {
int blocksDone = 0;
while( coordEnumerator.MoveNext() ) {
Coords = coordEnumerator.Current;
if( DrawOneBlock() ) {
blocksDone++;
if( blocksDone >= maxBlocksToDraw ) return blocksDone;
}
if( TimeToEndBatch ) return blocksDone;
}
IsDone = true;
return blocksDone;
}
IEnumerable<Vector3I> BlockEnumerator() {
for( int x = Bounds.XMin; x <= Bounds.XMax; x++ ) {
for( int y = Bounds.YMin; y <= Bounds.YMax; y++ ) {
for( int z = Bounds.ZMin; z <= Bounds.ZMax; z++ ) {
double dx = (x - center.X);
double dy = (y - center.Y);
double dz = (z - center.Z);
// test if it's inside the torus
double r1 = bigR - Math.Sqrt( dx * dx + dy * dy );
if( r1 * r1 + dz * dz <= tubeR * tubeR + Bias ) {
yield return new Vector3I( x, y, z );
}
}
}
}
}
}
} | {
"content_hash": "32a1b38f63b2c227e6e53c46e6a71a52",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 102,
"avg_line_length": 35.81818181818182,
"alnum_prop": 0.5206218274111675,
"repo_name": "DingusBungus/LegendCraft-RPG",
"id": "7f31ec92cc6cd02091e7c4d5d0a0c3d4fee4bef6",
"size": "3154",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "fCraft/Drawing/DrawOps/TorusDrawOperation.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3400656"
},
{
"name": "Lua",
"bytes": "3539"
},
{
"name": "Python",
"bytes": "3344"
}
],
"symlink_target": ""
} |
<?php
final class PhutilAWSException extends Exception {
private $httpStatus;
private $requestID;
public function __construct($http_status, array $params) {
$this->httpStatus = $http_status;
$this->requestID = idx($params, 'RequestID');
$this->params = $params;
$desc = array();
$desc[] = pht('AWS Request Failed');
$desc[] = pht('HTTP Status Code: %d', $http_status);
if ($this->requestID) {
$desc[] = pht('AWS Request ID: %s', $this->requestID);
$errors = idx($params, 'Errors');
if ($errors) {
$desc[] = pht('AWS Errors:');
foreach ($errors as $error) {
list($code, $message) = $error;
$desc[] = " - {$code}: {$message}\n";
}
}
} else {
$desc[] = pht('Response Body: %s', idx($params, 'body'));
}
$desc = implode("\n", $desc);
parent::__construct($desc);
}
public function getRequestID() {
return $this->requestID;
}
public function getHTTPStatus() {
return $this->httpStatus;
}
}
| {
"content_hash": "d4dbee04157bdf4e79d139794e8f8ca4",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 63,
"avg_line_length": 23.11111111111111,
"alnum_prop": 0.55,
"repo_name": "memsql/libphutil",
"id": "d48abf2080bf6f9038bc3b93f61e871f54d165a3",
"size": "1040",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "src/future/aws/PhutilAWSException.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "2069390"
},
{
"name": "Lex",
"bytes": "11600"
},
{
"name": "Makefile",
"bytes": "1579"
},
{
"name": "PHP",
"bytes": "1441072"
},
{
"name": "Shell",
"bytes": "40"
},
{
"name": "Yacc",
"bytes": "60590"
}
],
"symlink_target": ""
} |
<?php
namespace Chamilo\Core\Repository\ContentObject\Blog\Display\Component;
use Chamilo\Core\Repository\ContentObject\Blog\Display\Manager;
use Chamilo\Libraries\Architecture\Application\ApplicationConfiguration;
use Chamilo\Libraries\Architecture\Interfaces\DelegateComponent;
/**
*
* @package repository.lib.complex_builder.blog.component
*/
class CreatorComponent extends Manager implements DelegateComponent
{
public function run()
{
return $this->getApplicationFactory()->getApplication(
\Chamilo\Core\Repository\Display\Action\Manager::context(),
new ApplicationConfiguration($this->getRequest(), $this->get_user(), $this))->run();
}
}
| {
"content_hash": "65ce8cf07c202389567f6bc65eaec773",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 96,
"avg_line_length": 33.04761904761905,
"alnum_prop": 0.7536023054755043,
"repo_name": "forelo/cosnics",
"id": "cea44f4e34301bbbbca7dc51cc055b4a49914ded",
"size": "694",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Chamilo/Core/Repository/ContentObject/Blog/Display/Component/CreatorComponent.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "262730"
},
{
"name": "C",
"bytes": "12354"
},
{
"name": "CSS",
"bytes": "1334431"
},
{
"name": "CoffeeScript",
"bytes": "41023"
},
{
"name": "Gherkin",
"bytes": "24033"
},
{
"name": "HTML",
"bytes": "1016812"
},
{
"name": "Hack",
"bytes": "424"
},
{
"name": "JavaScript",
"bytes": "10768095"
},
{
"name": "Less",
"bytes": "331253"
},
{
"name": "Makefile",
"bytes": "3221"
},
{
"name": "PHP",
"bytes": "23623996"
},
{
"name": "Python",
"bytes": "2408"
},
{
"name": "Ruby",
"bytes": "618"
},
{
"name": "SCSS",
"bytes": "163532"
},
{
"name": "Shell",
"bytes": "7965"
},
{
"name": "Smarty",
"bytes": "15750"
},
{
"name": "Twig",
"bytes": "388197"
},
{
"name": "TypeScript",
"bytes": "123212"
},
{
"name": "Vue",
"bytes": "454138"
},
{
"name": "XSLT",
"bytes": "43009"
}
],
"symlink_target": ""
} |
'''
File: statistics.py
Author: Oliver Zscheyge
Description:
Collection of statistics functions.
'''
import math
def mean(values, ndigits=None):
"""
Return:
Mean of values, rounded to ndigits.
"""
n = len(values)
if n == 0:
raise ValueError(u"Can't compute mean over empty list!")
su = math.fsum(values)
if ndigits is not None:
return round(su / float(n), ndigits)
return su / float(n)
def variance(values, ndigits=None):
"""
Args:
values: List of at least 2 values.
Return:
Variance of a list of values, rounded to ndigits.
"""
n = len(values)
if n < 2:
raise ValueError(u"Can't compute variance over less than 2 values.")
mean = math.fsum(values) / float(n)
var = math.fsum([(v - mean) * (v - mean) for v in values])
if ndigits is not None:
return round(var / float(n), ndigits)
return var / float(n)
def stdev(values, ndigits=None):
"""
Args:
values: List of at least 2 values.
Return:
Standard deviation of a list of values, rounded to ndigits.
"""
n = len(values)
if n < 2:
raise ValueError(u"Can't compute standard deviation over less than 2 values.")
mean = math.fsum(values) / float(n)
var = math.fsum([(v - mean) * (v - mean) for v in values]) / float(n)
if ndigits is not None:
return round(math.sqrt(var), ndigits)
return math.sqrt(var)
def mean_stdev(values, ndigits=None):
"""
Args:
values: List of at least 2 values.
Return:
(mean, standard deviation) tuple of a list of values, rounded to ndigits.
"""
n = len(values)
if n < 2:
raise ValueError(u"Can't compute variance/standard deviation over less than 2 values.")
mean = math.fsum(values) / float(n)
sd = math.sqrt(math.fsum([(v - mean) * (v - mean) for v in values]) / float(n))
if ndigits is not None:
return (round(mean, ndigits), round(sd, ndigits))
return (mean, sd)
if __name__ == '__main__':
print u"Test for %s" % __file__
values = range(10)
def assert_raises(fun, arg, msg):
try:
res = fun(arg)
assert False, msg
except ValueError:
pass
print u" Testing mean and variance..."
m = mean(values)
var = variance(values)
assert m == 4.5
assert var == 8.25
assert_raises(mean, [], u"Mean of empty list did not fail properly!")
assert_raises(variance, [], u"Variance of empty list did not fail properly!")
assert_raises(variance, [42], u"Variance of 1 element list did not fail properly!")
print u" Testing stdev and mean_stdev..."
sv = stdev(values)
(mean2, stdev2) = mean_stdev(values)
assert sv == math.sqrt(var)
assert m == mean2
assert sv == stdev2
assert_raises(stdev, [], u"Stdev of empty list did not fail!")
assert_raises(stdev, [42], u"Stdev of 1 element list did not fail!")
assert_raises(mean_stdev, [], u"Mean_stdev of empty list did not fail!")
assert_raises(mean_stdev, [42], u"Mean_stdev of 1 element list did not fail!")
print u" Testing mean_stdev rounding..."
stats_rounded = mean_stdev(values, 2)
assert stats_rounded == (4.5, 2.87)
print u"Passed all tests!"
| {
"content_hash": "03266651e910dd3fc4d519ec74214fb6",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 95,
"avg_line_length": 29.4375,
"alnum_prop": 0.6060054595086443,
"repo_name": "ooz/Confopy",
"id": "1bcf618b8baf446984bfce0d820c06c28cde07e5",
"size": "3313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "confopy/analysis/statistics.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "182874"
},
{
"name": "Shell",
"bytes": "426"
}
],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
@SuppressWarnings("rawtypes")
public class Prayer_AuraIntolerance extends Prayer
{
@Override public String ID() { return "Prayer_AuraIntolerance"; }
private final static String localizedName = CMLib.lang()._("Aura of Intolerance");
@Override public String name() { return localizedName; }
private final static String localizedStaticDisplay = CMLib.lang()._("(Intolerance Aura)");
@Override public String displayText() { return localizedStaticDisplay; }
@Override protected int canAffectCode(){return Ability.CAN_MOBS;}
@Override protected int canTargetCode(){return 0;}
@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_COMMUNING;}
@Override public int abstractQuality(){ return Ability.QUALITY_BENEFICIAL_SELF;}
@Override public long flags(){return Ability.FLAG_HOLY;}
@Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB M=(MOB)affected;
super.unInvoke();
if((canBeUninvoked())&&(M!=null)&&(!M.amDead())&&(M.location()!=null))
M.location().show(M,null,CMMsg.MSG_OK_VISUAL,_("The intolerant aura around <S-NAME> fades."));
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(!(affected instanceof MOB))
return true;
if((msg.source()==affected)
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&(msg.target() instanceof MOB)
&&(msg.source().getWorshipCharID().length()>0)
&&(!((MOB)msg.target()).getWorshipCharID().equals(msg.source().getWorshipCharID())))
{
if(((MOB)msg.target()).getWorshipCharID().length()>0)
msg.setValue(msg.value()*2);
else
msg.setValue(msg.value()+(msg.value()/2));
}
return true;
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!(affected instanceof MOB))
return super.tick(ticking,tickID);
if(!super.tick(ticking,tickID))
return false;
final Room R=((MOB)affected).location();
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M!=null)
&&(M!=((MOB)affected))
&&((M.getWorshipCharID().length()==0)
||(((MOB)affected).getWorshipCharID().length()>0)&&(!M.getWorshipCharID().equals(((MOB)affected).getWorshipCharID()))))
{
if(M.getWorshipCharID().length()>0)
CMLib.combat().postDamage(((MOB)affected),M,this,3,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_UNDEAD,Weapon.TYPE_BURSTING,"The intolerant aura around <S-NAME> <DAMAGES> <T-NAMESELF>!");
else
CMLib.combat().postDamage(((MOB)affected),M,this,1,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_UNDEAD,Weapon.TYPE_BURSTING,"The intolerant aura around <S-NAME> <DAMAGES> <T-NAMESELF>!");
if((!M.isInCombat())&&(M.isMonster())&&(M!=invoker)&&(invoker!=null)&&(M.location()==invoker.location())&&(M.location().isInhabitant(invoker))&&(CMLib.flags().canBeSeenBy(invoker,M)))
CMLib.combat().postAttack(M,invoker,M.fetchWieldedItem());
}
}
return true;
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if(((mob.getWorshipCharID().length()==0)
||(CMLib.map().getDeity(mob.getWorshipCharID())==null)))
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(ID())!=null)
{
mob.tell(target,null,null,_("The aura of intolerance is already with <S-NAME>."));
return false;
}
if((!auto)&&((mob.getWorshipCharID().length()==0)
||(CMLib.map().getDeity(mob.getWorshipCharID())==null)))
{
mob.tell(_("You must worship a god to be intolerant."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
// it worked, so build a copy of this ability,
// and add it to the affects list of the
// affected MOB. Then tell everyone else
// what happened.
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":_("^S<S-NAME> @x1 for the aura of intolerance.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,_("<S-NAME> @x1 for an aura of intolerance, but <S-HIS-HER> plea is not answered.",prayWord(mob)));
// return whether it worked
return success;
}
}
| {
"content_hash": "6a7b709165656084fc8c118f9bcf5b35",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 196,
"avg_line_length": 34.56603773584906,
"alnum_prop": 0.7045123726346434,
"repo_name": "vjanmey/EpicMudfia",
"id": "84d47accaa7888cc236da8804eb6eb7e075055c5",
"size": "6086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_AuraIntolerance.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1405"
},
{
"name": "Java",
"bytes": "23999316"
},
{
"name": "JavaScript",
"bytes": "23194"
},
{
"name": "Shell",
"bytes": "14255"
}
],
"symlink_target": ""
} |
using namespace std;
using namespace cv;
using namespace cv::gpu;
static Mat loadImage(const string& name)
{
Mat image = imread(name, IMREAD_GRAYSCALE);
if (image.empty())
{
cerr << "Can't load image - " << name << endl;
exit(-1);
}
return image;
}
int main(int argc, const char* argv[])
{
CommandLineParser cmd(argc, argv,
"{ i | image | pic1.png | input image }"
"{ t | template | templ.png | template image }"
"{ s | scale | | estimate scale }"
"{ r | rotation | | estimate rotation }"
"{ | gpu | | use gpu version }"
"{ | minDist | 100 | minimum distance between the centers of the detected objects }"
"{ | levels | 360 | R-Table levels }"
"{ | votesThreshold | 30 | the accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected }"
"{ | angleThresh | 10000 | angle votes treshold }"
"{ | scaleThresh | 1000 | scale votes treshold }"
"{ | posThresh | 100 | position votes threshold }"
"{ | dp | 2 | inverse ratio of the accumulator resolution to the image resolution }"
"{ | minScale | 0.5 | minimal scale to detect }"
"{ | maxScale | 2 | maximal scale to detect }"
"{ | scaleStep | 0.05 | scale step }"
"{ | minAngle | 0 | minimal rotation angle to detect in degrees }"
"{ | maxAngle | 360 | maximal rotation angle to detect in degrees }"
"{ | angleStep | 1 | angle step in degrees }"
"{ | maxSize | 1000 | maximal size of inner buffers }"
"{ h | help | | print help message }"
);
//cmd.about("This program demonstrates arbitary object finding with the Generalized Hough transform.");
if (cmd.get<bool>("help"))
{
cmd.printParams();
return 0;
}
const string templName = cmd.get<string>("template");
const string imageName = cmd.get<string>("image");
const bool estimateScale = cmd.get<bool>("scale");
const bool estimateRotation = cmd.get<bool>("rotation");
const bool useGpu = cmd.get<bool>("gpu");
const double minDist = cmd.get<double>("minDist");
const int levels = cmd.get<int>("levels");
const int votesThreshold = cmd.get<int>("votesThreshold");
const int angleThresh = cmd.get<int>("angleThresh");
const int scaleThresh = cmd.get<int>("scaleThresh");
const int posThresh = cmd.get<int>("posThresh");
const double dp = cmd.get<double>("dp");
const double minScale = cmd.get<double>("minScale");
const double maxScale = cmd.get<double>("maxScale");
const double scaleStep = cmd.get<double>("scaleStep");
const double minAngle = cmd.get<double>("minAngle");
const double maxAngle = cmd.get<double>("maxAngle");
const double angleStep = cmd.get<double>("angleStep");
const int maxSize = cmd.get<int>("maxSize");
Mat templ = loadImage(templName);
Mat image = loadImage(imageName);
int method = GHT_POSITION;
if (estimateScale)
method += GHT_SCALE;
if (estimateRotation)
method += GHT_ROTATION;
vector<Vec4f> position;
cv::TickMeter tm;
if (useGpu)
{
GpuMat d_templ(templ);
GpuMat d_image(image);
GpuMat d_position;
Ptr<GeneralizedHough_GPU> d_hough = GeneralizedHough_GPU::create(method);
d_hough->set("minDist", minDist);
d_hough->set("levels", levels);
d_hough->set("dp", dp);
d_hough->set("maxSize", maxSize);
if (estimateScale && estimateRotation)
{
d_hough->set("angleThresh", angleThresh);
d_hough->set("scaleThresh", scaleThresh);
d_hough->set("posThresh", posThresh);
}
else
{
d_hough->set("votesThreshold", votesThreshold);
}
if (estimateScale)
{
d_hough->set("minScale", minScale);
d_hough->set("maxScale", maxScale);
d_hough->set("scaleStep", scaleStep);
}
if (estimateRotation)
{
d_hough->set("minAngle", minAngle);
d_hough->set("maxAngle", maxAngle);
d_hough->set("angleStep", angleStep);
}
d_hough->setTemplate(d_templ);
tm.start();
d_hough->detect(d_image, d_position);
d_hough->download(d_position, position);
tm.stop();
}
else
{
Ptr<GeneralizedHough> hough = GeneralizedHough::create(method);
hough->set("minDist", minDist);
hough->set("levels", levels);
hough->set("dp", dp);
if (estimateScale && estimateRotation)
{
hough->set("angleThresh", angleThresh);
hough->set("scaleThresh", scaleThresh);
hough->set("posThresh", posThresh);
hough->set("maxSize", maxSize);
}
else
{
hough->set("votesThreshold", votesThreshold);
}
if (estimateScale)
{
hough->set("minScale", minScale);
hough->set("maxScale", maxScale);
hough->set("scaleStep", scaleStep);
}
if (estimateRotation)
{
hough->set("minAngle", minAngle);
hough->set("maxAngle", maxAngle);
hough->set("angleStep", angleStep);
}
hough->setTemplate(templ);
tm.start();
hough->detect(image, position);
tm.stop();
}
cout << "Found : " << position.size() << " objects" << endl;
cout << "Detection time : " << tm.getTimeMilli() << " ms" << endl;
Mat out;
cvtColor(image, out, COLOR_GRAY2BGR);
for (size_t i = 0; i < position.size(); ++i)
{
Point2f pos(position[i][0], position[i][1]);
float scale = position[i][2];
float angle = position[i][3];
RotatedRect rect;
rect.center = pos;
rect.size = Size2f(templ.cols * scale, templ.rows * scale);
rect.angle = angle;
Point2f pts[4];
rect.points(pts);
line(out, pts[0], pts[1], Scalar(0, 0, 255), 3);
line(out, pts[1], pts[2], Scalar(0, 0, 255), 3);
line(out, pts[2], pts[3], Scalar(0, 0, 255), 3);
line(out, pts[3], pts[0], Scalar(0, 0, 255), 3);
}
imshow("out", out);
waitKey();
return 0;
}
| {
"content_hash": "5476b5d19ff2867fb48f56dcded46148",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 181,
"avg_line_length": 34.35751295336787,
"alnum_prop": 0.5383803347911326,
"repo_name": "i4Ds/IRE",
"id": "6f12ad75dfbe0c3ab87dd47b054475dac04d2482",
"size": "6870",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "IREMedia/libraries/OpenCV/samples/gpu/generalized_hough.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "87214"
},
{
"name": "Awk",
"bytes": "42674"
},
{
"name": "C",
"bytes": "12003793"
},
{
"name": "C++",
"bytes": "30247062"
},
{
"name": "CSS",
"bytes": "38633"
},
{
"name": "Clojure",
"bytes": "1479"
},
{
"name": "Cuda",
"bytes": "1621113"
},
{
"name": "F#",
"bytes": "6312"
},
{
"name": "Java",
"bytes": "799856"
},
{
"name": "JavaScript",
"bytes": "3615"
},
{
"name": "Objective-C",
"bytes": "122210"
},
{
"name": "Objective-C++",
"bytes": "176370"
},
{
"name": "Python",
"bytes": "1073309"
},
{
"name": "Scala",
"bytes": "5632"
},
{
"name": "Shell",
"bytes": "18653"
},
{
"name": "TeX",
"bytes": "48565"
}
],
"symlink_target": ""
} |
using RestSharp.Deserializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CodyQuiz.Web.Model {
public class Message {
[DeserializeAs(Name = "message_id")]
public int Id { get; set; }
public DateTime Date { get; set; }
public string Text { get; set; }
}
}
| {
"content_hash": "4142cd26373336d4aa393ae5475de5d7",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 44,
"avg_line_length": 18.35,
"alnum_prop": 0.6512261580381471,
"repo_name": "CodeMOOC/CodyQuiz",
"id": "9e88b22efee5f1a87159bed637e75f05c80f00a8",
"size": "369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CodyQuiz.Web/Model/Message.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "5033"
},
{
"name": "JavaScript",
"bytes": "10889"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;
using BLToolkit.EditableObjects;
using Kendo.Mvc.UI;
using bv.common.Core;
using eidss.model.Reports;
using eidss.model.Reports.Common;
using eidss.model.Resources;
using eidss.model.Schema;
using bv.model.BLToolkit;
using eidss.model.Core;
using eidss.web.common.Controllers;
using eidss.web.common.Utils;
using eidss.webclient.Utils;
using bv.model.Model.Core;
using eidss.model.Enums;
using System.Collections.Generic;
using System.Collections;
namespace eidss.webclient.Controllers
{
[AuthorizeEIDSS]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true, Duration = 0, VaryByParam = "*")]
public class LaboratoryController : BvController
{
public ActionResult Details(long? id)
{
return DetailsInternal<LaboratorySectionMaster.Accessor, LaboratorySectionMaster>(id, eidss.model.Schema.LaboratorySectionMaster.Accessor.Instance(null), null, null, null, null,
c => { c.bIsMyPref = false; c.DeepAcceptChanges(); }
);
}
public ActionResult DetailsMyPref(long? id)
{
ViewBag.StaticFilter = new FilterParams().Add("MyPref", "=", true);
return DetailsInternal<LaboratorySectionMaster.Accessor, LaboratorySectionMaster>(id, eidss.model.Schema.LaboratorySectionMaster.Accessor.Instance(null), null, null, null, null,
c => { c.bIsMyPref = true; c.DeepAcceptChanges(); }
);
}
[HttpPost]
public ActionResult Details(FormCollection form)
{
return DetailsInternalAjax<LaboratorySectionMaster.Accessor, LaboratorySectionMaster>(form, eidss.model.Schema.LaboratorySectionMaster.Accessor.Instance(null), null, null, null, null,
bCloneWithSetup: false);
}
[HttpPost]
public ActionResult DetailsMyPref(FormCollection form)
{
return DetailsInternalAjax<LaboratorySectionMaster.Accessor, LaboratorySectionMaster>(form, eidss.model.Schema.LaboratorySectionMaster.Accessor.Instance(null), null, null, null, null,
bCloneWithSetup: false);
}
public ActionResult IndexAjaxNotMy([DataSourceRequest]DataSourceRequest request, FormCollection form)
{
long id = Int64.Parse(form["ObjectAdditional"]);
var bIgnoreChanges = (form["SearchIgnoreChanges"] != null && form["SearchIgnoreChanges"] == "true");
var bSearchClick = (form["bSearchClick"] != null && form["bSearchClick"] == "1");
bool bFilterChanged = false;
var checkCol = new FormCollection();
form.AllKeys.Where(i => i != "sort" && i != "page" && i != "SearchIgnoreChanges").ToList().ForEach(i => checkCol.Add(i, form[i]));
if (Session["IndexAjaxNotMy"] is FormCollection)
{
var oldCheckCol = Session["IndexAjaxNotMy"] as FormCollection;
foreach (string key in checkCol.AllKeys)
{
if (checkCol[key] != oldCheckCol[key])
{
bFilterChanged = true;
break;
}
}
}
Session["IndexAjaxNotMy"] = checkCol;
var master = (LaboratorySectionMaster)ModelStorage.Get(Session.SessionID, id, null);
return IndexInternalAjax<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionItem.LaboratorySectionItemGridModelList>
(form, LaboratorySectionItem.Accessor.Instance(null), AutoGridRoots.LabSampleBook, request,
() =>
{
if ((!bFilterChanged || master.HasChanges) && !bIgnoreChanges && !bSearchClick)
{
master.LaboratorySectionItems.ForEach(c => c.Parent = master);
return master.LaboratorySectionItems.ToList();
}
return null;
},
list =>
{
if ((bFilterChanged && !master.HasChanges) || bIgnoreChanges || bSearchClick)
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
master.LaboratorySectionItems.Clear();
//master.LaboratorySectionItems.AddRange(list.Select(i => i.SetupLoad(manager)).ToList());
master.LaboratorySectionItems.AddRange(list);
master.LaboratorySectionItems.ForEach(c =>
{
c.Parent = master;
ModelStorage.Put(Session.SessionID, master.idfsLaboratorySection, c.ID, "_" + master.idfsLaboratorySection, c);
}
);
master.DeepAcceptChanges();
}
}
},
true
);
}
public ActionResult IndexAjaxMy([DataSourceRequest]DataSourceRequest request, FormCollection form)
{
long id = Int64.Parse(form["ObjectAdditional"]);
var bIgnoreChanges = (form["SearchIgnoreChanges"] != null && form["SearchIgnoreChanges"] == "true");
var bSearchClick = (form["bSearchClick"] != null && form["bSearchClick"] == "1");
bool bFilterChanged = false;
var checkCol = new FormCollection();
form.AllKeys.Where(i => i != "sort" && i != "page" && i != "SearchIgnoreChanges").ToList().ForEach(i => checkCol.Add(i, form[i]));
if (Session["IndexAjaxMy"] is FormCollection)
{
var oldCheckCol = Session["IndexAjaxMy"] as FormCollection;
foreach (string key in checkCol.AllKeys)
{
if (checkCol[key] != oldCheckCol[key])
{
bFilterChanged = true;
break;
}
}
}
Session["IndexAjaxMy"] = checkCol;
var master = (LaboratorySectionMaster)ModelStorage.Get(Session.SessionID, id, null);
return IndexInternalAjax<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionItem.LaboratorySectionItemGridModelList>
(form, LaboratorySectionItem.Accessor.Instance(null), AutoGridRoots.LabSampleBookPreference, request,
() =>
{
if ((!bFilterChanged || master.HasChanges) && !bIgnoreChanges && !bSearchClick)
{
master.LaboratorySectionMyPrefItems.ForEach(c => c.Parent = master);
return master.LaboratorySectionMyPrefItems.ToList();
}
return null;
},
list =>
{
if ((bFilterChanged && !master.HasChanges) || bIgnoreChanges || bSearchClick)
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
master.LaboratorySectionMyPrefItems.Clear();
//master.LaboratorySectionMyPrefItems.AddRange(list.Select(i => i.SetupLoad(manager)).ToList());
master.LaboratorySectionItems.AddRange(list);
master.LaboratorySectionMyPrefItems.ForEach(c =>
{
c.bIsMyPref = true;
c.Parent = master;
ModelStorage.Put(Session.SessionID, master.idfsLaboratorySection, c.ID, "_" + master.idfsLaboratorySection, c);
}
);
master.DeepAcceptChanges();
}
}
},
true
);
}
private List<LaboratorySectionItem> PreprocessGetAll(long root, string ids)
{
var ret = new List<LaboratorySectionItem>();
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
ViewBag.Root = root;
if (ids != null)
{
string[] idents = ids.Split(new[] {','});
idents.Select(c => Int64.Parse(c)).ToList().ForEach(id =>
{
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample != null)
ret.Add(sample);
});
ViewBag.Idents = ids;
}
return ret;
}
private LaboratorySectionItem PreprocessGet(long root, string ids)
{
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
ViewBag.Root = root;
if (ids != null)
{
string[] idents = ids.Split(new[] { ',' });
long id = long.Parse(idents[0]);
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
ViewBag.Idents = ids;
return sample;
}
return null;
}
private LaboratorySectionItem PreprocessGet(long root, long id)
{
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
ViewBag.Root = root;
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
return sample;
}
private void PostprocessPost(FormCollection form, Action<DbManagerProxy, LaboratorySectionItem> action)
{
var root = long.Parse(form["Root"]);
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
var ids = form["Idents"];
var idents = ids.Split(new[] { ',' });
foreach (var ident in idents)
{
var id = long.Parse(ident);
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
action(manager, sample);
}
}
if (master.bIsMyPref)
master.LaboratorySectionMyPrefItems.ForEach(c => ModelStorage.Put(Session.SessionID, root, c.ID, "_" + root, c));
else
master.LaboratorySectionItems.ForEach(c => ModelStorage.Put(Session.SessionID, root, c.ID, "_" + root, c));
}
private void PostprocessPost(FormCollection form, Action<DbManagerProxy, List<IObject>, IObject> action)
{
var root = long.Parse(form["Root"]);
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
var ids = form["Idents"];
var idents = ids.Split(new[] { ',' });
List<IObject> list = new List<IObject>();
foreach (var ident in idents)
{
var id = long.Parse(ident);
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample != null)
list.Add(sample);
}
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
action(manager, list, master);
}
if (master.bIsMyPref)
master.LaboratorySectionMyPrefItems.ForEach(c => ModelStorage.Put(Session.SessionID, root, c.ID, "_" + root, c));
else
master.LaboratorySectionItems.ForEach(c => ModelStorage.Put(Session.SessionID, root, c.ID, "_" + root, c));
}
private void PostprocessPostMaster(FormCollection form, Action<DbManagerProxy, LaboratorySectionMaster> action)
{
var root = long.Parse(form["Root"]);
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
action(manager, master);
}
if (master.bIsMyPref)
master.LaboratorySectionMyPrefItems.ForEach(c => ModelStorage.Put(Session.SessionID, root, c.ID, "_" + root, c));
else
master.LaboratorySectionItems.ForEach(c => ModelStorage.Put(Session.SessionID, root, c.ID, "_" + root, c));
}
[HttpGet]
public ActionResult CreateAliquotPicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.CreateAliquot, sample.idfsSampleType, null, null, null, null),
null);
}
[HttpPost]
public ActionResult SetCreateAliquot(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null,null,null,null,
(o, p) => PostprocessPost(form, (m, s) => LaboratorySectionItem.Accessor.Instance(null).MenuCreateAliquot(m, s, o.intNewSample.Value))
);
}
[HttpGet]
public ActionResult CreateDerivativePicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.CreateDerivative, sample.idfsSampleType, null, null, null, null),
null);
}
[HttpPost]
public ActionResult SetCreateDerivative(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPost(form, (m, s) => LaboratorySectionItem.Accessor.Instance(null).MenuCreateDerivative(m, s, o.intNewSample.Value, o.DerivativeType.idfsDerivativeType))
);
}
[HttpGet]
public ActionResult TransferOutSamplePicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.TransferOutSample, 0, null, null, null, null, null, DateTime.Today),
null);
}
[HttpPost]
public ActionResult SetTransferOutSample(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPost(form, (m, s) => LaboratorySectionItem.Accessor.Instance(null).MenuTransferOutSample(m, s, o.idfSendToOfficeOut, o.datSendDate))
);
}
[HttpGet]
public ActionResult AccessionInPoorConditionPicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.Accept, 0, null, null, null, null),
null);
}
[HttpPost]
public ActionResult SetAccessionInPoorCondition(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPost(form, (m, s) => LaboratorySectionItem.Accessor.Instance(null).MenuAccessionInPoorCondition(m, s, o.strComments))
);
}
[HttpGet]
public ActionResult AccessionInRejectedPicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.Accept, sample.idfsSampleType, null, null, null, null),
null);
}
[HttpPost]
public ActionResult SetAccessionInRejected(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPost(form, (m, s) => LaboratorySectionItem.Accessor.Instance(null).MenuAccessionInRejected(m, s, o.strComments))
);
}
[HttpGet]
public ActionResult AmendTestResultPicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.AmendTestResult, 0, sample.idfsTestName.Value, null, null, null, sample.GetOriginalTestResult()),
null);
}
[HttpPost]
public ActionResult SetAmendTestResult(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPost(form, (m, s) => LaboratorySectionItem.Accessor.Instance(null).MenuAmendTestResult(m, s, o.strReason, o.idfsTestResult.Value))
);
}
[HttpGet]
public ActionResult AssignTestPicker(long root, string ids)
{
var sample = PreprocessGet(root, ids);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.AssignTest, sample.idfsSampleType, null, sample.idfCaseOrSession, sample.idfsCaseType, sample.intCaseHACode, null, null, sample.idfMaterial, sample.idfsShowDiagnosis),
null);
}
[HttpPost]
public ActionResult SetAssignTest(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, r) => PostprocessPost(form, (m, l, p) =>
{
var bIsMyPref = false;
if (l.Count > 0)
bIsMyPref = ((LaboratorySectionItem) l[0]).bIsMyPref;
LaboratorySectionItem.Accessor.Instance(null).ItemAssignTest(m, o, l, p, bIsMyPref);
})
);
}
[HttpGet]
public ActionResult CreateSamplePicker(long root)
{
PreprocessGet(root, null);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.CreateSample, 0, null, null, null, null),
null);
}
[HttpPost]
public ActionResult SetCreateSample(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPostMaster(form, (m, mm) => LaboratorySectionItem.Accessor.Instance(null).ItemCreate(m, o, o.intNewSample.Value, mm, o, o.idfsSampleTypeFiltered, mm.bIsMyPref))
);
}
[HttpGet]
public ActionResult GroupAccessionInPicker(long root)
{
PreprocessGet(root, null);
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, 0, "", LaboratorySectionItem.Accessor.Instance(null), null,
null,
(m, a, p) => a.CreateWithNewMode(m, p, LabNewModeEnum.GroupAccessionIn, 0, null, null, null, null),
null);
}
[HttpPost]
public ActionResult SetGroupAccessionIn(FormCollection form)
{
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null,
(o, p) => PostprocessPostMaster(form, (m, mm) => LaboratorySectionItem.Accessor.Instance(null).ItemGroupAccessionIn(m, o, mm, mm.bIsMyPref))
);
}
[HttpGet]
public ActionResult DetailsPicker(long root, long id)
{
var sample = PreprocessGet(root, id);
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
sample.SetupLoad(manager);
}
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(root, id, "", LaboratorySectionItem.Accessor.Instance(null), null,
(m, a, p) =>
{
var ret = (sample.CloneWithSetup(m) as LaboratorySectionItem).GetWithOriginal(sample);
ModelStorage.Put(Session.SessionID, id, id, (ret.idfObservation.HasValue ? ret.idfObservation.Value : 0).ToString(), ret.FFPresenter);
return ret;
},
null,
(m, a, o) => ModelStorage.Put(Session.SessionID, id, id, o.ObjectIdent + "AmendmentHistory", o.AmendmentHistory)
);
}
private Tuple<FormCollection, ActionResult> SetOneField(LaboratorySectionItem sample, long id, FormCollection form, string field)
{
if (form.AllKeys.Any(c => c.EndsWith(field)))
{
var fieldKey = form.AllKeys.First(c => c.EndsWith(field));
var fieldValue = form[fieldKey];
form.Remove(fieldKey);
var formNew = new FormCollection();
//formNew.Add(LaboratorySectionItem.Accessor.Instance(null).KeyName, form[LaboratorySectionItem.Accessor.Instance(null).KeyName]);
//formNew.Add("Root", form["Root"]);
form.AllKeys.Where(c => !c.StartsWith("LaboratorySectionItem")).ToList().ForEach(c => formNew.Add(c, form[c]));
formNew.Add(fieldKey, fieldValue);
var ret = PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(formNew, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null, (c, p) => { }, c => sample
);
if (((ret as JsonResult).Data as CompareModel).Values.Any(c => c.Key == "ErrorMessage"))
{
return new Tuple<FormCollection, ActionResult>(null, ret);
}
if (id != sample.ID)
{
formNew = new FormCollection();
form.AllKeys.ToList().ForEach(c =>
{
string key = c.Replace(id.ToString(), sample.ID.ToString());
var value = form[c];
formNew.Add(key, value);
});
form = formNew;
}
}
return new Tuple<FormCollection, ActionResult>(form , null);
}
[HttpPost]
public ActionResult SetDetails(FormCollection form)
{
var id = long.Parse(form[LaboratorySectionItem.Accessor.Instance(null).KeyName]);
var root = long.Parse(form["Root"]);
var sample = PreprocessGet(root, id);
var ret = SetOneField(sample, id, form, "blnExternalTest");
if (ret.Item2 != null) return ret.Item2;
form = ret.Item1;
ret = SetOneField(sample, id, form, "TestNameRef");
if (ret.Item2 != null) return ret.Item2;
form = ret.Item1;
ret = SetOneField(sample, id, form, "DiagnosisForTest");
if (ret.Item2 != null) return ret.Item2;
form = ret.Item1;
ret = SetOneField(sample, id, form, "TestStatusShort");
if (ret.Item2 != null) return ret.Item2;
form = ret.Item1;
ret = SetOneField(sample, id, form, "TestResultRef");
if (ret.Item2 != null) return ret.Item2;
form = ret.Item1;
if (sample.FFPresenter != null && sample.FFPresenter.CurrentObservation.HasValue)
{
var idfObservation = sample.FFPresenter.CurrentObservation.Value;
var formNew = new FormCollection();
form.AllKeys.ToList().ForEach(c =>
{
var value = form[c];
int o = c.IndexOf("o");
int p = c.IndexOf("_p");
if (o == 0 && p > o)
{
string oldkey = c.Substring(o + 1, p - o - 1);
string key = c.Replace(oldkey, idfObservation.ToString());
formNew.Add(key, value);
}
else
{
formNew.Add(c, value);
}
});
form = formNew;
}
return PickerInternal<LaboratorySectionItem.Accessor, LaboratorySectionItem, LaboratorySectionMaster>(form, LaboratorySectionItem.Accessor.Instance(null),
null, null, null, null, null, c => sample
);
}
public ActionResult GetFlexForm(long root)
{
var item = ModelStorage.Get(Session.SessionID, root, null, false) as LaboratorySectionItem;
if ((item != null) && (item.FFPresenter != null) && (item.FFPresenter.CurrentObservation.HasValue))
{
LaboratorySectionItem.Accessor accessor = LaboratorySectionItem.Accessor.Instance(null);
item.FFPresenter.ReadOnly = accessor.IsReadOnlyForEdit || item.IsReadOnly("idfObservation");
ModelStorage.Put(Session.SessionID, item.idfTesting.Value, item.idfTesting.Value, item.FFPresenter.CurrentObservation.Value.ToString(), item.FFPresenter);
var ffDivContent = this.RenderPartialView("FlexForm", item);
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = ffDivContent };
}
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = "" };
}
[HttpPost]
public ActionResult Delete(long root, long id)
{
var sample = PreprocessGet(root, id);
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
LaboratorySectionItem.Accessor.Instance(null).MenuRemove(manager, sample);
}
var data = new CompareModel();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
}
[HttpPost]
public ActionResult SampleDelete(long root, string ids)
{
var samples = PreprocessGetAll(root, ids);
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
{
samples.ForEach(s => LaboratorySectionItem.Accessor.Instance(null).MenuDeleteSample(manager, s));
}
var data = new CompareModel();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
}
}
public class SampleBarcodeDTOComparator : EqualityComparer<SampleBarcodeDTO>
{
public override bool Equals(SampleBarcodeDTO x, SampleBarcodeDTO y)
{
return x.Barcode == y.Barcode
&& x.CollectionDate == y.CollectionDate
&& x.OwnerId == y.OwnerId
&& x.SpeciesCode == y.SpeciesCode
&& x.SpecimenCode == y.SpecimenCode
;
}
public override int GetHashCode(SampleBarcodeDTO obj)
{
return base.GetHashCode();
}
}
[AuthorizeEIDSS]
public class LaboratoryReportController : BvController
{
private LaboratorySectionItem PreprocessGet(long root, string ids)
{
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
ViewBag.Root = root;
if (ids != null)
{
string[] idents = ids.Split(new[] { ',' });
long id = long.Parse(idents[0]);
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
ViewBag.Idents = ids;
return sample;
}
return null;
}
private List<LaboratorySectionItem> PreprocessGetAll(long root, string ids)
{
var ret = new List<LaboratorySectionItem>();
var master = ModelStorage.Get(Session.SessionID, root, null) as LaboratorySectionMaster;
ViewBag.Root = root;
if (ids != null)
{
string[] idents = ids.Split(new[] { ',' });
idents.Select(c => Int64.Parse(c)).ToList().ForEach(id =>
{
var sample = master.LaboratorySectionItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample == null)
sample = master.LaboratorySectionMyPrefItems.FirstOrDefault(c => c.idfMaterial == id || c.idfTesting == id);
if (sample != null)
ret.Add(sample);
});
ViewBag.Idents = ids;
}
return ret;
}
public ActionResult SampleReport(long id)
{
try
{
byte[] report;
using (var wrapper = new ReportClientWrapper())
{
var model = new BaseIdModel(ModelUserContext.CurrentLanguage, id, ModelUserContext.Instance.IsArchiveMode);
report = wrapper.Client.ExportLimSample(model);
}
return ReportResponse(report, "SampleReport.pdf");
}
catch
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = null };
}
}
public ActionResult TestResultReport(long root, string ids)
{
try
{
byte[] report;
using (var wrapper = new ReportClientWrapper())
{
var item = PreprocessGet(root, ids);
var model = new LimTestResultModel(ModelUserContext.CurrentLanguage, item.idfTesting ?? 0, item.idfObservation ?? 0, item.idfsTestName ?? 0, ModelUserContext.Instance.IsArchiveMode);
report = wrapper.Client.ExportLimTestResult(model);
}
return ReportResponse(report, "TestResultReport.pdf");
}
catch
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = null };
}
}
public ActionResult SampleDestructionReport(long id)
{
try
{
byte[] report;
using (var wrapper = new ReportClientWrapper())
{
var model = new IdListModel(ModelUserContext.CurrentLanguage, new[] { id }, ModelUserContext.Instance.IsArchiveMode);
report = wrapper.Client.ExportLimSampleDestruction(model);
}
return ReportResponse(report, "SampleDestructionReport.pdf");
}
catch
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = null };
}
}
public ActionResult PrintBarcode(long root, string ids)
{
try
{
byte[] report;
using (var wrapper = new ReportClientWrapper())
{
var items = PreprocessGetAll(root, ids);
var model = items.Select(c => new SampleBarcodeDTO()
{
Barcode = c.strBarcode,
CollectionDate = c.datFieldCollectionDate.HasValue ? c.datFieldCollectionDate.Value : DateTime.MinValue,
OwnerId = c.strCalculatedCaseID,
SpeciesCode = c.SpeciesVectorInfo == null ? "" : c.SpeciesVectorInfo.SpeciesOrVectorType,
SpecimenCode = c.SampleType == null ? "" : c.SampleType.name
}).Distinct(new SampleBarcodeDTOComparator()).ToArray();
report = wrapper.Client.ExportSampleBarcodes(model);
}
return ReportResponse(report, "PrintBarcode.pdf");
}
catch
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = null };
}
}
[HttpGet]
public ActionResult TestsReport(long id, bool isHuman)
{
try
{
byte[] report;
using (var wrapper = new ReportClientWrapper())
{
var model = new LimTestModel(ModelUserContext.CurrentLanguage, id, isHuman, ModelUserContext.Instance.IsArchiveMode);
report = wrapper.Client.ExportLimTest(model);
}
return ReportResponse(report, "TestsReport.pdf");
}
catch
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = null };
}
}
}
}
| {
"content_hash": "25d1cf4a3793472bb215cb6a04963be3",
"timestamp": "",
"source": "github",
"line_count": 776,
"max_line_length": 237,
"avg_line_length": 49.128865979381445,
"alnum_prop": 0.5529063057391669,
"repo_name": "EIDSS/EIDSS-Legacy",
"id": "82afaa38bbe2b48a9d854fedc11d44242d0adb28",
"size": "38126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EIDSS v6/eidss.webclient/Controllers/LaboratoryController.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "256377"
},
{
"name": "Batchfile",
"bytes": "30009"
},
{
"name": "C#",
"bytes": "106160789"
},
{
"name": "CSS",
"bytes": "833586"
},
{
"name": "HTML",
"bytes": "7507"
},
{
"name": "Java",
"bytes": "2188690"
},
{
"name": "JavaScript",
"bytes": "17000221"
},
{
"name": "PLSQL",
"bytes": "2499"
},
{
"name": "PLpgSQL",
"bytes": "6422"
},
{
"name": "Pascal",
"bytes": "159898"
},
{
"name": "PowerShell",
"bytes": "339522"
},
{
"name": "Puppet",
"bytes": "3758"
},
{
"name": "SQLPL",
"bytes": "12198"
},
{
"name": "Smalltalk",
"bytes": "301266"
},
{
"name": "Visual Basic",
"bytes": "20819564"
},
{
"name": "XSLT",
"bytes": "4253600"
}
],
"symlink_target": ""
} |
package floschlo.smokingspots.views;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**
* This is a relative layout where its width is same as its height.
*/
public class RectRelativeLayout extends RelativeLayout {
public static int MATCH_WIDTH = 0;
public static int MATCH_HEIGHT = 1;
private int mMatchMode;
public RectRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mMatchMode = MATCH_WIDTH;
}
/**
* Sets the match mode to MATCH_WIDTH or MATCH_HEIGHT.
*
* @param matchMode
*/
public void setMatchMode(int matchMode) {
if (matchMode != MATCH_HEIGHT && matchMode != MATCH_WIDTH) {
return;
}
mMatchMode = matchMode;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mMatchMode == MATCH_HEIGHT) {
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
} else if (mMatchMode == MATCH_WIDTH) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
}
| {
"content_hash": "386579ea81b04095dcda75a4e157d5d7",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 75,
"avg_line_length": 20.732142857142858,
"alnum_prop": 0.6494401378122309,
"repo_name": "Floschlo/SmokingSpots",
"id": "64bc5d877bbdd23b0e162e33f33640b9dbb9d99e",
"size": "1910",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/floschlo/smokingspots/views/RectRelativeLayout.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "185368"
}
],
"symlink_target": ""
} |
datafolder: engine-cli
datafile: docker_cp
title: docker cp
---
<!--
Sorry, but the contents of this page are automatically generated from
Docker's source code. If you want to suggest a change to the text that appears
here, you'll need to find the string by searching this repo:
https://www.github.com/docker/docker
-->
{% if page.datafolder contains '-edge' %}
{% include edge_only.md section="cliref" %}
{% endif %}
{% include cli.md datafolder=page.datafolder datafile=page.datafile %}
| {
"content_hash": "fa0b20d38ff0b60d76def43ea2e905e9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 78,
"avg_line_length": 32.8,
"alnum_prop": 0.7378048780487805,
"repo_name": "docker-zh/docker.github.io",
"id": "b8d4c3ffc594aaff83bd347287cd682206b46e57",
"size": "496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/reference/commandline/cp.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "652154"
},
{
"name": "Go",
"bytes": "8433"
},
{
"name": "HTML",
"bytes": "1340885"
},
{
"name": "JavaScript",
"bytes": "5329454"
},
{
"name": "Makefile",
"bytes": "6684"
},
{
"name": "Ruby",
"bytes": "4864"
},
{
"name": "Shell",
"bytes": "8975"
}
],
"symlink_target": ""
} |
package jrds.starter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import jrds.HostInfo;
import jrds.PropertiesManager;
import org.apache.log4j.Level;
public class Timer extends StarterNode {
public final static String DEFAULTNAME = "_default";
public static final class Stats implements Cloneable {
Stats() {
lastCollect = new Date(0);
}
public long runtime = 0;
public Date lastCollect;
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public Object clone() throws CloneNotSupportedException {
Stats newstates = new Stats();
synchronized(this) {
newstates.runtime = runtime;
newstates.lastCollect = new Date(lastCollect.getTime());
}
return newstates;
}
}
private final Map<String, HostStarter> hostList = new HashMap<String, HostStarter>();
private Semaphore collectMutex = new Semaphore(1);
private final Stats stats = new Stats();
private final int numCollectors;
private final String name;
private TimerTask collector;
public Timer(String name, PropertiesManager.TimerInfo ti) {
super();
this.name = name;
setTimeout(ti.timeout);
setStep(ti.step);
this.numCollectors = ti.numCollectors;
}
public HostStarter getHost(HostInfo info) {
String hostName = info.getName();
HostStarter starter = hostList.get(hostName);
if(starter == null) {
starter = new HostStarter(info);
hostList.put(hostName, starter);
starter.setTimeout(getTimeout());
starter.setStep(getStep());
starter.setParent(this);
}
return starter;
}
public Iterable<HostStarter> getAllHosts() {
return hostList.values();
}
public void startTimer(java.util.Timer collectTimer) {
collector = new TimerTask () {
public void run() {
Thread subcollector = new Thread("Collector/" + Timer.this.name) {
@Override
public void run() {
try {
Timer.this.collectAll();
} catch (RuntimeException e) {
Timer.this.log(Level.FATAL, e, "A fatal error occured during collect: %s", e.getMessage());
}
}
};
subcollector.start();
}
};
collectTimer.scheduleAtFixedRate(collector, getTimeout() * 1000L, getStep() * 1000L);
}
public void collectAll() {
log(Level.DEBUG, "One collect is launched");
Date start = new Date();
try {
if( ! collectMutex.tryAcquire(getTimeout(), TimeUnit.SECONDS)) {
log(Level.FATAL, "A collect failed because a start time out");
return;
}
} catch (InterruptedException e) {
log(Level.FATAL, "A collect start was interrupted");
return;
}
try {
final AtomicInteger counter = new AtomicInteger(0);
ExecutorService tpool = Executors.newFixedThreadPool(numCollectors,
new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(r, Timer.this.name + "/CollectorThread" + counter.getAndIncrement());
t.setDaemon(true);
log(Level.DEBUG, "New thread name:" + t.getName());
return t;
}
}
);
startCollect();
for(final HostStarter host: hostList.values()) {
if( ! isCollectRunning())
break;
Runnable runCollect = new Runnable() {
public void run() {
log(Level.DEBUG, "Collect all stats for host " + host.getName());
String threadName = Timer.this.name + "/" + "JrdsCollect-" + host.getName();
Thread.currentThread().setName(threadName);
host.collectAll();
Thread.currentThread().setName(threadName + ":finished");
}
@Override
public String toString() {
return Thread.currentThread().toString();
}
};
try {
tpool.execute(runCollect);
}
catch(RejectedExecutionException ex) {
log(Level.DEBUG, "collector thread dropped for host " + host.getName());
}
}
tpool.shutdown();
try {
tpool.awaitTermination(getStep() - getTimeout() * 2 , TimeUnit.SECONDS);
} catch (InterruptedException e) {
log(Level.WARN, "Collect interrupted");
}
stopCollect();
if( ! tpool.isTerminated()) {
//Second chance, we wait for the time out
boolean emergencystop = false;
try {
emergencystop = tpool.awaitTermination(getTimeout(), TimeUnit.SECONDS);
} catch (InterruptedException e) {
log(Level.WARN, "Collect interrupted in last chance");
}
if(! emergencystop) {
log(Level.WARN, "Some task still alive, needs to be killed");
//Last chance to commit results
List<Runnable> timedOut = tpool.shutdownNow();
if(! timedOut.isEmpty()) {
log(Level.WARN, "Still " + timedOut.size() + " waiting probes: ");
for(Runnable r: timedOut) {
log(Level.WARN, r.toString());
}
}
}
}
} catch (RuntimeException e) {
log(Level.ERROR, "problem while collecting data: ", e);
}
finally {
collectMutex.release();
}
Date end = new Date();
long duration = end.getTime() - start.getTime();
synchronized(stats) {
stats.lastCollect = start;
stats.runtime = duration;
}
System.gc();
log(Level.INFO, "Collect started at " + start + " ran for " + duration + "ms");
}
public void lockCollect() throws InterruptedException {
collectMutex.acquire();
}
public void releaseCollect() {
collectMutex.release();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "timer:" + name;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the stats
*/
public Stats getStats() {
return stats;
}
}
| {
"content_hash": "a3604baeab8063839b0f232091d4c3dd",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 119,
"avg_line_length": 34.50230414746544,
"alnum_prop": 0.5227728061974088,
"repo_name": "snow-listen/Mycat-Web",
"id": "be376fdf8b25af58a78ac2b160d6427209e88cfa",
"size": "7487",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/jrds/starter/Timer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "381"
},
{
"name": "CSS",
"bytes": "681357"
},
{
"name": "FreeMarker",
"bytes": "2090"
},
{
"name": "HTML",
"bytes": "306721"
},
{
"name": "Java",
"bytes": "966063"
},
{
"name": "JavaScript",
"bytes": "1707814"
},
{
"name": "Shell",
"bytes": "381"
}
],
"symlink_target": ""
} |
#include <aws/core/client/AWSError.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/core/utils/HashingUtils.h>
using namespace Aws::Client;
using namespace Aws::Utils;
using namespace Aws::Http;
#ifdef _MSC_VER
#pragma warning(push)
// VS2015 compiler's bug, warning s_CoreErrorsMapper: symbol will be dynamically initialized (implementation limitation)
#pragma warning(disable : 4592)
#endif
static Aws::UniquePtr<Aws::Map<Aws::String, AWSError<CoreErrors> > > s_CoreErrorsMapper(nullptr);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
void CoreErrorsMapper::InitCoreErrorsMapper()
{
if (s_CoreErrorsMapper)
{
return;
}
s_CoreErrorsMapper = Aws::MakeUnique<Aws::Map<Aws::String, AWSError<CoreErrors> > >("InitCoreErrorsMapper");
s_CoreErrorsMapper->emplace("IncompleteSignature", AWSError<CoreErrors>(CoreErrors::INCOMPLETE_SIGNATURE, false));
s_CoreErrorsMapper->emplace("IncompleteSignatureException", AWSError<CoreErrors>(CoreErrors::INCOMPLETE_SIGNATURE, false));
s_CoreErrorsMapper->emplace("InvalidSignatureException", AWSError<CoreErrors>(CoreErrors::INVALID_SIGNATURE, false));
s_CoreErrorsMapper->emplace("InvalidSignature", AWSError<CoreErrors>(CoreErrors::INVALID_SIGNATURE, false));
s_CoreErrorsMapper->emplace("InternalFailureException", AWSError<CoreErrors>(CoreErrors::INTERNAL_FAILURE, true));
s_CoreErrorsMapper->emplace("InternalFailure", AWSError<CoreErrors>(CoreErrors::INTERNAL_FAILURE, true));
s_CoreErrorsMapper->emplace("InternalServerError", AWSError<CoreErrors>(CoreErrors::INTERNAL_FAILURE, true));
s_CoreErrorsMapper->emplace("InternalError", AWSError<CoreErrors>(CoreErrors::INTERNAL_FAILURE, true));
s_CoreErrorsMapper->emplace("InvalidActionException", AWSError<CoreErrors>(CoreErrors::INVALID_ACTION, false));
s_CoreErrorsMapper->emplace("InvalidAction", AWSError<CoreErrors>(CoreErrors::INVALID_ACTION, false));
s_CoreErrorsMapper->emplace("InvalidClientTokenIdException", AWSError<CoreErrors>(CoreErrors::INVALID_CLIENT_TOKEN_ID, false));
s_CoreErrorsMapper->emplace("InvalidClientTokenId", AWSError<CoreErrors>(CoreErrors::INVALID_CLIENT_TOKEN_ID, false));
s_CoreErrorsMapper->emplace("InvalidParameterCombinationException", AWSError<CoreErrors>(CoreErrors::INVALID_PARAMETER_COMBINATION, false));
s_CoreErrorsMapper->emplace("InvalidParameterCombination", AWSError<CoreErrors>(CoreErrors::INVALID_PARAMETER_COMBINATION, false));
s_CoreErrorsMapper->emplace("InvalidParameterValueException", AWSError<CoreErrors>(CoreErrors::INVALID_PARAMETER_VALUE, false));
s_CoreErrorsMapper->emplace("InvalidParameterValue", AWSError<CoreErrors>(CoreErrors::INVALID_PARAMETER_VALUE, false));
s_CoreErrorsMapper->emplace("InvalidQueryParameterException", AWSError<CoreErrors>(CoreErrors::INVALID_QUERY_PARAMETER, false));
s_CoreErrorsMapper->emplace("InvalidQueryParameter", AWSError<CoreErrors>(CoreErrors::INVALID_QUERY_PARAMETER, false));
s_CoreErrorsMapper->emplace("MalformedQueryStringException", AWSError<CoreErrors>(CoreErrors::MALFORMED_QUERY_STRING, false));
s_CoreErrorsMapper->emplace("MalformedQueryString", AWSError<CoreErrors>(CoreErrors::MALFORMED_QUERY_STRING, false));
s_CoreErrorsMapper->emplace("MissingActionException", AWSError<CoreErrors>(CoreErrors::MISSING_ACTION, false));
s_CoreErrorsMapper->emplace("MissingAction", AWSError<CoreErrors>(CoreErrors::MISSING_ACTION, false));
s_CoreErrorsMapper->emplace("MissingAuthenticationTokenException", AWSError<CoreErrors>(CoreErrors::MISSING_AUTHENTICATION_TOKEN, false));
s_CoreErrorsMapper->emplace("MissingAuthenticationToken", AWSError<CoreErrors>(CoreErrors::MISSING_AUTHENTICATION_TOKEN, false));
s_CoreErrorsMapper->emplace("MissingParameterException", AWSError<CoreErrors>(CoreErrors::MISSING_PARAMETER, false));
s_CoreErrorsMapper->emplace("MissingParameter", AWSError<CoreErrors>(CoreErrors::MISSING_PARAMETER, false));
s_CoreErrorsMapper->emplace("OptInRequired", AWSError<CoreErrors>(CoreErrors::OPT_IN_REQUIRED, false));
s_CoreErrorsMapper->emplace("RequestExpiredException", AWSError<CoreErrors>(CoreErrors::REQUEST_EXPIRED, true));
s_CoreErrorsMapper->emplace("RequestExpired", AWSError<CoreErrors>(CoreErrors::REQUEST_EXPIRED, true));
s_CoreErrorsMapper->emplace("ServiceUnavailableException", AWSError<CoreErrors>(CoreErrors::SERVICE_UNAVAILABLE, true));
s_CoreErrorsMapper->emplace("ServiceUnavailableError", AWSError<CoreErrors>(CoreErrors::SERVICE_UNAVAILABLE, true));
s_CoreErrorsMapper->emplace("ServiceUnavailable", AWSError<CoreErrors>(CoreErrors::SERVICE_UNAVAILABLE, true));
s_CoreErrorsMapper->emplace("RequestThrottledException", AWSError<CoreErrors>(CoreErrors::THROTTLING, true));
s_CoreErrorsMapper->emplace("RequestThrottled", AWSError<CoreErrors>(CoreErrors::THROTTLING, true));
s_CoreErrorsMapper->emplace("ThrottlingException", AWSError<CoreErrors>(CoreErrors::THROTTLING, true));
s_CoreErrorsMapper->emplace("ThrottledException", AWSError<CoreErrors>(CoreErrors::THROTTLING, true));
s_CoreErrorsMapper->emplace("Throttling", AWSError<CoreErrors>(CoreErrors::THROTTLING, true));
s_CoreErrorsMapper->emplace("ValidationErrorException", AWSError<CoreErrors>(CoreErrors::VALIDATION, false));
s_CoreErrorsMapper->emplace("ValidationException", AWSError<CoreErrors>(CoreErrors::VALIDATION, false));
s_CoreErrorsMapper->emplace("ValidationError", AWSError<CoreErrors>(CoreErrors::VALIDATION, false));
s_CoreErrorsMapper->emplace("AccessDeniedException", AWSError<CoreErrors>(CoreErrors::ACCESS_DENIED, false));
s_CoreErrorsMapper->emplace("AccessDenied", AWSError<CoreErrors>(CoreErrors::ACCESS_DENIED, false));
s_CoreErrorsMapper->emplace("ResourceNotFoundException", AWSError<CoreErrors>(CoreErrors::RESOURCE_NOT_FOUND, false));
s_CoreErrorsMapper->emplace("ResourceNotFound", AWSError<CoreErrors>(CoreErrors::RESOURCE_NOT_FOUND, false));
s_CoreErrorsMapper->emplace("UnrecognizedClientException", AWSError<CoreErrors>(CoreErrors::UNRECOGNIZED_CLIENT, false));
s_CoreErrorsMapper->emplace("UnrecognizedClient", AWSError<CoreErrors>(CoreErrors::UNRECOGNIZED_CLIENT, false));
s_CoreErrorsMapper->emplace("SlowDownException", AWSError<CoreErrors>(CoreErrors::SLOW_DOWN, true));
s_CoreErrorsMapper->emplace("SlowDown", AWSError<CoreErrors>(CoreErrors::SLOW_DOWN, true));
s_CoreErrorsMapper->emplace("SignatureDoesNotMatchException", AWSError<CoreErrors>(CoreErrors::SIGNATURE_DOES_NOT_MATCH, false));
s_CoreErrorsMapper->emplace("SignatureDoesNotMatch", AWSError<CoreErrors>(CoreErrors::SIGNATURE_DOES_NOT_MATCH, false));
s_CoreErrorsMapper->emplace("InvalidAccessKeyIdException", AWSError<CoreErrors>(CoreErrors::INVALID_ACCESS_KEY_ID, false));
s_CoreErrorsMapper->emplace("InvalidAccessKeyId", AWSError<CoreErrors>(CoreErrors::INVALID_ACCESS_KEY_ID, false));
s_CoreErrorsMapper->emplace("RequestTimeTooSkewedException", AWSError<CoreErrors>(CoreErrors::REQUEST_TIME_TOO_SKEWED, true));
s_CoreErrorsMapper->emplace("RequestTimeTooSkewed", AWSError<CoreErrors>(CoreErrors::REQUEST_TIME_TOO_SKEWED, true));
s_CoreErrorsMapper->emplace("RequestTimeoutException", AWSError<CoreErrors>(CoreErrors::REQUEST_TIMEOUT, true));
s_CoreErrorsMapper->emplace("RequestTimeout", AWSError<CoreErrors>(CoreErrors::REQUEST_TIMEOUT, true));
}
void CoreErrorsMapper::CleanupCoreErrorsMapper()
{
if (s_CoreErrorsMapper)
{
s_CoreErrorsMapper = nullptr;
}
}
AWSError<CoreErrors> CoreErrorsMapper::GetErrorForName(const char* errorName)
{
auto iter = s_CoreErrorsMapper->find(errorName);
if (iter != s_CoreErrorsMapper->end())
{
return iter->second;
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
AWS_CORE_API AWSError<CoreErrors> CoreErrorsMapper::GetErrorForHttpResponseCode(HttpResponseCode code)
{
// best effort attempt to map HTTP response codes to CoreErrors
bool retryable = IsRetryableHttpResponseCode(code);
AWSError<CoreErrors> error;
switch (code)
{
case HttpResponseCode::UNAUTHORIZED:
case HttpResponseCode::FORBIDDEN:
error = AWSError<CoreErrors>(CoreErrors::ACCESS_DENIED, retryable);
break;
case HttpResponseCode::NOT_FOUND:
error = AWSError<CoreErrors>(CoreErrors::RESOURCE_NOT_FOUND, retryable);
break;
case HttpResponseCode::TOO_MANY_REQUESTS:
error = AWSError<CoreErrors>(CoreErrors::SLOW_DOWN, retryable);
break;
case HttpResponseCode::INTERNAL_SERVER_ERROR:
error = AWSError<CoreErrors>(CoreErrors::INTERNAL_FAILURE, retryable);
break;
case HttpResponseCode::BANDWIDTH_LIMIT_EXCEEDED:
error = AWSError<CoreErrors>(CoreErrors::THROTTLING, retryable);
break;
case HttpResponseCode::SERVICE_UNAVAILABLE:
error = AWSError<CoreErrors>(CoreErrors::SERVICE_UNAVAILABLE, retryable);
break;
case HttpResponseCode::REQUEST_TIMEOUT:
case HttpResponseCode::AUTHENTICATION_TIMEOUT:
case HttpResponseCode::LOGIN_TIMEOUT:
case HttpResponseCode::GATEWAY_TIMEOUT:
case HttpResponseCode::NETWORK_READ_TIMEOUT:
case HttpResponseCode::NETWORK_CONNECT_TIMEOUT:
error = AWSError<CoreErrors>(CoreErrors::REQUEST_TIMEOUT, retryable);
break;
default:
int codeValue = static_cast<int>(code);
error = AWSError<CoreErrors>(CoreErrors::UNKNOWN, codeValue >= 500 && codeValue < 600);
}
error.SetResponseCode(code);
return error;
}
| {
"content_hash": "1b3aab576e0eaa9875d6c277e93d5c49",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 144,
"avg_line_length": 65.6891891891892,
"alnum_prop": 0.7603373791400946,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "8c2c288dcd4f08a548e36538054a0cca17af2809",
"size": "9839",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-core/source/client/CoreErrors.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
// Copyright 2013, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zktopo
import (
"encoding/json"
"fmt"
"path"
"sort"
"github.com/youtube/vitess/go/event"
"github.com/youtube/vitess/go/vt/topo"
"github.com/youtube/vitess/go/vt/topo/events"
"github.com/youtube/vitess/go/zk"
"golang.org/x/net/context"
"launchpad.net/gozk/zookeeper"
pb "github.com/youtube/vitess/go/vt/proto/topodata"
)
/*
This file contains the Keyspace management code for zktopo.Server
*/
const (
globalKeyspacesPath = "/zk/global/vt/keyspaces"
)
// CreateKeyspace is part of the topo.Server interface
func (zkts *Server) CreateKeyspace(ctx context.Context, keyspace string, value *pb.Keyspace) error {
keyspacePath := path.Join(globalKeyspacesPath, keyspace)
pathList := []string{
keyspacePath,
path.Join(keyspacePath, "action"),
path.Join(keyspacePath, "actionlog"),
path.Join(keyspacePath, "shards"),
}
data, err := json.MarshalIndent(value, "", " ")
if err != nil {
return err
}
alreadyExists := false
for i, zkPath := range pathList {
c := ""
if i == 0 {
c = string(data)
}
_, err := zk.CreateRecursive(zkts.zconn, zkPath, c, 0, zookeeper.WorldACL(zookeeper.PERM_ALL))
if err != nil {
if zookeeper.IsError(err, zookeeper.ZNODEEXISTS) {
alreadyExists = true
} else {
return fmt.Errorf("error creating keyspace: %v %v", zkPath, err)
}
}
}
if alreadyExists {
return topo.ErrNodeExists
}
event.Dispatch(&events.KeyspaceChange{
KeyspaceInfo: *topo.NewKeyspaceInfo(keyspace, value, -1),
Status: "created",
})
return nil
}
// UpdateKeyspace is part of the topo.Server interface
func (zkts *Server) UpdateKeyspace(ctx context.Context, ki *topo.KeyspaceInfo, existingVersion int64) (int64, error) {
keyspacePath := path.Join(globalKeyspacesPath, ki.KeyspaceName())
data, err := json.MarshalIndent(ki.Keyspace, "", " ")
if err != nil {
return -1, err
}
stat, err := zkts.zconn.Set(keyspacePath, string(data), int(existingVersion))
if err != nil {
if zookeeper.IsError(err, zookeeper.ZNONODE) {
err = topo.ErrNoNode
}
return -1, err
}
event.Dispatch(&events.KeyspaceChange{
KeyspaceInfo: *ki,
Status: "updated",
})
return int64(stat.Version()), nil
}
// DeleteKeyspace is part of the topo.Server interface.
func (zkts *Server) DeleteKeyspace(ctx context.Context, keyspace string) error {
keyspacePath := path.Join(globalKeyspacesPath, keyspace)
err := zk.DeleteRecursive(zkts.zconn, keyspacePath, -1)
if err != nil {
if zookeeper.IsError(err, zookeeper.ZNONODE) {
err = topo.ErrNoNode
}
return err
}
event.Dispatch(&events.KeyspaceChange{
KeyspaceInfo: *topo.NewKeyspaceInfo(keyspace, nil, -1),
Status: "deleted",
})
return nil
}
// GetKeyspace is part of the topo.Server interface
func (zkts *Server) GetKeyspace(ctx context.Context, keyspace string) (*topo.KeyspaceInfo, error) {
keyspacePath := path.Join(globalKeyspacesPath, keyspace)
data, stat, err := zkts.zconn.Get(keyspacePath)
if err != nil {
if zookeeper.IsError(err, zookeeper.ZNONODE) {
err = topo.ErrNoNode
}
return nil, err
}
k := &pb.Keyspace{}
if err = json.Unmarshal([]byte(data), k); err != nil {
return nil, fmt.Errorf("bad keyspace data %v", err)
}
return topo.NewKeyspaceInfo(keyspace, k, int64(stat.Version())), nil
}
// GetKeyspaces is part of the topo.Server interface
func (zkts *Server) GetKeyspaces(ctx context.Context) ([]string, error) {
children, _, err := zkts.zconn.Children(globalKeyspacesPath)
if err != nil {
if zookeeper.IsError(err, zookeeper.ZNONODE) {
return nil, nil
}
return nil, err
}
sort.Strings(children)
return children, nil
}
// DeleteKeyspaceShards is part of the topo.Server interface
func (zkts *Server) DeleteKeyspaceShards(ctx context.Context, keyspace string) error {
shardsPath := path.Join(globalKeyspacesPath, keyspace, "shards")
if err := zk.DeleteRecursive(zkts.zconn, shardsPath, -1); err != nil && !zookeeper.IsError(err, zookeeper.ZNONODE) {
return err
}
event.Dispatch(&events.KeyspaceChange{
KeyspaceInfo: *topo.NewKeyspaceInfo(keyspace, nil, -1),
Status: "deleted all shards",
})
return nil
}
| {
"content_hash": "c400f4a4dc28773f651f3704f570ee6a",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 118,
"avg_line_length": 27.261146496815286,
"alnum_prop": 0.7046728971962617,
"repo_name": "kmiku7/vitess-annotated",
"id": "75ce431110af3f8d5e94acc96d6ad96848e31b3e",
"size": "4280",
"binary": false,
"copies": "3",
"ref": "refs/heads/comment",
"path": "go/vt/zktopo/keyspace.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "40319"
},
{
"name": "CSS",
"bytes": "80739"
},
{
"name": "Go",
"bytes": "4515839"
},
{
"name": "HTML",
"bytes": "86600"
},
{
"name": "Java",
"bytes": "186832"
},
{
"name": "JavaScript",
"bytes": "71420"
},
{
"name": "Liquid",
"bytes": "15797"
},
{
"name": "Makefile",
"bytes": "7834"
},
{
"name": "PHP",
"bytes": "7167"
},
{
"name": "PLpgSQL",
"bytes": "10072"
},
{
"name": "Protocol Buffer",
"bytes": "61194"
},
{
"name": "Python",
"bytes": "964742"
},
{
"name": "Ruby",
"bytes": "465"
},
{
"name": "Shell",
"bytes": "53683"
},
{
"name": "Yacc",
"bytes": "18969"
}
],
"symlink_target": ""
} |
{% extends "notifications/_alerts/emails/base.html" %}
{% block content %}
<table cellspacing="0" cellpadding="0" align="left">
<tbody>
<tr>
<h3>Alert details</h3>
<strong>Period: </strong> {{ trigger.from|day_local:timezone }} - between {{ trigger.from|time_local:timezone }} and {{ trigger.time|time_local:timezone }}
<br><br>
<strong>Server:</strong> {{ server.name }} {% if server.ip_address %}({{ server.ip_address}}) {% endif %}
<br><br>
<strong>Process:</strong> {{ process.name }}
{% if trigger.average_value %}
- average value: {{ trigger.average_value }}
{% if alert.metric|lower == 'memory' %}MB {% else %}%{% endif %}
{% endif %}
<br><br>
<a target="_blank" href="{% base_url 'view_process' server_id=server|mongo_id %}?process={{ process|mongo_id }}&duration={{ alert.period }}&enddate={{ trigger.time }}">
View chart</a>
<br><br>
</tr>
</tbody>
</table>
<div align="left" class="article-content">
<multiline label="Description">
This notification was sent for alert: <br>
{{ server.name }}/{{ process.name }} - {{ alert.check }} {{ alert.metric }} {{ alert.above_below }}
{{ alert.metric_value }} {{ alert.metric_type }} for {% if alert.period > 60 %}
{{ alert.period|seconds_to_minutes }} minutes
{% else %}
{{alert.period}} seconds
{% endif %}
<br><br>
If you want to stop receiving these notifications, you can
<a target="_blank" href="{% base_url 'mute_alert' alert_id=alert|mongo_id %}">mute</a> or <a target="_blank" href="{% base_url 'edit_alert' alert_id=alert|mongo_id %}">edit</a> this alert
</multiline>
</div>
{% endblock content %} | {
"content_hash": "e9ece7f13f38759c16d2ed3dbd88391c",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 187,
"avg_line_length": 46.205128205128204,
"alnum_prop": 0.5660377358490566,
"repo_name": "martinrusev/amonone",
"id": "df537ec07347e966cc634fa53e3d67f3cfbdbe7e",
"size": "1802",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "amon/templates/notifications/_alerts/emails/process_alert.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "77950"
},
{
"name": "JavaScript",
"bytes": "28811"
},
{
"name": "Python",
"bytes": "180983"
},
{
"name": "Ruby",
"bytes": "131"
},
{
"name": "Shell",
"bytes": "5652"
}
],
"symlink_target": ""
} |
r"""Train Onsets and Frames piano transcription model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from magenta.common import tf_utils
from magenta.models.onsets_frames_transcription import constants
from magenta.models.onsets_frames_transcription import model
from magenta.models.onsets_frames_transcription import train_util
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('master', '',
'Name of the TensorFlow runtime to use.')
tf.app.flags.DEFINE_string(
'examples_path', None,
'Path to a TFRecord file of train/eval examples.')
tf.app.flags.DEFINE_string(
'model_dir', '~/tmp/onsets_frames',
'Path where checkpoints and summary events will be located during '
'training and evaluation. Separate subdirectories `train` and `eval` '
'will be created within this directory.')
tf.app.flags.DEFINE_integer('num_steps', 1000000,
'Number of training steps or `None` for infinite.')
tf.app.flags.DEFINE_integer(
'keep_checkpoint_max', 100,
'Maximum number of checkpoints to keep in `train` mode or 0 for infinite.')
tf.app.flags.DEFINE_string(
'hparams', '',
'A comma-separated list of `name=value` hyperparameter values.')
tf.app.flags.DEFINE_string(
'log', 'INFO',
'The threshold for what messages will be logged: '
'DEBUG, INFO, WARN, ERROR, or FATAL.')
def run(hparams, model_dir):
"""Run train/eval/test."""
train_util.train(
master=FLAGS.master,
model_dir=model_dir,
examples_path=FLAGS.examples_path,
hparams=hparams,
keep_checkpoint_max=FLAGS.keep_checkpoint_max,
num_steps=FLAGS.num_steps)
def main(unused_argv):
tf.logging.set_verbosity(FLAGS.log)
tf.app.flags.mark_flags_as_required(['examples_path'])
model_dir = os.path.expanduser(FLAGS.model_dir)
hparams = tf_utils.merge_hparams(constants.DEFAULT_HPARAMS,
model.get_default_hparams())
# Command line flags override any of the preceding hyperparameter values.
hparams.parse(FLAGS.hparams)
run(hparams, model_dir)
def console_entry_point():
tf.app.run(main)
if __name__ == '__main__':
console_entry_point()
| {
"content_hash": "fe2aa84fed487aa46c4ad517bb81711f",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 79,
"avg_line_length": 31.410958904109588,
"alnum_prop": 0.6916703009158308,
"repo_name": "adarob/magenta",
"id": "9422fb329157f94caacef498e23e2cd70cc983bd",
"size": "2878",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "magenta/models/onsets_frames_transcription/onsets_frames_transcription_train.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1933"
},
{
"name": "Python",
"bytes": "2941402"
},
{
"name": "Shell",
"bytes": "24986"
}
],
"symlink_target": ""
} |
require "spec_helper"
RSpec.describe "SP Product Ad Requests" do
before(:all) do
blurb = Blurb.new()
@resource = blurb.active_profile.product_ads
@resource_name = 'ad'
@create_hash = {
sku: Faker::Lorem.word,
state: ["enabled", "paused"].sample,
campaign_id: blurb.active_profile.campaigns(:sp).list(state_filter: 'enabled').first[:campaign_id],
ad_group_id: blurb.active_profile.product_ads.list(state_filter: 'enabled').first[:ad_group_id],
}
@update_hash = {
state: "enabled"
}
end
include_examples "request collection"
end
| {
"content_hash": "e83bba5f3fa963dfe8bfff068e77b238",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 105,
"avg_line_length": 28.285714285714285,
"alnum_prop": 0.6481481481481481,
"repo_name": "iserve-products/blurb",
"id": "d8836358ad0e03a13e9986092fd58559d5c7716c",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/blurb/product_ad_requests_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "42068"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\HttpKernel\Tests\Profiler;
use Symfony\Component\HttpKernel\Profiler\MemcachedProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\MemcachedMock;
/**
* @group legacy
*/
class MemcachedProfilerStorageTest extends AbstractProfilerStorageTest
{
protected static $storage;
protected function setUp()
{
$memcachedMock = new MemcachedMock();
$memcachedMock->addServer('127.0.0.1', 11211);
self::$storage = new MemcachedProfilerStorage('memcached://127.0.0.1:11211', '', '', 86400);
self::$storage->setMemcached($memcachedMock);
if (self::$storage) {
self::$storage->purge();
}
}
protected function tearDown()
{
if (self::$storage) {
self::$storage->purge();
self::$storage = false;
}
}
/**
* @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
*/
protected function getStorage()
{
return self::$storage;
}
}
| {
"content_hash": "8d60bc69104ddb6cb6e3ed90a2fb5792",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 100,
"avg_line_length": 24.266666666666666,
"alnum_prop": 0.6053113553113553,
"repo_name": "Condors/TunisiaMall",
"id": "f035f774f03bcf2dea8d7cd8e6fb2ea68683dcc4",
"size": "1328",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Profiler/MemcachedProfilerStorageTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "16927"
},
{
"name": "ApacheConf",
"bytes": "3688"
},
{
"name": "Batchfile",
"bytes": "690"
},
{
"name": "CSS",
"bytes": "836798"
},
{
"name": "HTML",
"bytes": "917753"
},
{
"name": "JavaScript",
"bytes": "1079135"
},
{
"name": "PHP",
"bytes": "196744"
},
{
"name": "Shell",
"bytes": "4247"
}
],
"symlink_target": ""
} |
package com.appeaser.sublimepickerlibrary.datepicker;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import com.appeaser.sublimepickerlibrary.R;
import com.appeaser.sublimepickerlibrary.utilities.Config;
import com.appeaser.sublimepickerlibrary.utilities.SUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* This displays a list of months in a calendar format with selectable days.
*/
class DayPickerViewPager extends ViewPager {
private static final String TAG = DayPickerViewPager.class.getSimpleName();
private final int MONTH_SCROLL_THRESHOLD;
private final int TOUCH_SLOP_SQUARED;
private final ArrayList<View> mMatchParentChildren = new ArrayList<>(1);
private Method mPopulateMethod;
private boolean mAlreadyTriedAccessingMethod;
private boolean mCanPickRange;
private DayPickerPagerAdapter mDayPickerPagerAdapter;
private float mInitialDownX, mInitialDownY;
private boolean mIsLongPressed = false;
private CheckForLongPress mCheckForLongPress;
private SelectedDate mTempSelectedDate;
// Scrolling support
private static final int SCROLLING_LEFT = -1;
private static final int NOT_SCROLLING = 0;
private static final int SCROLLING_RIGHT = 1;
private ScrollerRunnable mScrollerRunnable;
private int mScrollingDirection = NOT_SCROLLING;
public DayPickerViewPager(Context context) {
this(context, null);
}
public DayPickerViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
TOUCH_SLOP_SQUARED = ViewConfiguration.get(context).getScaledTouchSlop()
* ViewConfiguration.get(context).getScaledTouchSlop();
MONTH_SCROLL_THRESHOLD = context.getResources()
.getDimensionPixelSize(R.dimen.sp_month_scroll_threshold);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//populate();
// Use reflection
callPopulate();
// Everything below is mostly copied from FrameLayout.
int count = getChildCount();
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
// Account for padding too
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
if (SUtils.isApi_23_OrHigher()) {
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
}
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
count = mMatchParentChildren.size();
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec;
final int childHeightMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight(),
lp.width);
}
if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTop() + getPaddingBottom(),
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
mMatchParentChildren.clear();
}
private void initializePopulateMethod() {
try {
mPopulateMethod = ViewPager.class.getDeclaredMethod("populate", (Class[]) null);
mPopulateMethod.setAccessible(true);
} catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
mAlreadyTriedAccessingMethod = true;
}
private void callPopulate() {
if (!mAlreadyTriedAccessingMethod) {
initializePopulateMethod();
}
if (mPopulateMethod != null) {
// Multi-catch block cannot be used before API 19
//noinspection TryWithIdenticalCatches
try {
mPopulateMethod.invoke(this);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "Could not call `ViewPager.populate()`");
}
}
protected void setCanPickRange(boolean canPickRange) {
mCanPickRange = canPickRange;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!mCanPickRange) {
return super.onInterceptTouchEvent(ev);
}
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (Config.DEBUG) {
Log.i(TAG, "OITE: DOWN");
}
mInitialDownX = ev.getX();
mInitialDownY = ev.getY();
if (mCheckForLongPress == null) {
mCheckForLongPress = new CheckForLongPress();
}
postDelayed(mCheckForLongPress, ViewConfiguration.getLongPressTimeout());
} else if (ev.getAction() == MotionEvent.ACTION_UP
|| ev.getAction() == MotionEvent.ACTION_CANCEL) {
if (Config.DEBUG) {
Log.i(TAG, "OITE: (UP || CANCEL)");
}
if (mCheckForLongPress != null) {
removeCallbacks(mCheckForLongPress);
}
mIsLongPressed = false;
mInitialDownX = -1;
mInitialDownY = -1;
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
if (Config.DEBUG) {
Log.i(TAG, "OITE: MOVE");
}
if (!isStillALongPress((int) ev.getX(), (int) ev.getY())) {
if (Config.DEBUG) {
Log.i(TAG, "OITE: MOVED TOO MUCH, CANCELLING CheckForLongPress Runnable");
}
if (mCheckForLongPress != null) {
removeCallbacks(mCheckForLongPress);
}
}
}
return mIsLongPressed || super.onInterceptTouchEvent(ev);
}
private boolean isStillALongPress(int x, int y) {
return (((x - mInitialDownX) * (x - mInitialDownX))
+ ((y - mInitialDownY) * (y - mInitialDownY))) <= TOUCH_SLOP_SQUARED;
}
private class CheckForLongPress implements Runnable {
@Override
public void run() {
if (mDayPickerPagerAdapter != null) {
mTempSelectedDate = mDayPickerPagerAdapter.resolveStartDateForRange((int) mInitialDownX,
(int) mInitialDownY, getCurrentItem());
if (mTempSelectedDate != null) {
if (Config.DEBUG) {
Log.i(TAG, "CheckForLongPress Runnable Fired");
}
mIsLongPressed = true;
mDayPickerPagerAdapter.onDateRangeSelectionStarted(mTempSelectedDate);
}
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mCanPickRange) {
return super.onTouchEvent(ev);
}
// looks like the ViewPager wants to step in
if (mCheckForLongPress != null) {
removeCallbacks(mCheckForLongPress);
}
if (mIsLongPressed && ev.getAction() == MotionEvent.ACTION_UP
|| ev.getAction() == MotionEvent.ACTION_CANCEL) {
if (Config.DEBUG) {
Log.i(TAG, "OTE: LONGPRESS && (UP || CANCEL)");
}
if (ev.getAction() == MotionEvent.ACTION_UP) {
if (mDayPickerPagerAdapter != null) {
mTempSelectedDate = mDayPickerPagerAdapter.resolveEndDateForRange((int) ev.getX(),
(int) ev.getY(), getCurrentItem(), false);
mDayPickerPagerAdapter.onDateRangeSelectionEnded(mTempSelectedDate);
}
}
mIsLongPressed = false;
mInitialDownX = -1;
mInitialDownY = -1;
mScrollingDirection = NOT_SCROLLING;
if (mScrollerRunnable != null) {
removeCallbacks(mScrollerRunnable);
}
//return true;
} else if (mIsLongPressed && ev.getAction() == MotionEvent.ACTION_DOWN) {
if (Config.DEBUG) {
Log.i(TAG, "OTE: LONGPRESS && DOWN");
}
mScrollingDirection = NOT_SCROLLING;
} else if (mIsLongPressed && ev.getAction() == MotionEvent.ACTION_MOVE) {
if (Config.DEBUG) {
Log.i(TAG, "OTE: LONGPRESS && MOVE");
}
int direction = resolveDirectionForScroll(ev.getX());
boolean directionChanged = mScrollingDirection != direction;
if (directionChanged) {
if (mScrollerRunnable != null) {
removeCallbacks(mScrollerRunnable);
}
}
if (mScrollerRunnable == null) {
mScrollerRunnable = new ScrollerRunnable();
}
mScrollingDirection = direction;
if (mScrollingDirection == NOT_SCROLLING) {
if (mDayPickerPagerAdapter != null) {
mTempSelectedDate = mDayPickerPagerAdapter.resolveEndDateForRange((int) ev.getX(),
(int) ev.getY(), getCurrentItem(), true);
if (mTempSelectedDate != null) {
mDayPickerPagerAdapter.onDateRangeSelectionUpdated(mTempSelectedDate);
}
}
} else if (directionChanged) { // SCROLLING_LEFT || SCROLLING_RIGHT
post(mScrollerRunnable);
}
}
return mIsLongPressed || super.onTouchEvent(ev);
}
private int resolveDirectionForScroll(float x) {
if (x - getLeft() < MONTH_SCROLL_THRESHOLD) {
return SCROLLING_LEFT;
} else if (getRight() - x < MONTH_SCROLL_THRESHOLD) {
return SCROLLING_RIGHT;
}
return NOT_SCROLLING;
}
private class ScrollerRunnable implements Runnable {
@Override
public void run() {
if (mScrollingDirection == NOT_SCROLLING) {
return;
}
final int direction = mScrollingDirection;
// Animation is expensive for accessibility services since it sends
// lots of scroll and content change events.
final boolean animate = true; //!mAccessibilityManager.isEnabled()
// ViewPager clamps input values, so we don't need to worry
// about passing invalid indices.
setCurrentItem(getCurrentItem() + direction, animate);
// Four times the default anim duration
postDelayed(this, 1000L);
}
}
// May need to refer to this later
/*@Override
public boolean onTouchEvent(MotionEvent ev) {
// looks like the ViewPager wants to step in
if (mCheckForLongPress != null) {
removeCallbacks(mCheckForLongPress);
}
if (mIsLongPressed && ev.getAction() == MotionEvent.ACTION_UP
|| ev.getAction() == MotionEvent.ACTION_CANCEL) {
if (Config.DEBUG) {
Log.i(TAG, "OTE: LONGPRESS && (UP || CANCEL)");
}
if (ev.getAction() == MotionEvent.ACTION_UP) {
if (mDayPickerPagerAdapter != null) {
mTempSelectedDate = mDayPickerPagerAdapter.resolveEndDateForRange((int)ev.getX(),
(int)ev.getY(), getCurrentItem(), false);
mDayPickerPagerAdapter.onDateRangeSelectionEnded(mTempSelectedDate);
}
}
mIsLongPressed = false;
mInitialDownX = -1;
mInitialDownY = -1;
if (mScrollerRunnable != null) {
removeCallbacks(mScrollerRunnable);
}
//return true;
} else if (mIsLongPressed && ev.getAction() == MotionEvent.ACTION_DOWN) {
if (Config.DEBUG) {
Log.i(TAG, "OTE: LONGPRESS && DOWN");
}
} else if (mIsLongPressed && ev.getAction() == MotionEvent.ACTION_MOVE) {
if (Config.DEBUG) {
Log.i(TAG, "OTE: LONGPRESS && MOVE");
}
int direction = resolveDirectionForScroll(ev.getX(), ev.getY());
if (direction == 0) {
mScrollingLeft = false;
mScrollingRight = false;
if (mScrollerRunnable != null) {
removeCallbacks(mScrollerRunnable);
}
if (mDayPickerPagerAdapter != null) {
mTempSelectedDate = mDayPickerPagerAdapter.resolveEndDateForRange((int)ev.getX(),
(int)ev.getY(), getCurrentItem(), true);
if (mTempSelectedDate != null) {
mDayPickerPagerAdapter.onDateRangeSelectionUpdated(mTempSelectedDate);
}
}
} else if (direction == -1) {
if (mScrollingLeft) {
// nothing
} else if (mScrollingRight) {
mScrollingRight = false;
mScrollingLeft = true;
if (mScrollerRunnable != null) {
removeCallbacks(mScrollerRunnable);
}
if (mScrollerRunnable == null) {
mScrollerRunnable = new ScrollerRunnable();
}
post(mScrollerRunnable);
} else {
mScrollingLeft = true;
if (mScrollerRunnable == null) {
mScrollerRunnable = new ScrollerRunnable();
}
post(mScrollerRunnable);
}
} else if (direction == 1) {
if (mScrollingRight) {
// nothing
} else if (mScrollingLeft) {
mScrollingLeft = false;
mScrollingRight = true;
if (mScrollerRunnable != null) {
removeCallbacks(mScrollerRunnable);
}
if (mScrollerRunnable == null) {
mScrollerRunnable = new ScrollerRunnable();
}
post(mScrollerRunnable);
} else {
mScrollingRight = true;
if (mScrollerRunnable == null) {
mScrollerRunnable = new ScrollerRunnable();
}
post(mScrollerRunnable);
}
}
}
return mIsLongPressed || super.onTouchEvent(ev);
}
private int resolveDirectionForScroll(float x, float y) {
if (x - getLeft() < MONTH_SCROLL_THRESHOLD) {
return -1;
} else if (getRight() - x < MONTH_SCROLL_THRESHOLD) {
return 1;
}
return 0;
}
public class ScrollerRunnable implements Runnable {
@Override
public void run() {
final int direction;
if (mScrollingLeft) {
direction = -1;
} else if (mScrollingRight) {
direction = 1;
} else {
return;
}
// Animation is expensive for accessibility services since it sends
// lots of scroll and content change events.
final boolean animate = true; //!mAccessibilityManager.isEnabled()
// ViewPager clamps input values, so we don't need to worry
// about passing invalid indices.
setCurrentItem(getCurrentItem() + direction, animate);
// Four times the default anim duration
postDelayed(this, 1000L);
}
}*/
@Override
public void setAdapter(PagerAdapter adapter) {
super.setAdapter(adapter);
if (adapter instanceof DayPickerPagerAdapter) {
mDayPickerPagerAdapter = (DayPickerPagerAdapter) adapter;
}
}
@Override
public void onRestoreInstanceState(Parcelable state) {
// A 'null' hack may be required to keep the ViewPager
// from saving its own state.
// Since we were using two
// ViewPagers with the same ID, state restoration was
// having issues ==> wrong 'current' item. The approach
// I am currently using is to define two different layout
// files, which contain ViewPagers with different IDs.
// If this approach does not pan out, we will need to
// employ a 'null' hack where the ViewPager does not
// get to see 'state' in 'onRestoreInstanceState(Parecelable)'.
// super.onRestoreInstanceState(null);
super.onRestoreInstanceState(state);
}
}
| {
"content_hash": "1b80a446106b22b4927f181efe2c9630",
"timestamp": "",
"source": "github",
"line_count": 551,
"max_line_length": 104,
"avg_line_length": 35.740471869328495,
"alnum_prop": 0.5556796831361397,
"repo_name": "andela-kogunde/CheckSmarter",
"id": "b88529162aa11d679fd2e75b0d8047636c6504bc",
"size": "20312",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sublimepickerlibrary/src/main/java/com/appeaser/sublimepickerlibrary/datepicker/DayPickerViewPager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "622310"
},
{
"name": "Kotlin",
"bytes": "39634"
}
],
"symlink_target": ""
} |
package docker
import (
"fmt"
"net"
"net/url"
"strconv"
"sync"
"time"
"github.com/fsouza/go-dockerclient/testing"
"github.com/tsuru/config"
"github.com/tsuru/docker-cluster/cluster"
"github.com/tsuru/tsuru/app"
"github.com/tsuru/tsuru/db"
"github.com/tsuru/tsuru/iaas"
"github.com/tsuru/tsuru/provision/provisiontest"
"gopkg.in/check.v1"
"gopkg.in/mgo.v2/bson"
)
type TestHealerIaaS struct {
addr string
err error
delErr error
}
func (t *TestHealerIaaS) DeleteMachine(m *iaas.Machine) error {
if t.delErr != nil {
return t.delErr
}
return nil
}
func (t *TestHealerIaaS) CreateMachine(params map[string]string) (*iaas.Machine, error) {
if t.err != nil {
return nil, t.err
}
m := iaas.Machine{
Id: "m-" + t.addr,
Status: "running",
Address: t.addr,
}
return &m, nil
}
func (TestHealerIaaS) Describe() string {
return "iaas describe"
}
func urlPort(uStr string) int {
url, _ := url.Parse(uStr)
_, port, _ := net.SplitHostPort(url.Host)
portInt, _ := strconv.Atoi(port)
return portInt
}
func (s *S) TestHealerHealNode(c *check.C) {
rollback := startTestRepositoryServer()
defer rollback()
defer func() {
machines, _ := iaas.ListMachines()
for _, m := range machines {
m.Destroy()
}
}()
factory, iaasInst := newHealerIaaSConstructorWithInst("127.0.0.1")
iaas.RegisterIaasProvider("my-healer-iaas", factory)
_, err := iaas.CreateMachineForIaaS("my-healer-iaas", map[string]string{})
c.Assert(err, check.IsNil)
iaasInst.addr = "localhost"
node1, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
node2, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
config.Set("iaas:node-protocol", "http")
config.Set("iaas:node-port", urlPort(node2.URL()))
defer config.Unset("iaas:node-protocol")
defer config.Unset("iaas:node-port")
cluster, err := cluster.New(nil, &cluster.MapStorage{},
cluster.Node{Address: node1.URL()},
)
c.Assert(err, check.IsNil)
appInstance := provisiontest.NewFakeApp("myapp", "python", 0)
var p dockerProvisioner
err = p.Initialize()
c.Assert(err, check.IsNil)
p.cluster = cluster
defer p.Destroy(appInstance)
p.Provision(appInstance)
imageId, err := appCurrentImageName(appInstance.GetName())
c.Assert(err, check.IsNil)
customData := map[string]interface{}{
"procfile": "web: python ./myapp",
}
err = saveImageCustomData(imageId, customData)
c.Assert(err, check.IsNil)
_, err = addContainersWithHost(&changeUnitsPipelineArgs{
toHost: "127.0.0.1",
toAdd: map[string]*containersToAdd{"web": {Quantity: 1}},
app: appInstance,
imageId: imageId,
provisioner: &p,
})
c.Assert(err, check.IsNil)
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
appStruct := &app.App{
Name: appInstance.GetName(),
}
err = conn.Apps().Insert(appStruct)
c.Assert(err, check.IsNil)
defer conn.Apps().Remove(bson.M{"name": appStruct.Name})
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: &p,
disabledTime: 0,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes, err := p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
containers, err := p.listAllContainers()
c.Assert(err, check.IsNil)
c.Assert(containers, check.HasLen, 1)
c.Assert(containers[0].HostAddr, check.Equals, "127.0.0.1")
machines, err := iaas.ListMachines()
c.Assert(err, check.IsNil)
c.Assert(machines, check.HasLen, 1)
c.Assert(machines[0].Address, check.Equals, "127.0.0.1")
nodes[0].Metadata["iaas"] = "my-healer-iaas"
created, err := healer.healNode(&nodes[0])
c.Assert(err, check.IsNil)
c.Assert(created.Address, check.Equals, fmt.Sprintf("http://localhost:%d", urlPort(node2.URL())))
nodes, err = cluster.UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node2.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "localhost")
machines, err = iaas.ListMachines()
c.Assert(err, check.IsNil)
c.Assert(machines, check.HasLen, 1)
c.Assert(machines[0].Address, check.Equals, "localhost")
done := make(chan bool)
go func() {
for range time.Tick(100 * time.Millisecond) {
containers, err := p.listAllContainers()
if err == nil && len(containers) == 1 && containers[0].HostAddr == "localhost" {
close(done)
return
}
}
}()
select {
case <-done:
case <-time.After(5 * time.Second):
c.Fatal("Timed out waiting for containers to move")
}
}
func (s *S) TestHealerHealNodeWithoutIaaS(c *check.C) {
node1, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
cluster, err := cluster.New(nil, &cluster.MapStorage{},
cluster.Node{Address: node1.URL()},
)
c.Assert(err, check.IsNil)
var p dockerProvisioner
err = p.Initialize()
c.Assert(err, check.IsNil)
p.cluster = cluster
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: &p,
disabledTime: 0,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes, err := p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
created, err := healer.healNode(&nodes[0])
c.Assert(err, check.ErrorMatches, ".*error creating new machine.*")
c.Assert(created.Address, check.Equals, "")
nodes, err = p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
}
func (s *S) TestHealerHealNodeCreateMachineError(c *check.C) {
defer func() {
machines, _ := iaas.ListMachines()
for _, m := range machines {
m.Destroy()
}
}()
factory, iaasInst := newHealerIaaSConstructorWithInst("127.0.0.1")
iaas.RegisterIaasProvider("my-healer-iaas", factory)
_, err := iaas.CreateMachineForIaaS("my-healer-iaas", map[string]string{})
c.Assert(err, check.IsNil)
iaasInst.addr = "localhost"
iaasInst.err = fmt.Errorf("my create machine error")
node1, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
cluster, err := cluster.New(nil, &cluster.MapStorage{},
cluster.Node{Address: node1.URL()},
)
c.Assert(err, check.IsNil)
node1.PrepareFailure("pingErr", "/_ping")
cluster.StartActiveMonitoring(100 * time.Millisecond)
time.Sleep(300 * time.Millisecond)
cluster.StopActiveMonitoring()
var p dockerProvisioner
err = p.Initialize()
c.Assert(err, check.IsNil)
p.cluster = cluster
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: &p,
disabledTime: 0,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes, err := p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
c.Assert(nodes[0].FailureCount() > 0, check.Equals, true)
nodes[0].Metadata["iaas"] = "my-healer-iaas"
created, err := healer.healNode(&nodes[0])
c.Assert(err, check.ErrorMatches, ".*my create machine error.*")
c.Assert(created.Address, check.Equals, "")
c.Assert(nodes[0].FailureCount(), check.Equals, 0)
nodes, err = p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
}
func (s *S) TestHealerHealNodeWaitAndRegisterError(c *check.C) {
defer func() {
machines, _ := iaas.ListMachines()
for _, m := range machines {
m.Destroy()
}
}()
iaas.RegisterIaasProvider("my-healer-iaas", newHealerIaaSConstructor("127.0.0.1", nil))
_, err := iaas.CreateMachineForIaaS("my-healer-iaas", map[string]string{})
c.Assert(err, check.IsNil)
iaas.RegisterIaasProvider("my-healer-iaas", newHealerIaaSConstructor("localhost", nil))
node1, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
node2, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
node2.PrepareFailure("ping-failure", "/_ping")
config.Set("iaas:node-protocol", "http")
config.Set("iaas:node-port", urlPort(node2.URL()))
defer config.Unset("iaas:node-protocol")
defer config.Unset("iaas:node-port")
cluster, err := cluster.New(nil, &cluster.MapStorage{},
cluster.Node{Address: node1.URL()},
)
c.Assert(err, check.IsNil)
node1.PrepareFailure("pingErr", "/_ping")
cluster.StartActiveMonitoring(100 * time.Millisecond)
time.Sleep(300 * time.Millisecond)
cluster.StopActiveMonitoring()
var p dockerProvisioner
err = p.Initialize()
c.Assert(err, check.IsNil)
p.cluster = cluster
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: &p,
disabledTime: 0,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes, err := p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
c.Assert(nodes[0].FailureCount() > 0, check.Equals, true)
nodes[0].Metadata["iaas"] = "my-healer-iaas"
created, err := healer.healNode(&nodes[0])
c.Assert(err, check.ErrorMatches, ".*error registering new node.*")
c.Assert(created.Address, check.Equals, "")
c.Assert(nodes[0].FailureCount(), check.Equals, 0)
nodes, err = p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
}
func (s *S) TestHealerHealNodeDestroyError(c *check.C) {
rollback := startTestRepositoryServer()
defer rollback()
defer func() {
machines, _ := iaas.ListMachines()
for _, m := range machines {
m.Destroy()
}
machines, _ = iaas.ListMachines()
}()
factory, iaasInst := newHealerIaaSConstructorWithInst("127.0.0.1")
iaasInst.delErr = fmt.Errorf("my destroy error")
iaas.RegisterIaasProvider("my-healer-iaas", factory)
_, err := iaas.CreateMachineForIaaS("my-healer-iaas", map[string]string{})
c.Assert(err, check.IsNil)
iaasInst.addr = "localhost"
node1, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
node2, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
config.Set("iaas:node-protocol", "http")
config.Set("iaas:node-port", urlPort(node2.URL()))
defer config.Unset("iaas:node-protocol")
defer config.Unset("iaas:node-port")
cluster, err := cluster.New(nil, &cluster.MapStorage{},
cluster.Node{Address: node1.URL()},
)
c.Assert(err, check.IsNil)
var p dockerProvisioner
err = p.Initialize()
c.Assert(err, check.IsNil)
p.cluster = cluster
appInstance := provisiontest.NewFakeApp("myapp", "python", 0)
defer p.Destroy(appInstance)
p.Provision(appInstance)
imageId, err := appCurrentImageName(appInstance.GetName())
c.Assert(err, check.IsNil)
customData := map[string]interface{}{
"procfile": "web: python ./myapp",
}
err = saveImageCustomData(imageId, customData)
c.Assert(err, check.IsNil)
_, err = addContainersWithHost(&changeUnitsPipelineArgs{
toHost: "127.0.0.1",
toAdd: map[string]*containersToAdd{"web": {Quantity: 1}},
app: appInstance,
imageId: imageId,
provisioner: &p,
})
c.Assert(err, check.IsNil)
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
appStruct := &app.App{
Name: appInstance.GetName(),
}
err = conn.Apps().Insert(appStruct)
c.Assert(err, check.IsNil)
defer conn.Apps().Remove(bson.M{"name": appStruct.Name})
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: &p,
disabledTime: 0,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes, err := p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
containers, err := p.listAllContainers()
c.Assert(err, check.IsNil)
c.Assert(containers, check.HasLen, 1)
c.Assert(containers[0].HostAddr, check.Equals, "127.0.0.1")
machines, err := iaas.ListMachines()
c.Assert(err, check.IsNil)
c.Assert(machines, check.HasLen, 1)
c.Assert(machines[0].Address, check.Equals, "127.0.0.1")
nodes[0].Metadata["iaas"] = "my-healer-iaas"
created, err := healer.healNode(&nodes[0])
c.Assert(err, check.IsNil)
c.Assert(created.Address, check.Equals, fmt.Sprintf("http://localhost:%d", urlPort(node2.URL())))
nodes, err = p.getCluster().UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node2.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "localhost")
machines, err = iaas.ListMachines()
c.Assert(err, check.IsNil)
c.Assert(machines, check.HasLen, 1)
c.Assert(machines[0].Address, check.Equals, "localhost")
done := make(chan bool)
go func() {
for range time.Tick(100 * time.Millisecond) {
containers, err := p.listAllContainers()
if err == nil && len(containers) == 1 && containers[0].HostAddr == "localhost" {
close(done)
return
}
}
}()
select {
case <-done:
case <-time.After(5 * time.Second):
c.Fatal("Timed out waiting for containers to move")
}
}
func (s *S) TestHealerHandleError(c *check.C) {
rollback := startTestRepositoryServer()
defer rollback()
defer func() {
machines, _ := iaas.ListMachines()
for _, m := range machines {
m.Destroy()
}
}()
factory, iaasInst := newHealerIaaSConstructorWithInst("127.0.0.1")
iaas.RegisterIaasProvider("my-healer-iaas", factory)
_, err := iaas.CreateMachineForIaaS("my-healer-iaas", map[string]string{})
c.Assert(err, check.IsNil)
iaasInst.addr = "localhost"
node1, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
node2, err := testing.NewServer("127.0.0.1:0", nil, nil)
c.Assert(err, check.IsNil)
config.Set("iaas:node-protocol", "http")
config.Set("iaas:node-port", urlPort(node2.URL()))
defer config.Unset("iaas:node-protocol")
defer config.Unset("iaas:node-port")
cluster, err := cluster.New(nil, &cluster.MapStorage{},
cluster.Node{Address: node1.URL()},
)
c.Assert(err, check.IsNil)
var p dockerProvisioner
err = p.Initialize()
c.Assert(err, check.IsNil)
p.cluster = cluster
appInstance := provisiontest.NewFakeApp("myapp", "python", 0)
defer p.Destroy(appInstance)
p.Provision(appInstance)
imageId, err := appCurrentImageName(appInstance.GetName())
c.Assert(err, check.IsNil)
customData := map[string]interface{}{
"procfile": "web: python ./myapp",
}
err = saveImageCustomData(imageId, customData)
c.Assert(err, check.IsNil)
_, err = addContainersWithHost(&changeUnitsPipelineArgs{
toHost: "127.0.0.1",
toAdd: map[string]*containersToAdd{"web": {Quantity: 1}},
app: appInstance,
imageId: imageId,
provisioner: &p,
})
c.Assert(err, check.IsNil)
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
appStruct := &app.App{
Name: appInstance.GetName(),
}
err = conn.Apps().Insert(appStruct)
c.Assert(err, check.IsNil)
defer conn.Apps().Remove(bson.M{"name": appStruct.Name})
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: &p,
disabledTime: 0,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes, err := cluster.UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node1.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "127.0.0.1")
machines, err := iaas.ListMachines()
c.Assert(err, check.IsNil)
c.Assert(machines, check.HasLen, 1)
c.Assert(machines[0].Address, check.Equals, "127.0.0.1")
nodes[0].Metadata["iaas"] = "my-healer-iaas"
nodes[0].Metadata["Failures"] = "2"
waitTime := healer.HandleError(&nodes[0])
c.Assert(waitTime, check.Equals, time.Duration(0))
nodes, err = cluster.UnfilteredNodes()
c.Assert(err, check.IsNil)
c.Assert(nodes, check.HasLen, 1)
c.Assert(urlPort(nodes[0].Address), check.Equals, urlPort(node2.URL()))
c.Assert(urlToHost(nodes[0].Address), check.Equals, "localhost")
machines, err = iaas.ListMachines()
c.Assert(err, check.IsNil)
c.Assert(machines, check.HasLen, 1)
c.Assert(machines[0].Address, check.Equals, "localhost")
healingColl, err := healingCollection()
c.Assert(err, check.IsNil)
defer healingColl.Close()
var events []healingEvent
err = healingColl.Find(nil).All(&events)
c.Assert(err, check.IsNil)
c.Assert(events, check.HasLen, 1)
c.Assert(events[0].Action, check.Equals, "node-healing")
c.Assert(events[0].StartTime, check.Not(check.DeepEquals), time.Time{})
c.Assert(events[0].EndTime, check.Not(check.DeepEquals), time.Time{})
c.Assert(events[0].Error, check.Equals, "")
c.Assert(events[0].Successful, check.Equals, true)
c.Assert(events[0].FailingNode.Address, check.Equals, fmt.Sprintf("http://127.0.0.1:%d/", urlPort(node1.URL())))
c.Assert(events[0].CreatedNode.Address, check.Equals, fmt.Sprintf("http://localhost:%d", urlPort(node2.URL())))
}
func (s *S) TestHealerHandleErrorDoesntTriggerEventIfNotNeeded(c *check.C) {
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: nil,
disabledTime: 20,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
node := cluster.Node{Address: "addr", Metadata: map[string]string{
"Failures": "2",
"LastSuccess": "something",
}}
waitTime := healer.HandleError(&node)
c.Assert(waitTime, check.Equals, time.Duration(20))
healingColl, err := healingCollection()
c.Assert(err, check.IsNil)
defer healingColl.Close()
var events []healingEvent
err = healingColl.Find(nil).All(&events)
c.Assert(err, check.IsNil)
c.Assert(events, check.HasLen, 0)
node = cluster.Node{Address: "addr", Metadata: map[string]string{
"Failures": "0",
"LastSuccess": "something",
"iaas": "invalid",
}}
waitTime = healer.HandleError(&node)
c.Assert(waitTime, check.Equals, time.Duration(20))
healingColl, err = healingCollection()
c.Assert(err, check.IsNil)
defer healingColl.Close()
err = healingColl.Find(nil).All(&events)
c.Assert(err, check.IsNil)
c.Assert(events, check.HasLen, 0)
node = cluster.Node{Address: "addr", Metadata: map[string]string{
"Failures": "2",
"iaas": "invalid",
}}
waitTime = healer.HandleError(&node)
c.Assert(waitTime, check.Equals, time.Duration(20))
healingColl, err = healingCollection()
c.Assert(err, check.IsNil)
defer healingColl.Close()
err = healingColl.Find(nil).All(&events)
c.Assert(err, check.IsNil)
c.Assert(events, check.HasLen, 0)
}
func (s *S) TestHealerHandleErrorDoesntTriggerEventIfHealingCountTooLarge(c *check.C) {
nodes := []cluster.Node{
{Address: "addr1"}, {Address: "addr2"}, {Address: "addr3"}, {Address: "addr4"},
{Address: "addr5"}, {Address: "addr6"}, {Address: "addr7"}, {Address: "addr8"},
}
for i := 0; i < len(nodes)-1; i++ {
evt, err := newHealingEvent(nodes[i])
c.Assert(err, check.IsNil)
err = evt.update(nodes[i+1], nil)
c.Assert(err, check.IsNil)
}
iaas.RegisterIaasProvider("my-healer-iaas", newHealerIaaSConstructor("127.0.0.1", nil))
healer := nodeHealer{
locks: make(map[string]*sync.Mutex),
provisioner: nil,
disabledTime: 20,
failuresBeforeHealing: 1,
waitTimeNewMachine: time.Second,
}
nodes[7].Metadata = map[string]string{
"Failures": "2",
"LastSuccess": "something",
"iaas": "my-healer-iaas",
}
waitTime := healer.HandleError(&nodes[7])
c.Assert(waitTime, check.Equals, time.Duration(20))
healingColl, err := healingCollection()
c.Assert(err, check.IsNil)
defer healingColl.Close()
var events []healingEvent
err = healingColl.Find(nil).All(&events)
c.Assert(err, check.IsNil)
c.Assert(events, check.HasLen, 7)
}
| {
"content_hash": "92851ce8e2ee78085f938e6d80b0fc9d",
"timestamp": "",
"source": "github",
"line_count": 624,
"max_line_length": 113,
"avg_line_length": 32.8349358974359,
"alnum_prop": 0.6876860754551223,
"repo_name": "RichardKnop/tsuru",
"id": "6fa5986d1573d357d4af3974b4ef7c8e6c470080",
"size": "20648",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "provision/docker/healer_node_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "2262657"
},
{
"name": "HTML",
"bytes": "315"
},
{
"name": "Makefile",
"bytes": "3751"
},
{
"name": "Shell",
"bytes": "7915"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.NodeFactory;
using Umbraco.Web;
namespace InfoCaster.Umbraco.UrlTracker.Models
{
public class UrlTrackerDomain
{
public int Id { get; set; }
public int NodeId { get; set; }
public string Name { get; set; }
public Node Node { get { return new Node(NodeId); } }
public string UrlWithDomain
{
get
{
var node = Node;
if (UrlTrackerSettings.HasDomainOnChildNode && node.Parent != null)
{
using (InfoCaster.Umbraco.UrlTracker.Helpers.ContextHelper.EnsureHttpContext())
{
// not sure if this will ever occur because the ensurehttpcontext is now added...
if (UmbracoContext.Current != null)
{
/*var url = new Node(node.Id).Url;
return url;*/
return Node.Url; // do not re-instantiate
}
else
{
return string.Format("{0}{1}{2}", HttpContext.Current != null ? HttpContext.Current.Request.Url.Scheme : Uri.UriSchemeHttp, Uri.SchemeDelimiter, HttpContext.Current.Request.Url.Host + "/" + Node.Parent.UrlName + "/" + Node.UrlName);
}
}
}
else
{
if (Name.Contains(Uri.UriSchemeHttp))
{
return Name;
}
else
{
return string.Format("{0}{1}{2}", HttpContext.Current != null ? HttpContext.Current.Request.Url.Scheme : Uri.UriSchemeHttp, Uri.SchemeDelimiter, Name);
}
}
}
}
public UrlTrackerDomain() { }
public UrlTrackerDomain(int id, int nodeId, string name)
{
Id = id;
NodeId = nodeId;
Name = name;
}
public override string ToString()
{
return UrlWithDomain;
}
}
} | {
"content_hash": "2e5be00a73e3f2d695f641dede8e100c",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 260,
"avg_line_length": 34.014925373134325,
"alnum_prop": 0.46643264589732336,
"repo_name": "GertyEngrie/UrlTracker",
"id": "79b2e1f4c4799fca54e646588dcc53764484ac64",
"size": "2281",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Models/UrlTrackerDomain.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "85145"
},
{
"name": "C#",
"bytes": "180576"
},
{
"name": "CSS",
"bytes": "16665"
},
{
"name": "JavaScript",
"bytes": "45794"
}
],
"symlink_target": ""
} |
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
| {
"content_hash": "f007a32114e0f8e68b8bf3f7fde8b62b",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 42,
"avg_line_length": 22.22222222222222,
"alnum_prop": 0.65,
"repo_name": "IrmantasLiepis/logo-design",
"id": "056cd1170b64ef9795b2e8a7c25ae548cc26db66",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "routes/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "631630"
},
{
"name": "HTML",
"bytes": "1301729"
},
{
"name": "JavaScript",
"bytes": "83986"
},
{
"name": "TypeScript",
"bytes": "316006"
}
],
"symlink_target": ""
} |
package org.apache.geronimo.kernel.config;
import java.net.URI;
import javax.management.ObjectName;
import org.apache.geronimo.gbean.GBeanData;
import org.apache.geronimo.kernel.GBeanNotFoundException;
/**
* A specialized ConfigurationManager that can change the set of GBeans
* included in the configuration at runtime.
*
* @version $Rev$ $Date$
*/
public interface EditableConfigurationManager extends ConfigurationManager {
/**
* Adds a new GBean to an existing Configuration.
* @param configID The configuration to add the GBean to.
* @param gbean The data representing the GBean to add.
* @param start If true, the GBean should be started as part of this call.
*/
void addGBeanToConfiguration(URI configID, GBeanData gbean, boolean start) throws InvalidConfigException;
/**
* Removes a GBean from a configuration. Note: this may simply mark it to
* not be loaded in the future, as opposed to actually removing it from
* the data in the config store.
* @param configID The configuration to remove the GBean from.
* @param gbean The ObjectName of the GBean to remove.
*/
void removeGBeanFromConfiguration(URI configID, ObjectName gbean) throws InvalidConfigException, GBeanNotFoundException;
}
| {
"content_hash": "edb2898f1d720a7093215058ee337ed5",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 124,
"avg_line_length": 40.375,
"alnum_prop": 0.7368421052631579,
"repo_name": "vibe13/geronimo",
"id": "2723c55b25208661afba9760439c00b56379c455",
"size": "1922",
"binary": false,
"copies": "2",
"ref": "refs/heads/1.0",
"path": "modules/kernel/src/java/org/apache/geronimo/kernel/config/EditableConfigurationManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29627"
},
{
"name": "CSS",
"bytes": "47972"
},
{
"name": "HTML",
"bytes": "838469"
},
{
"name": "Java",
"bytes": "8975734"
},
{
"name": "JavaScript",
"bytes": "906"
},
{
"name": "Shell",
"bytes": "32814"
},
{
"name": "XSLT",
"bytes": "4468"
}
],
"symlink_target": ""
} |
emacsclient -create-frame --nw --alternate-editor="" "$@"
| {
"content_hash": "36cfe6f32c5239a7a48cdaa21d43c7a1",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 57,
"avg_line_length": 58,
"alnum_prop": 0.6724137931034483,
"repo_name": "KyleOndy/dotfiles",
"id": "d6c46726462fe315d1879c4c5a2c546c78c514ba",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "nix/pkgs/my-scripts/scripts/emacs.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7145"
},
{
"name": "Dockerfile",
"bytes": "1048"
},
{
"name": "HCL",
"bytes": "4372"
},
{
"name": "Lua",
"bytes": "8161"
},
{
"name": "Makefile",
"bytes": "5150"
},
{
"name": "Nix",
"bytes": "162145"
},
{
"name": "Python",
"bytes": "6070"
},
{
"name": "Shell",
"bytes": "22328"
},
{
"name": "Vim Script",
"bytes": "7920"
}
],
"symlink_target": ""
} |
namespace EliotJones.DataTable.Types
{
using System.Reflection;
public class ExtendedPropertyInfo
{
public string FieldName { get; set; }
public PropertyInfo PropertyInfo { get; set; }
public int ColumnIndex { get; set; }
public ExtendedPropertyInfo(string fieldName, PropertyInfo propertyInfo, int columnIndex)
{
this.FieldName = fieldName;
this.PropertyInfo = propertyInfo;
this.ColumnIndex = columnIndex;
}
}
}
| {
"content_hash": "cb2b1b7d1aa0c4a94bd55d628cd72f1d",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 97,
"avg_line_length": 25.95,
"alnum_prop": 0.6339113680154143,
"repo_name": "EliotJones/DataTable",
"id": "1e753bf2dc9d1c881eefcb10e286d4f093f70248",
"size": "521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EliotJones.DataTable/Types/ExtendedPropertyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "114804"
}
],
"symlink_target": ""
} |
import json
import os
import random
import unittest
import warnings
from copy import deepcopy
import numpy as np
from scipy.misc import central_diff_weights
from pymatgen.analysis.elasticity.elastic import (
ComplianceTensor,
ElasticTensor,
ElasticTensorExpansion,
NthOrderElasticTensor,
diff_fit,
find_eq_stress,
generate_pseudo,
get_diff_coeff,
get_strain_state_dict,
)
from pymatgen.analysis.elasticity.strain import Deformation, Strain
from pymatgen.analysis.elasticity.stress import Stress
from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Structure
from pymatgen.core.tensors import Tensor
from pymatgen.core.units import FloatWithUnit
from pymatgen.util.testing import PymatgenTest
class ElasticTensorTest(PymatgenTest):
def setUp(self):
self.voigt_1 = [
[59.33, 28.08, 28.08, 0, 0, 0],
[28.08, 59.31, 28.07, 0, 0, 0],
[28.08, 28.07, 59.32, 0, 0, 0],
[0, 0, 0, 26.35, 0, 0],
[0, 0, 0, 0, 26.35, 0],
[0, 0, 0, 0, 0, 26.35],
]
mat = np.random.randn(6, 6)
mat = mat + np.transpose(mat)
self.rand_elastic_tensor = ElasticTensor.from_voigt(mat)
self.ft = np.array(
[
[
[[59.33, 0, 0], [0, 28.08, 0], [0, 0, 28.08]],
[[0, 26.35, 0], [26.35, 0, 0], [0, 0, 0]],
[[0, 0, 26.35], [0, 0, 0], [26.35, 0, 0]],
],
[
[[0, 26.35, 0], [26.35, 0, 0], [0, 0, 0]],
[[28.08, 0, 0], [0, 59.31, 0], [0, 0, 28.07]],
[[0, 0, 0], [0, 0, 26.35], [0, 26.35, 0]],
],
[
[[0, 0, 26.35], [0, 0, 0], [26.35, 0, 0]],
[[0, 0, 0], [0, 0, 26.35], [0, 26.35, 0]],
[[28.08, 0, 0], [0, 28.07, 0], [0, 0, 59.32]],
],
]
)
self.elastic_tensor_1 = ElasticTensor(self.ft)
filepath = os.path.join(PymatgenTest.TEST_FILES_DIR, "Sn_def_stress.json")
with open(filepath) as f:
self.def_stress_dict = json.load(f)
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "test_toec_data.json")) as f:
self.toec_dict = json.load(f)
self.structure = self.get_structure("Sn")
warnings.simplefilter("always")
def test_properties(self):
# compliance tensor
ct = ComplianceTensor.from_voigt(np.linalg.inv(self.elastic_tensor_1.voigt))
self.assertArrayAlmostEqual(ct, self.elastic_tensor_1.compliance_tensor)
# KG average properties
self.assertAlmostEqual(38.49111111111, self.elastic_tensor_1.k_voigt)
self.assertAlmostEqual(22.05866666666, self.elastic_tensor_1.g_voigt)
self.assertAlmostEqual(38.49110945133, self.elastic_tensor_1.k_reuss)
self.assertAlmostEqual(20.67146635306, self.elastic_tensor_1.g_reuss)
self.assertAlmostEqual(38.49111028122, self.elastic_tensor_1.k_vrh)
self.assertAlmostEqual(21.36506650986, self.elastic_tensor_1.g_vrh)
# universal anisotropy
self.assertAlmostEqual(0.33553509658699, self.elastic_tensor_1.universal_anisotropy)
# homogeneous poisson
self.assertAlmostEqual(0.26579965576472, self.elastic_tensor_1.homogeneous_poisson)
# voigt notation tensor
self.assertArrayAlmostEqual(self.elastic_tensor_1.voigt, self.voigt_1)
# young's modulus
self.assertAlmostEqual(54087787667.160583, self.elastic_tensor_1.y_mod)
# prop dict
prop_dict = self.elastic_tensor_1.property_dict
self.assertAlmostEqual(prop_dict["homogeneous_poisson"], 0.26579965576)
for k, v in prop_dict.items():
self.assertAlmostEqual(getattr(self.elastic_tensor_1, k), v)
def test_directional_elastic_mod(self):
self.assertAlmostEqual(
self.elastic_tensor_1.directional_elastic_mod([1, 0, 0]),
self.elastic_tensor_1.voigt[0, 0],
)
self.assertAlmostEqual(self.elastic_tensor_1.directional_elastic_mod([1, 1, 1]), 73.624444444)
def test_compliance_tensor(self):
stress = self.elastic_tensor_1.calculate_stress([0.01] + [0] * 5)
comp = self.elastic_tensor_1.compliance_tensor
strain = Strain(comp.einsum_sequence([stress]))
self.assertArrayAlmostEqual(strain.voigt, [0.01] + [0] * 5)
def test_directional_poisson_ratio(self):
v_12 = self.elastic_tensor_1.directional_poisson_ratio([1, 0, 0], [0, 1, 0])
self.assertAlmostEqual(v_12, 0.321, places=3)
def test_structure_based_methods(self):
# trans_velocity
self.assertAlmostEqual(1996.35019877, self.elastic_tensor_1.trans_v(self.structure))
# long_velocity
self.assertAlmostEqual(3534.68123832, self.elastic_tensor_1.long_v(self.structure))
# Snyder properties
self.assertAlmostEqual(18.06127074, self.elastic_tensor_1.snyder_ac(self.structure))
self.assertAlmostEqual(0.18937465, self.elastic_tensor_1.snyder_opt(self.structure))
self.assertAlmostEqual(18.25064540, self.elastic_tensor_1.snyder_total(self.structure))
# Clarke
self.assertAlmostEqual(0.3450307, self.elastic_tensor_1.clarke_thermalcond(self.structure))
# Cahill
self.assertAlmostEqual(0.37896275, self.elastic_tensor_1.cahill_thermalcond(self.structure))
# Debye
self.assertAlmostEqual(198.8037985019, self.elastic_tensor_1.debye_temperature(self.structure))
# structure-property dict
sprop_dict = self.elastic_tensor_1.get_structure_property_dict(self.structure)
self.assertAlmostEqual(sprop_dict["long_v"], 3534.68123832)
for val in sprop_dict.values():
self.assertFalse(isinstance(val, FloatWithUnit))
for k, v in sprop_dict.items():
if k == "structure":
self.assertEqual(v, self.structure)
else:
f = getattr(self.elastic_tensor_1, k)
if callable(f):
self.assertAlmostEqual(getattr(self.elastic_tensor_1, k)(self.structure), v)
else:
self.assertAlmostEqual(getattr(self.elastic_tensor_1, k), v)
# Test other sprop dict modes
sprop_dict = self.elastic_tensor_1.get_structure_property_dict(self.structure, include_base_props=False)
self.assertFalse("k_vrh" in sprop_dict)
# Test ValueError being raised for structure properties
test_et = deepcopy(self.elastic_tensor_1)
test_et[0][0][0][0] = -100000
prop_dict = test_et.property_dict
for attr_name in sprop_dict:
if attr_name not in (list(prop_dict.keys()) + ["structure"]):
self.assertRaises(ValueError, getattr(test_et, attr_name), self.structure)
self.assertRaises(ValueError, test_et.get_structure_property_dict, self.structure)
noval_sprop_dict = test_et.get_structure_property_dict(self.structure, ignore_errors=True)
self.assertIsNone(noval_sprop_dict["snyder_ac"])
def test_new(self):
self.assertArrayAlmostEqual(self.elastic_tensor_1, ElasticTensor(self.ft))
nonsymm = self.ft
nonsymm[0, 1, 2, 2] += 1.0
with warnings.catch_warnings(record=True) as w:
ElasticTensor(nonsymm)
self.assertEqual(len(w), 1)
badtensor1 = np.zeros((3, 3, 3))
badtensor2 = np.zeros((3, 3, 3, 2))
self.assertRaises(ValueError, ElasticTensor, badtensor1)
self.assertRaises(ValueError, ElasticTensor, badtensor2)
def test_from_pseudoinverse(self):
strain_list = [Strain.from_deformation(def_matrix) for def_matrix in self.def_stress_dict["deformations"]]
stress_list = [stress for stress in self.def_stress_dict["stresses"]]
with warnings.catch_warnings(record=True):
et_fl = -0.1 * ElasticTensor.from_pseudoinverse(strain_list, stress_list).voigt
self.assertArrayAlmostEqual(
et_fl.round(2),
[
[59.29, 24.36, 22.46, 0, 0, 0],
[28.06, 56.91, 22.46, 0, 0, 0],
[28.06, 25.98, 54.67, 0, 0, 0],
[0, 0, 0, 26.35, 0, 0],
[0, 0, 0, 0, 26.35, 0],
[0, 0, 0, 0, 0, 26.35],
],
)
def test_from_independent_strains(self):
strains = self.toec_dict["strains"]
stresses = self.toec_dict["stresses"]
with warnings.catch_warnings(record=True):
et = ElasticTensor.from_independent_strains(strains, stresses)
self.assertArrayAlmostEqual(et.voigt, self.toec_dict["C2_raw"], decimal=-1)
def test_energy_density(self):
film_elac = ElasticTensor.from_voigt(
[
[324.32, 187.3, 170.92, 0.0, 0.0, 0.0],
[187.3, 324.32, 170.92, 0.0, 0.0, 0.0],
[170.92, 170.92, 408.41, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 150.73, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 150.73, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 238.74],
]
)
dfm = Deformation(
[
[-9.86004855e-01, 2.27539582e-01, -4.64426035e-17],
[-2.47802121e-01, -9.91208483e-01, -7.58675185e-17],
[-6.12323400e-17, -6.12323400e-17, 1.00000000e00],
]
)
self.assertAlmostEqual(film_elac.energy_density(dfm.green_lagrange_strain), 0.00125664672793)
film_elac.energy_density(
Strain.from_deformation(
[
[0.99774738, 0.11520994, -0.0],
[-0.11520994, 0.99774738, 0.0],
[
-0.0,
-0.0,
1.0,
],
]
)
)
class ElasticTensorExpansionTest(PymatgenTest):
def setUp(self):
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "test_toec_data.json")) as f:
self.data_dict = json.load(f)
self.strains = [Strain(sm) for sm in self.data_dict["strains"]]
self.pk_stresses = [Stress(d) for d in self.data_dict["pk_stresses"]]
self.c2 = self.data_dict["C2_raw"]
self.c3 = self.data_dict["C3_raw"]
self.exp = ElasticTensorExpansion.from_voigt([self.c2, self.c3])
self.cu = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.623), ["Cu"], [[0] * 3])
indices = [(0, 0), (0, 1), (3, 3)]
values = [167.8, 113.5, 74.5]
cu_c2 = ElasticTensor.from_values_indices(values, indices, structure=self.cu, populate=True)
indices = [(0, 0, 0), (0, 0, 1), (0, 1, 2), (0, 3, 3), (0, 5, 5), (3, 4, 5)]
values = [-1507.0, -965.0, -71.0, -7.0, -901.0, 45.0]
cu_c3 = Tensor.from_values_indices(values, indices, structure=self.cu, populate=True)
self.exp_cu = ElasticTensorExpansion([cu_c2, cu_c3])
cu_c4 = Tensor.from_voigt(self.data_dict["Cu_fourth_order"])
self.exp_cu_4 = ElasticTensorExpansion([cu_c2, cu_c3, cu_c4])
warnings.simplefilter("ignore")
def tearDown(self):
warnings.simplefilter("default")
def test_init(self):
cijkl = Tensor.from_voigt(self.c2)
cijklmn = Tensor.from_voigt(self.c3)
exp = ElasticTensorExpansion([cijkl, cijklmn])
ElasticTensorExpansion.from_voigt([self.c2, self.c3])
self.assertEqual(exp.order, 3)
def test_from_diff_fit(self):
ElasticTensorExpansion.from_diff_fit(self.strains, self.pk_stresses)
def test_calculate_stress(self):
calc_stress = self.exp.calculate_stress(self.strains[0])
self.assertArrayAlmostEqual(self.pk_stresses[0], calc_stress, decimal=2)
def test_energy_density(self):
edensity = self.exp.energy_density(self.strains[0])
self.assertAlmostEqual(edensity, 1.36363099e-4)
def test_gruneisen(self):
# Get GGT
ggt = self.exp_cu.get_ggt([1, 0, 0], [0, 1, 0])
self.assertArrayAlmostEqual(np.eye(3) * np.array([4.92080537, 4.2852349, -0.7147651]), ggt)
# Get TGT
tgt = self.exp_cu.get_tgt()
self.assertArrayAlmostEqual(tgt, np.eye(3) * 2.59631832)
# Get heat capacity
c0 = self.exp_cu.get_heat_capacity(0, self.cu, [1, 0, 0], [0, 1, 0])
self.assertEqual(c0, 0.0)
c = self.exp_cu.get_heat_capacity(300, self.cu, [1, 0, 0], [0, 1, 0])
self.assertAlmostEqual(c, 8.285611958)
# Get Gruneisen parameter
gp = self.exp_cu.get_gruneisen_parameter()
self.assertAlmostEqual(gp, 2.59631832)
_ = self.exp_cu.get_gruneisen_parameter(temperature=200, structure=self.cu)
def test_thermal_expansion_coeff(self):
# TODO get rid of duplicates
alpha_dp = self.exp_cu.thermal_expansion_coeff(self.cu, 300, mode="dulong-petit")
alpha_dp_ground_truth = 6.3471959e-07 * np.ones((3, 3))
alpha_dp_ground_truth[np.diag_indices(3)] = 2.2875769e-7
self.assertArrayAlmostEqual(alpha_dp_ground_truth, alpha_dp, decimal=4)
alpha_debye = self.exp_cu.thermal_expansion_coeff(self.cu, 300, mode="debye")
alpha_comp = 5.9435148e-7 * np.ones((3, 3))
alpha_comp[np.diag_indices(3)] = 21.4533472e-06
self.assertArrayAlmostEqual(alpha_comp, alpha_debye)
def test_get_compliance_expansion(self):
ce_exp = self.exp_cu.get_compliance_expansion()
et_comp = ElasticTensorExpansion(ce_exp)
strain_orig = Strain.from_voigt([0.01, 0, 0, 0, 0, 0])
stress = self.exp_cu.calculate_stress(strain_orig)
strain_revert = et_comp.calculate_stress(stress)
self.assertArrayAlmostEqual(strain_orig, strain_revert, decimal=4)
def test_get_effective_ecs(self):
# Ensure zero strain is same as SOEC
test_zero = self.exp_cu.get_effective_ecs(np.zeros((3, 3)))
self.assertArrayAlmostEqual(test_zero, self.exp_cu[0])
s = np.zeros((3, 3))
s[0, 0] = 0.02
test_2percent = self.exp_cu.get_effective_ecs(s)
diff = test_2percent - test_zero
self.assertArrayAlmostEqual(self.exp_cu[1].einsum_sequence([s]), diff)
def test_get_strain_from_stress(self):
strain = Strain.from_voigt([0.05, 0, 0, 0, 0, 0])
stress3 = self.exp_cu.calculate_stress(strain)
strain_revert3 = self.exp_cu.get_strain_from_stress(stress3)
self.assertArrayAlmostEqual(strain, strain_revert3, decimal=2)
# fourth order
stress4 = self.exp_cu_4.calculate_stress(strain)
strain_revert4 = self.exp_cu_4.get_strain_from_stress(stress4)
self.assertArrayAlmostEqual(strain, strain_revert4, decimal=2)
def test_get_yield_stress(self):
self.exp_cu_4.get_yield_stress([1, 0, 0])
class NthOrderElasticTensorTest(PymatgenTest):
def setUp(self):
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "test_toec_data.json")) as f:
self.data_dict = json.load(f)
self.strains = [Strain(sm) for sm in self.data_dict["strains"]]
self.pk_stresses = [Stress(d) for d in self.data_dict["pk_stresses"]]
self.c2 = NthOrderElasticTensor.from_voigt(self.data_dict["C2_raw"])
self.c3 = NthOrderElasticTensor.from_voigt(self.data_dict["C3_raw"])
def test_init(self):
c2 = NthOrderElasticTensor(self.c2.tolist())
c3 = NthOrderElasticTensor(self.c3.tolist())
c4 = NthOrderElasticTensor(np.zeros([3] * 8))
for n, c in enumerate([c2, c3, c4]):
self.assertEqual(c.order, n + 2)
self.assertRaises(ValueError, NthOrderElasticTensor, np.zeros([3] * 5))
def test_from_diff_fit(self):
c3 = NthOrderElasticTensor.from_diff_fit(
self.strains,
self.pk_stresses,
eq_stress=self.data_dict["eq_stress"],
order=3,
)
self.assertArrayAlmostEqual(c3.voigt, self.data_dict["C3_raw"], decimal=2)
def test_calculate_stress(self):
calc_stress = self.c2.calculate_stress(self.strains[0])
self.assertArrayAlmostEqual(self.pk_stresses[0], calc_stress, decimal=0)
# Test calculation from voigt strain
self.c2.calculate_stress(self.strains[0].voigt)
def test_energy_density(self):
self.c3.energy_density(self.strains[0])
class DiffFitTest(PymatgenTest):
"""
Tests various functions related to diff fitting
"""
def setUp(self):
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "test_toec_data.json")) as f:
self.data_dict = json.load(f)
self.strains = [Strain(sm) for sm in self.data_dict["strains"]]
self.pk_stresses = [Stress(d) for d in self.data_dict["pk_stresses"]]
def test_get_strain_state_dict(self):
strain_inds = [(0,), (1,), (2,), (1, 3), (1, 2, 3)]
vecs = {}
strain_states = []
for strain_ind in strain_inds:
ss = np.zeros(6)
np.put(ss, strain_ind, 1)
strain_states.append(tuple(ss))
vec = np.zeros((4, 6))
rand_values = np.random.uniform(0.1, 1, 4)
for i in strain_ind:
vec[:, i] = rand_values
vecs[strain_ind] = vec
all_strains = [Strain.from_voigt(v).zeroed() for vec in vecs.values() for v in vec]
random.shuffle(all_strains)
all_stresses = [Stress.from_voigt(np.random.random(6)).zeroed() for s in all_strains]
strain_dict = {k.tostring(): v for k, v in zip(all_strains, all_stresses)}
ss_dict = get_strain_state_dict(all_strains, all_stresses, add_eq=False)
# Check length of ss_dict
self.assertEqual(len(strain_inds), len(ss_dict))
# Check sets of strain states are correct
self.assertEqual(set(strain_states), set(ss_dict.keys()))
for strain_state, data in ss_dict.items():
# Check correspondence of strains/stresses
for strain, stress in zip(data["strains"], data["stresses"]):
self.assertArrayAlmostEqual(
Stress.from_voigt(stress),
strain_dict[Strain.from_voigt(strain).tostring()],
)
# Add test to ensure zero strain state doesn't cause issue
strains, stresses = [Strain.from_voigt([-0.01] + [0] * 5)], [Stress(np.eye(3))]
ss_dict = get_strain_state_dict(strains, stresses)
self.assertArrayAlmostEqual(list(ss_dict.keys()), [[1, 0, 0, 0, 0, 0]])
def test_find_eq_stress(self):
test_strains = deepcopy(self.strains)
test_stresses = deepcopy(self.pk_stresses)
with warnings.catch_warnings(record=True):
no_eq = find_eq_stress(test_strains, test_stresses)
self.assertArrayAlmostEqual(no_eq, np.zeros((3, 3)))
test_strains[3] = Strain.from_voigt(np.zeros(6))
eq_stress = find_eq_stress(test_strains, test_stresses)
self.assertArrayAlmostEqual(test_stresses[3], eq_stress)
def test_get_diff_coeff(self):
forward_11 = get_diff_coeff([0, 1], 1)
forward_13 = get_diff_coeff([0, 1, 2, 3], 1)
backward_26 = get_diff_coeff(np.arange(-6, 1), 2)
central_29 = get_diff_coeff(np.arange(-4, 5), 2)
self.assertArrayAlmostEqual(forward_11, [-1, 1])
self.assertArrayAlmostEqual(forward_13, [-11.0 / 6, 3, -3.0 / 2, 1.0 / 3])
self.assertArrayAlmostEqual(
backward_26,
[
137.0 / 180,
-27.0 / 5,
33.0 / 2,
-254.0 / 9,
117.0 / 4,
-87.0 / 5,
203.0 / 45,
],
)
self.assertArrayAlmostEqual(central_29, central_diff_weights(9, 2))
def test_generate_pseudo(self):
strain_states = np.eye(6).tolist()
m2, abs = generate_pseudo(strain_states, order=2)
m3, abs = generate_pseudo(strain_states, order=3)
m4, abs = generate_pseudo(strain_states, order=4)
def test_fit(self):
diff_fit(self.strains, self.pk_stresses, self.data_dict["eq_stress"])
reduced = [(e, pk) for e, pk in zip(self.strains, self.pk_stresses) if not (abs(abs(e) - 0.05) < 1e-10).any()]
# Get reduced dataset
r_strains, r_pk_stresses = zip(*reduced)
with warnings.catch_warnings(record=True):
c2 = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=2)
c2, c3, c4 = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=4)
c2, c3 = diff_fit(self.strains, self.pk_stresses, self.data_dict["eq_stress"], order=3)
c2_red, c3_red = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=3)
self.assertArrayAlmostEqual(c2.voigt, self.data_dict["C2_raw"])
self.assertArrayAlmostEqual(c3.voigt, self.data_dict["C3_raw"], decimal=5)
self.assertArrayAlmostEqual(c2, c2_red, decimal=0)
self.assertArrayAlmostEqual(c3, c3_red, decimal=-1)
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "bed3b84c9bfdfab6ae0e3ef6915496f9",
"timestamp": "",
"source": "github",
"line_count": 478,
"max_line_length": 118,
"avg_line_length": 44.44979079497908,
"alnum_prop": 0.5946251235468537,
"repo_name": "davidwaroquiers/pymatgen",
"id": "db305bdaf5d12e6a82e74e43c49cc61d6e8494f2",
"size": "21247",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pymatgen/analysis/elasticity/tests/test_elastic.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "87"
},
{
"name": "CSS",
"bytes": "7572"
},
{
"name": "Cython",
"bytes": "38793"
},
{
"name": "HTML",
"bytes": "12642493"
},
{
"name": "OpenEdge ABL",
"bytes": "312"
},
{
"name": "Python",
"bytes": "9213466"
},
{
"name": "Roff",
"bytes": "1407429"
},
{
"name": "Shell",
"bytes": "12027"
}
],
"symlink_target": ""
} |
set +e
# Case insensitive string comparison
shopt -s nocaseglob
#shopt -s nocasematch
ECHO=echo
OS=
ARCH=
WORD=
NO_UI=${NO_UI-}
GIT_PROTOCOL=${GIT_PROTOCOL:="git"}
GIT_URL=${GIT_URL:=$GIT_PROTOCOL"://factorcode.org/git/factor.git"}
SCRIPT_ARGS="$*"
# return 1 on found
test_program_installed() {
if ! [[ -n `type -p $1` ]] ; then
return 0;
fi
return 1;
}
# return 1 on found
test_programs_installed() {
installed=0;
$ECHO -n "Checking for all($*)..."
for i in $* ;
do
test_program_installed $i
if [[ $? -eq 1 ]]; then
installed=$(( $installed + 1 ))
fi
done
if [[ $installed -eq $# ]] ; then
$ECHO "found!"
return 1
else
$ECHO "all not found."
return 0
fi
}
exit_script() {
if [[ $FIND_MAKE_TARGET = true ]] ; then
# Must be echo not $ECHO
echo $MAKE_TARGET;
fi
exit $1
}
ensure_program_installed() {
installed=0;
$ECHO -n "Checking for any($*)..."
for i in $* ;
do
test_program_installed $i
if [[ $? -eq 1 ]]; then
$ECHO "found $i!"
installed=$(( $installed + 1 ))
return
fi
done
$ECHO "none found."
$ECHO -n "Install "
if [[ $# -eq 1 ]] ; then
$ECHO -n $1
else
$ECHO -n "any of [ $* ]"
fi
$ECHO " and try again."
if [[ $OS == macosx ]] ; then
$ECHO "If you have Xcode 4.3 or higher installed, you must install the"
$ECHO "Command Line Tools from Xcode Preferences > Downloads in order"
$ECHO "to build Factor."
fi
exit_script 1;
}
check_ret() {
RET=$?
if [[ $RET -ne 0 ]] ; then
$ECHO $1 failed
exit_script 2
fi
}
set_downloader() {
test_program_installed wget
if [[ $? -ne 0 ]] ; then
DOWNLOADER=wget
return
fi
test_program_installed curl
if [[ $? -ne 0 ]] ; then
DOWNLOADER="curl -f -O"
return
fi
$ECHO "error: wget or curl required"
exit_script 11
}
set_md5sum() {
test_program_installed md5sum
if [[ $? -ne 0 ]] ; then
MD5SUM=md5sum
else
MD5SUM="md5 -r"
fi
}
semver_into() {
RE_SEMVER="^([0-9]*)\.([0-9]*)\.([0-9]*)-?(.*)?$" # 3.3.3-5
CLANG_RE_OLD="^([0-9]*)\.([0-9]*)-?(.*)?$" # 3.3-5
if [[ $1 =~ $RE_SEMVER ]] ; then
export "$2=${BASH_REMATCH[1]}"
export "$3=${BASH_REMATCH[2]}"
export "$4=${BASH_REMATCH[3]}"
export "$5=${BASH_REMATCH[4]}"
elif [[ $1 =~ $CLANG_RE_OLD ]] ; then
export "$2=${BASH_REMATCH[1]}"
export "$3=${BASH_REMATCH[2]}"
export "$4=0"
export "$5=${BASH_REMATCH[3]}"
else
echo "unsupported version number, please report a bug: $1"
exit 123
fi
}
# issue 1440
gcc_version_ok() {
GCC_VERSION=`gcc -dumpversion`
local GCC_MAJOR local GCC_MINOR local GCC_PATCH local GCC_SPECIAL
semver_into $GCC_VERSION GCC_MAJOR GCC_MINOR GCC_PATCH GCC_SPECIAL
if [[ $GCC_MAJOR -lt 4
|| ( $GCC_MAJOR -eq 4 && $GCC_MINOR -lt 7 )
|| ( $GCC_MAJOR -eq 4 && $GCC_MINOR -eq 7 && $GCC_THIRD -lt 3 )
|| ( $GCC_MAJOR -eq 4 && $GCC_MINOR -eq 8 && $GCC_THIRD -eq 0 )
]] ; then
echo "gcc version required >= 4.7.3, != 4.8.0, >= 4.8.1, got $GCC_VERSION"
return 1
fi
return 0
}
clang_version_ok() {
CLANG_VERSION=`clang --version | head -n1`
CLANG_VERSION_RE='^[a-zA-Z0-9 ]* version (.*)$' # 3.3-5
if [[ $CLANG_VERSION =~ $CLANG_VERSION_RE ]] ; then
export "CLANG_VERSION=${BASH_REMATCH[1]}"
local CLANG_MAJOR local CLANG_MINOR local CLANG_PATCH local CLANG_SPECIAL
semver_into "$CLANG_VERSION" CLANG_MAJOR CLANG_MINOR CLANG_PATCH CLANG_SPECIAL
if [[ $CLANG_MAJOR -lt 3
|| ( $CLANG_MAJOR -eq 3 && $CLANG_MINOR -le 1 )
]] ; then
echo "clang version required >= 3.1, got $CLANG_VERSION"
return 1
fi
else
return 1
fi
return 0
}
set_cc() {
test_programs_installed clang clang++
if [[ $? -ne 0 ]] && clang_version_ok ; then
[ -z "$CC" ] && CC=clang
[ -z "$CXX" ] && CXX=clang++
return
fi
test_programs_installed gcc g++
if [[ $? -ne 0 ]] && gcc_version_ok ; then
[ -z "$CC" ] && CC=gcc
[ -z "$CXX" ] && CXX=g++
return
fi
$ECHO "error: high enough version of either (clang/clang++) or (gcc/g++) required!"
exit_script 10
}
set_make() {
MAKE='make'
}
check_git_branch() {
BRANCH=`git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,'`
if [ "$BRANCH" != "master" ] ; then
$ECHO "git branch is $BRANCH, not master"
exit_script 3
fi
}
check_installed_programs() {
ensure_program_installed chmod
ensure_program_installed uname
ensure_program_installed git
ensure_program_installed wget curl
ensure_program_installed clang gcc
ensure_program_installed clang++ g++ cl
ensure_program_installed make gmake
ensure_program_installed md5sum md5
ensure_program_installed cut
}
check_library_exists() {
GCC_TEST=factor-library-test.c
GCC_OUT=factor-library-test.out
$ECHO -n "Checking for library $1..."
$ECHO "int main(){return 0;}" > $GCC_TEST
$CC $GCC_TEST -o $GCC_OUT -l $1 2>&-
if [[ $? -ne 0 ]] ; then
$ECHO "not found."
$ECHO "***Factor will compile NO_UI=1"
NO_UI=1
else
$ECHO "found."
fi
$DELETE -f $GCC_TEST
check_ret $DELETE
$DELETE -f $GCC_OUT
check_ret $DELETE
}
check_X11_libraries() {
if [ -z "$NO_UI" ]; then
check_library_exists GL
check_library_exists X11
check_library_exists pango-1.0
fi
}
check_gtk_libraries() {
if [ -z "$NO_UI" ]; then
check_library_exists gobject-2.0
check_library_exists gtk-x11-2.0
check_library_exists gdk-x11-2.0
check_library_exists gdk_pixbuf-2.0
check_library_exists gtkglext-x11-1.0
check_library_exists atk-1.0
check_library_exists gio-2.0
check_library_exists gdkglext-x11-1.0
check_library_exists pango-1.0
fi
}
check_libraries() {
case $OS in
linux) check_X11_libraries
check_gtk_libraries;;
unix) check_gtk_libraries;;
esac
}
check_factor_exists() {
if [[ -d "factor" ]] ; then
$ECHO "A directory called 'factor' already exists."
$ECHO "Rename or delete it and try again."
exit_script 4
fi
}
find_os() {
if [[ -n $OS ]] ; then return; fi
$ECHO "Finding OS..."
uname_s=`uname -s`
check_ret uname
case $uname_s in
CYGWIN_NT-5.2-WOW64) OS=windows;;
*CYGWIN_NT*) OS=windows;;
*CYGWIN*) OS=windows;;
MINGW32*) OS=windows;;
*darwin*) OS=macosx;;
*Darwin*) OS=macosx;;
*linux*) OS=linux;;
*Linux*) OS=linux;;
esac
}
find_architecture() {
if [[ -n $ARCH ]] ; then return; fi
$ECHO "Finding ARCH..."
uname_m=`uname -m`
check_ret uname
case $uname_m in
i386) ARCH=x86;;
i686) ARCH=x86;;
i86pc) ARCH=x86;;
amd64) ARCH=x86;;
ppc64) ARCH=ppc;;
*86) ARCH=x86;;
*86_64) ARCH=x86;;
"Power Macintosh") ARCH=ppc;;
esac
}
write_test_program() {
#! Must be 'echo'
echo "#include <stdio.h>" > $C_WORD.c
echo "int main(){printf(\"%ld\", (long)(8*sizeof(void*))); return 0; }" >> $C_WORD.c
}
c_find_word_size() {
$ECHO "Finding WORD..."
C_WORD=factor-word-size
write_test_program
$CC -o $C_WORD $C_WORD.c
WORD=$(./$C_WORD)
check_ret $C_WORD
$DELETE -f $C_WORD*
}
intel_macosx_word_size() {
ensure_program_installed sysctl
$ECHO -n "Testing if your Intel Mac supports 64bit binaries..."
sysctl machdep.cpu.extfeatures | grep EM64T >/dev/null
if [[ $? -eq 0 ]] ; then
WORD=64
$ECHO "yes!"
else
WORD=32
$ECHO "no."
fi
}
find_word_size() {
if [[ -n $WORD ]] ; then return; fi
if [[ $OS == macosx && $ARCH == x86 ]] ; then
intel_macosx_word_size
else
c_find_word_size
fi
}
set_factor_binary() {
case $OS in
windows) FACTOR_BINARY=factor.com;;
*) FACTOR_BINARY=factor;;
esac
}
set_factor_library() {
case $OS in
windows) FACTOR_LIBRARY=factor.dll;;
macosx) FACTOR_LIBRARY=libfactor.dylib;;
*) FACTOR_LIBRARY=libfactor.a;;
esac
}
set_factor_image() {
FACTOR_IMAGE=factor.image
FACTOR_IMAGE_FRESH=factor.image.fresh
}
echo_build_info() {
$ECHO OS=$OS
$ECHO ARCH=$ARCH
$ECHO WORD=$WORD
$ECHO FACTOR_BINARY=$FACTOR_BINARY
$ECHO FACTOR_LIBRARY=$FACTOR_LIBRARY
$ECHO FACTOR_IMAGE=$FACTOR_IMAGE
$ECHO MAKE_TARGET=$MAKE_TARGET
$ECHO BOOT_IMAGE=$BOOT_IMAGE
$ECHO MAKE_IMAGE_TARGET=$MAKE_IMAGE_TARGET
$ECHO GIT_PROTOCOL=$GIT_PROTOCOL
$ECHO GIT_URL=$GIT_URL
$ECHO DOWNLOADER=$DOWNLOADER
$ECHO CC=$CC
$ECHO CXX=$CXX
$ECHO MAKE=$MAKE
$ECHO COPY=$COPY
$ECHO DELETE=$DELETE
}
check_os_arch_word() {
if ! [[ -n $OS && -n $ARCH && -n $WORD ]] ; then
$ECHO "OS: $OS"
$ECHO "ARCH: $ARCH"
$ECHO "WORD: $WORD"
$ECHO "OS, ARCH, or WORD is empty. Please report this."
$ECHO $MAKE_TARGET
exit_script 5
fi
}
set_build_info() {
check_os_arch_word
if [[ $OS == linux && $ARCH == ppc ]] ; then
MAKE_IMAGE_TARGET=linux-ppc.32
MAKE_TARGET=linux-ppc-32
elif [[ $OS == windows && $ARCH == x86 && $WORD == 64 ]] ; then
MAKE_IMAGE_TARGET=windows-x86.64
MAKE_TARGET=windows-x86-64
elif [[ $OS == windows && $ARCH == x86 && $WORD == 32 ]] ; then
MAKE_IMAGE_TARGET=windows-x86.32
MAKE_TARGET=windows-x86-32
elif [[ $ARCH == x86 && $WORD == 64 ]] ; then
MAKE_IMAGE_TARGET=unix-x86.64
MAKE_TARGET=$OS-x86-64
elif [[ $ARCH == x86 && $WORD == 32 ]] ; then
MAKE_IMAGE_TARGET=unix-x86.32
MAKE_TARGET=$OS-x86-32
else
MAKE_IMAGE_TARGET=$ARCH.$WORD
MAKE_TARGET=$OS-$ARCH-$WORD
fi
BOOT_IMAGE=boot.$MAKE_IMAGE_TARGET.image
}
parse_build_info() {
ensure_program_installed cut
$ECHO "Parsing make target from command line: $1"
OS=`echo $1 | cut -d '-' -f 1`
ARCH=`echo $1 | cut -d '-' -f 2`
WORD=`echo $1 | cut -d '-' -f 3`
if [[ $OS == linux && $ARCH == ppc ]] ; then WORD=32; fi
if [[ $OS == linux && $ARCH == arm ]] ; then WORD=32; fi
if [[ $OS == macosx && $ARCH == ppc ]] ; then WORD=32; fi
$ECHO "OS=$OS"
$ECHO "ARCH=$ARCH"
$ECHO "WORD=$WORD"
}
find_build_info() {
find_os
find_architecture
set_cc
find_word_size
set_factor_binary
set_factor_library
set_factor_image
set_build_info
set_downloader
set_make
echo_build_info
}
invoke_git() {
git $*
check_ret git
}
git_clone() {
$ECHO "Downloading the git repository from factorcode.org..."
invoke_git clone $GIT_URL
}
update_script_name() {
$ECHO `dirname $0`/_update.sh
}
update_script() {
update_script=`update_script_name`
bash_path=`which bash`
$ECHO "#!$bash_path" >"$update_script"
$ECHO "git pull \"$GIT_URL\" master" >>"$update_script"
$ECHO "if [[ \$? -eq 0 ]]; then exec \"$0\" $SCRIPT_ARGS; else echo \"git pull failed\"; exit 2; fi" \
>>"$update_script"
$ECHO "exit 0" >>"$update_script"
chmod 755 "$update_script"
exec "$update_script"
}
update_script_changed() {
invoke_git diff --stat `invoke_git merge-base HEAD FETCH_HEAD` FETCH_HEAD | grep 'build\.sh' >/dev/null
}
git_fetch_factorcode() {
$ECHO "Fetching the git repository from factorcode.org..."
rm -f `update_script_name`
invoke_git fetch "$GIT_URL" master
if update_script_changed; then
$ECHO "Updating and restarting the build.sh script..."
update_script
else
$ECHO "Updating the working tree..."
invoke_git pull "$GIT_URL" master
fi
}
cd_factor() {
cd factor
check_ret cd
}
set_copy() {
case $OS in
windows) COPY=cp;;
*) COPY=cp;;
esac
}
set_delete() {
case $OS in
windows) DELETE=rm;;
*) DELETE=rm;;
esac
}
backup_factor() {
$ECHO "Backing up factor..."
$COPY $FACTOR_BINARY $FACTOR_BINARY.bak
$COPY $FACTOR_LIBRARY $FACTOR_LIBRARY.bak
$COPY $BOOT_IMAGE $BOOT_IMAGE.bak
$COPY $FACTOR_IMAGE $FACTOR_IMAGE.bak
$ECHO "Done with backup."
}
check_makefile_exists() {
if [[ ! -e "GNUmakefile" ]] ; then
$ECHO ""
$ECHO "***GNUmakefile not found***"
$ECHO "You are likely in the wrong directory."
$ECHO "Run this script from your factor directory:"
$ECHO " ./build.sh"
exit_script 6
fi
}
invoke_make() {
check_makefile_exists
$MAKE $MAKE_OPTS $*
check_ret $MAKE
}
make_clean() {
invoke_make clean
}
make_factor() {
invoke_make CC=$CC CXX=$CXX NO_UI=$NO_UI $MAKE_TARGET -j5
}
make_clean_factor() {
make_clean
make_factor
}
update_boot_images() {
$ECHO "Deleting old images..."
$DELETE checksums.txt* > /dev/null 2>&1
# delete boot images with one or two characters after the dot
$DELETE $BOOT_IMAGE.{?,??} > /dev/null 2>&1
$DELETE temp/staging.*.image > /dev/null 2>&1
if [[ -f $BOOT_IMAGE ]] ; then
get_url http://downloads.factorcode.org/images/latest/checksums.txt
factorcode_md5=`cat checksums.txt|grep $BOOT_IMAGE|cut -f2 -d' '`
set_md5sum
disk_md5=`$MD5SUM $BOOT_IMAGE|cut -f1 -d' '`
$ECHO "Factorcode md5: $factorcode_md5";
$ECHO "Disk md5: $disk_md5";
if [[ "$factorcode_md5" == "$disk_md5" ]] ; then
$ECHO "Your disk boot image matches the one on factorcode.org."
else
$DELETE $BOOT_IMAGE > /dev/null 2>&1
get_boot_image;
fi
else
get_boot_image
fi
}
get_boot_image() {
$ECHO "Downloading boot image $BOOT_IMAGE."
get_url http://downloads.factorcode.org/images/latest/$BOOT_IMAGE
}
get_url() {
if [[ -z $DOWNLOADER ]] ; then
set_downloader;
fi
$ECHO $DOWNLOADER $1 ;
$DOWNLOADER $1
check_ret $DOWNLOADER
}
get_config_info() {
find_build_info
check_installed_programs
check_libraries
}
copy_fresh_image() {
$ECHO "Copying $FACTOR_IMAGE to $FACTOR_IMAGE_FRESH..."
$COPY $FACTOR_IMAGE $FACTOR_IMAGE_FRESH
}
bootstrap() {
./$FACTOR_BINARY -i=$BOOT_IMAGE
copy_fresh_image
}
install() {
check_factor_exists
get_config_info
git_clone
cd_factor
make_factor
get_boot_image
bootstrap
}
update() {
get_config_info
check_git_branch
git_fetch_factorcode
backup_factor
make_clean_factor
}
download_and_bootstrap() {
update_boot_images
bootstrap
}
net_bootstrap_no_pull() {
get_config_info
make_clean_factor
download_and_bootstrap
}
refresh_image() {
./$FACTOR_BINARY -script -e="USING: vocabs.loader vocabs.refresh system memory ; refresh-all save 0 exit"
check_ret factor
}
make_boot_image() {
./$FACTOR_BINARY -script -e="\"$MAKE_IMAGE_TARGET\" USING: system bootstrap.image memory ; make-image save 0 exit"
check_ret factor
}
install_deps_apt_get() {
sudo apt-get --yes install libc6-dev libpango1.0-dev libx11-dev xorg-dev libgtk2.0-dev gtk2-engines-pixbuf libgtkglext1-dev wget git git-doc rlwrap clang gcc make screen tmux libssl-dev g++
check_ret sudo
}
install_deps_pacman() {
sudo pacman --noconfirm -S gcc clang make rlwrap git wget pango glibc gtk2 gtk3 gtkglext gtk-engines gdk-pixbuf2 libx11 screen tmux
check_ret sudo
}
install_deps_dnf() {
sudo dnf --assumeyes install gcc gcc-c++ glibc-devel binutils libX11-devel pango-devel gtk3-devel gdk-pixbuf2-devel gtkglext-devel tmux rlwrap wget
check_ret sudo
}
install_deps_macosx() {
test_program_installed git
if [[ $? -ne 1 ]] ; then
ensure_program_installed yes
$ECHO "git not found."
$ECHO "This script requires either git-core or port."
$ECHO "If it fails, install git-core or port and try again."
ensure_program_installed port
$ECHO "Installing git-core with port...this will take awhile."
yes | sudo port install git-core
fi
}
usage() {
$ECHO "usage: $0 command [optional-target]"
$ECHO " install - git clone, compile, bootstrap"
$ECHO " deps-apt-get - install required packages for Factor on Linux using apt-get"
$ECHO " deps-pacman - install required packages for Factor on Linux using pacman"
$ECHO " deps-dnf - install required packages for Factor on Linux using dnf"
$ECHO " deps-macosx - install git on MacOSX using port"
$ECHO " self-update - git pull, recompile, make local boot image, bootstrap"
$ECHO " quick-update - git pull, refresh-all, save"
$ECHO " update|latest - git pull, recompile, download a boot image, bootstrap"
$ECHO " bootstrap - bootstrap with existing boot image"
$ECHO " net-bootstrap - recompile, download a boot image, bootstrap"
$ECHO " make-target - find and print the os-arch-cpu string"
$ECHO " report - print the build variables"
$ECHO ""
$ECHO "If you are behind a firewall, invoke as:"
$ECHO "env GIT_PROTOCOL=http $0 <command>"
$ECHO ""
$ECHO "Example for overriding the default target:"
$ECHO " $0 update macosx-x86-32"
}
MAKE_TARGET=unknown
# -n is nonzero length, -z is zero length
if [[ -n "$2" ]] ; then
parse_build_info $2
fi
set_copy
set_delete
case "$1" in
install) install ;;
deps-apt-get) install_deps_apt_get ;;
deps-pacman) install_deps_pacman ;;
deps-macosx) install_deps_macosx ;;
deps-dnf) install_deps_dnf ;;
self-update) update; make_boot_image; bootstrap;;
quick-update) update; refresh_image ;;
update) update; download_and_bootstrap ;;
latest) update; download_and_bootstrap ;;
bootstrap) get_config_info; bootstrap ;;
net-bootstrap) net_bootstrap_no_pull ;;
make-target) FIND_MAKE_TARGET=true; ECHO=false; find_build_info; exit_script ;;
report) find_build_info ;;
full-report) find_build_info; check_installed_programs; check_libraries ;;
*) usage ;;
esac
| {
"content_hash": "5bed874c8d02833c46b93435549f6dab",
"timestamp": "",
"source": "github",
"line_count": 720,
"max_line_length": 193,
"avg_line_length": 25.304166666666667,
"alnum_prop": 0.587408749108074,
"repo_name": "bjourne/factor",
"id": "3424ba1a79962a626c7c5f451472f0253f96908a",
"size": "18296",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "build.sh",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "1071"
},
{
"name": "Batchfile",
"bytes": "2739"
},
{
"name": "C",
"bytes": "24632"
},
{
"name": "C++",
"bytes": "451942"
},
{
"name": "CSS",
"bytes": "6136"
},
{
"name": "CoffeeScript",
"bytes": "14709"
},
{
"name": "Cuda",
"bytes": "4139"
},
{
"name": "Emacs Lisp",
"bytes": "190522"
},
{
"name": "Factor",
"bytes": "14503810"
},
{
"name": "GLSL",
"bytes": "8229"
},
{
"name": "Game Maker Language",
"bytes": "6477"
},
{
"name": "HTML",
"bytes": "63730"
},
{
"name": "JavaScript",
"bytes": "52579"
},
{
"name": "LLVM",
"bytes": "82"
},
{
"name": "Lua",
"bytes": "4020"
},
{
"name": "Makefile",
"bytes": "5753"
},
{
"name": "Objective-C++",
"bytes": "2749"
},
{
"name": "Ruby",
"bytes": "1203"
},
{
"name": "Rust",
"bytes": "38"
},
{
"name": "Shell",
"bytes": "18688"
},
{
"name": "Smalltalk",
"bytes": "2426"
},
{
"name": "VimL",
"bytes": "48824"
},
{
"name": "Visual Basic",
"bytes": "1389"
}
],
"symlink_target": ""
} |
SuperCamera = function (player, game) {
this.camera = game.camera;
this.player = player;
this.worldWidth = game.world.width;
this.camera.follow(this.player);
this.camera.deadzone = new Phaser.Rectangle(50, 0, game.width - 200, 0);
// if the player is on the left side...
this.isScrollingLeft = function () {
if (!this.camera.deadzone)
return false;
var threshold = this.camera.x + this.camera.deadzone.x;
if (this.player.isMovingHorz && this.camera.x > 0 && Math.floor(this.player.x) <= threshold)
return true;
return false;
}
// if the player is on the right side...
this.isScrollingRight = function () {
if (!this.camera.deadzone)
return false;
var threshold = this.camera.x + this.camera.deadzone.x + this.camera.deadzone.width;
if (this.player.isMovingHorz && (this.camera.x + this.camera.width) < this.worldWidth && this.player.x >= threshold)
return true;
return false;
}
} | {
"content_hash": "24d68881ff051664f4ec00eadfb13d17",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 118,
"avg_line_length": 28.060606060606062,
"alnum_prop": 0.6900647948164147,
"repo_name": "TransNeptunianStudios/VikingRobotRampage",
"id": "3414389ae8058152db320ececc245ffa8448f5cd",
"size": "926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SuperCamera.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1298"
},
{
"name": "JavaScript",
"bytes": "2773908"
}
],
"symlink_target": ""
} |
/**
* Contains logic for deleting and adding tags.
*
* For deleting tags it makes a request to the server to delete the tag.
* For adding tags it makes a request to the server to add the tag.
*
* @output wp-admin/js/tags.js
*/
/* global ajaxurl, wpAjax, tagsl10n, showNotice, validateForm */
jQuery(document).ready(function($) {
/**
* Adds an event handler to the delete term link on the term overview page.
*
* Cancels default event handling and event bubbling.
*
* @since 2.8.0
*
* @returns boolean Always returns false to cancel the default event handling.
*/
$( '#the-list' ).on( 'click', '.delete-tag', function() {
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
/**
* Makes a request to the server to delete the term that corresponds to the
* delete term button.
*
* @param {string} r The response from the server.
*
* @returns {void}
*/
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
/**
* Removes the term from the parent box and the tag cloud.
*
* `data.match(/tag_ID=(\d+)/)[1]` matches the term id from the data variable.
* This term id is then used to select the relevant HTML elements:
* The parent box and the tag cloud.
*/
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
/**
* Adds a deletion confirmation when removing a tag.
*
* @since 4.8.0
*
* @returns {void}
*/
$( '#edittag' ).on( 'click', '.delete', function( e ) {
if ( 'undefined' === typeof showNotice ) {
return true;
}
// Confirms the deletion, a negative response means the deletion must not be executed.
var response = showNotice.warn();
if ( ! response ) {
e.preventDefault();
}
});
/**
* Adds an event handler to the form submit on the term overview page.
*
* Cancels default event handling and event bubbling.
*
* @since 2.8.0
*
* @returns boolean Always returns false to cancel the default event handling.
*/
$('#submit').click(function(){
var form = $(this).parents('form');
if ( ! validateForm( form ) )
return false;
/**
* Does a request to the server to add a new term to the database
*
* @param {string} r The response from the server.
*
* @returns {void}
*/
$.post(ajaxurl, $('#addtag').serialize(), function(r){
var res, parent, term, indent, i;
$('#ajax-response').empty();
res = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( ! res || res.errors )
return;
parent = form.find( 'select#parent' ).val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$( '.tags #tag-' + parent ).after( res.responses[0].supplemental.noparents ); // As the parent exists, Insert the version with - - - prefixed
else
$( '.tags' ).prepend( res.responses[0].supplemental.parents ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
term = res.responses[1].supplemental;
// Create an indent for the Parent field
indent = '';
for ( i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find( 'select#parent option:selected' ).after( '<option value="' + term.term_id + '">' + indent + term.name + '</option>' );
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| {
"content_hash": "58a57f957959b2418cc05b8df844f546",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 149,
"avg_line_length": 29.564625850340136,
"alnum_prop": 0.5964104924068109,
"repo_name": "shampine/patrickshampine.com",
"id": "0f195c777e529acc742945571862803c88763c9c",
"size": "4346",
"binary": false,
"copies": "28",
"ref": "refs/heads/master",
"path": "public/wp-admin/js/tags.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2084264"
},
{
"name": "HTML",
"bytes": "6600"
},
{
"name": "JavaScript",
"bytes": "8066890"
},
{
"name": "PHP",
"bytes": "17749147"
},
{
"name": "Python",
"bytes": "3069"
},
{
"name": "Ruby",
"bytes": "823"
},
{
"name": "Shell",
"bytes": "4773"
},
{
"name": "XSLT",
"bytes": "4267"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81a.cpp
Label Definition File: CWE126_Buffer_Overread.stack.label.xml
Template File: sources-sink-81a.tmpl.cpp
*/
/*
* @description
* CWE: 126 Buffer Over-read
* BadSource: Set data pointer to a small buffer
* GoodSource: Set data pointer to a large buffer
* Sinks: memcpy
* BadSink : Copy data to string using memcpy
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include "CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81.h"
namespace CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t));
wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBadBuffer, L'A', 50-1); /* fill with 'A's */
dataBadBuffer[50-1] = L'\0'; /* null terminate */
wmemset(dataGoodBuffer, L'A', 100-1); /* fill with 'A's */
dataGoodBuffer[100-1] = L'\0'; /* null terminate */
/* FLAW: Set data pointer to a small buffer */
data = dataBadBuffer;
const CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81_base& baseObject = CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81_bad();
baseObject.action(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t));
wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBadBuffer, L'A', 50-1); /* fill with 'A's */
dataBadBuffer[50-1] = L'\0'; /* null terminate */
wmemset(dataGoodBuffer, L'A', 100-1); /* fill with 'A's */
dataGoodBuffer[100-1] = L'\0'; /* null terminate */
/* FIX: Set data pointer to a large buffer */
data = dataGoodBuffer;
const CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81_base& baseObject = CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81_goodG2B();
baseObject.action(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "c22dc0ccaf5cb74b3f2ce0ad21a8d6e8",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 137,
"avg_line_length": 31.90625,
"alnum_prop": 0.653934051583415,
"repo_name": "maurer/tiamat",
"id": "e396d05ba735a7129a375b080c1dc43be73215b9",
"size": "3063",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE126_Buffer_Overread/s03/CWE126_Buffer_Overread__wchar_t_alloca_memcpy_81a.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
QDialog(parent),
ui(new Ui::QRCodeDialog),
model(0),
address(addr)
{
ui->setupUi(this);
setWindowTitle(QString("%1").arg(address));
ui->chkReqPayment->setVisible(enableReq);
ui->lblAmount->setVisible(enableReq);
ui->lnReqAmount->setVisible(enableReq);
ui->lnLabel->setText(label);
ui->btnSaveAs->setEnabled(false);
genCode();
}
QRCodeDialog::~QRCodeDialog()
{
delete ui;
}
void QRCodeDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void QRCodeDialog::genCode()
{
QString uri = getURI();
if (uri != "")
{
ui->lblQRCode->setText("");
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->outUri->setPlainText(uri);
}
}
QString QRCodeDialog::getURI()
{
QString ret = QString("partycoin:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();
if (ui->chkReqPayment->isChecked())
{
if (ui->lnReqAmount->validate())
{
// even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21)
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value()));
paramCount++;
}
else
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("The entered amount is invalid, please check."));
return QString("");
}
}
if (!ui->lnLabel->text().isEmpty())
{
QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!ui->lnMessage->text().isEmpty())
{
QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
// limit URI length to prevent a DoS against the QR-Code dialog
if (ret.length() > MAX_URI_LENGTH)
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
return QString("");
}
ui->btnSaveAs->setEnabled(true);
return ret;
}
void QRCodeDialog::on_lnReqAmount_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnLabel_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnMessage_textChanged()
{
genCode();
}
void QRCodeDialog::on_btnSaveAs_clicked()
{
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)"));
if (!fn.isEmpty())
myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);
}
void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)
{
if (!fChecked)
// if chkReqPayment is not active, don't display lnReqAmount as invalid
ui->lnReqAmount->setValid(true);
genCode();
}
void QRCodeDialog::updateDisplayUnit()
{
if (model)
{
// Update lnReqAmount with the current unit
ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());
}
}
| {
"content_hash": "08c526742adc21074be97839d51a1123",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 127,
"avg_line_length": 25.930379746835442,
"alnum_prop": 0.5862826458384184,
"repo_name": "CCPorg/PARTY-PartyCoin-Ver-631-Original",
"id": "441d5e560ff49cae74ff6080296be1a5ab013bc9",
"size": "4312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/qrcodedialog.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "78622"
},
{
"name": "C++",
"bytes": "1377346"
},
{
"name": "IDL",
"bytes": "11106"
},
{
"name": "Objective-C",
"bytes": "2463"
},
{
"name": "Python",
"bytes": "18144"
},
{
"name": "Shell",
"bytes": "1144"
},
{
"name": "TypeScript",
"bytes": "3810608"
}
],
"symlink_target": ""
} |
u8R""__RAW_STRING__(
local U = require "togo.utility"
local M = U.module(...)
M.LogLevel = {
silent = 0,
error = 1,
info = 2,
debug = 3,
}
M.log_level = M.LogLevel.info
local BYTE_LF = string.byte('\n', 1)
local function boundary(text, s, e, byte)
local step = s > e and -1 or 1
for i = s, e, step do
if string.byte(text, i) ~= byte then
return i
end
end
return s
end
local function trim_text(text)
return string.sub(
text,
boundary(text, 1, #text, BYTE_LF),
boundary(text, #text, 1, BYTE_LF)
)
end
local function indent_text(text, level)
if level <= 0 then
return text
end
local indent = string.rep(" ", level)
text, _ = string.gsub(text, "\n", "\n" .. indent)
return indent .. text
end
function M.log_error(msg, ...)
U.type_assert(msg, "string")
if M.log_level >= M.LogLevel.error then
U.print("error: " .. msg, ...)
end
return false
end
function M.log(msg, ...)
U.type_assert(msg, "string")
if M.log_level >= M.LogLevel.info then
U.print(msg, ...)
end
end
function M.log_debug(msg, ...)
U.type_assert(msg, "string")
if M.log_level >= M.LogLevel.debug then
U.print(U.get_trace(1) .. ": debug: " .. msg, ...)
end
end
function M.error(msg, ...)
U.errorl(1, msg, ...)
end
U.class(M)
function M:__init(name, options, commands, help_text, func)
U.type_assert(name, "string")
U.type_assert(help_text, "string")
U.type_assert(options, "table")
U.type_assert(func, "function")
self.name = name
self.help_text = trim_text(help_text)
self.func = func
self.options = {}
self.commands = {}
self.default_data = {}
self.data = nil
self.auto_read_options = true
self:add_options(options)
self:add_commands(commands)
end
function M:add_options(options)
if U.is_type(options, M.Option) then
local option = options
for _, name in ipairs(option.names) do
U.assert(
self.options[name] == nil,
"tool %s: option must be unique: %s",
self.name, name
)
self.options[name] = option
end
table.insert(self.options, option)
else
U.type_assert(options, "table")
for _, option in pairs(options) do
self:add_options(option)
end
end
end
function M:add_commands(commands)
if U.is_type(commands, M) then
local command = commands
U.assert(command ~= self)
U.assert(
self.commands[command.name] == nil,
"tool %s: command must be unique: %s",
self.name, command.name
)
self.commands[command.name] = command
table.insert(self.commands, command)
else
U.type_assert(commands, "table")
for _, command in pairs(commands) do
self:add_commands(command)
end
end
end
function M:print_help(level)
level = U.type_assert(level, "number") or 0
print(indent_text(self.help_text, level))
for _, option in ipairs(self.options) do
print()
option:print_help(level + 1)
end
for _, command in ipairs(self.commands) do
print()
command:print_help(level + 1)
end
end
function M:read_options(options)
for _, option in ipairs(options) do
local tool_option = self.options[option.name]
if not tool_option then
return M.log_error("%s: option not recognized: %s", self.name, option.name)
end
if not tool_option:consume(self, option.name, option.value) then
return false
end
end
return true
end
function M:run(parent, options, params)
--[[U.print("[%s] %d options", self.name, #options)
for _, p in pairs(options) do
U.print(" %s = %s", p.name, p.value)
end
U.print("[%s] %d params", self.name, #params)
for _, p in pairs(params) do
U.print(" %s%s", p.name and (p.name .. " = ") or "", p.value)
end--]]
U.type_assert(self.default_data, "table")
U.assert(self.data == nil, "nested tool execution is unimplemented")
self.data = U.table_copy({}, self.default_data)
if self.auto_read_options then
if not self:read_options(options) then
self.data = nil
return false
end
end
local rv = self.func(self, parent, options, params)
self.data = nil
if rv == nil then
rv = true
end
return U.type_assert(rv, "boolean")
end
function M:run_command(parent_params)
local options = {}
local params = {}
if #parent_params == 0 then
return M.log_error("%s: expected command", self.name)
end
local name = parent_params[1].value
local i = 2
while i <= #parent_params do
local p = parent_params[i]
if not p.name then
break
end
table.insert(options, p)
i = i + 1
end
while i <= #parent_params do
table.insert(params, parent_params[i])
i = i + 1
end
local command = self.commands[name]
if not command then
return M.log_error("%s: command not recognized: %s", self.name, name)
end
return command:run(self, options, params)
end
M.Option = U.class(M.Option)
function M.Option:__init(names, types, help_text, func)
U.type_assert_any(names, {"string", "table"})
U.type_assert_any(table, {"string", "table"}, true)
U.type_assert(help_text, "string")
U.type_assert(func, "function")
self.names = U.is_type(names, "table") and names or {names}
if types then
self.types = U.is_type(types, "table") and types or {types}
else
self.types = nil
end
self.help_text = trim_text(help_text)
self.func = func
end
function M.Option:print_help(level)
level = U.type_assert(level, "number") or 0
print(indent_text(self.help_text, level))
end
function M.Option:consume(tool, name, value)
if self.types and not U.is_type_any(value, self.types) then
return M.log_error("%s: value type is invalid", name)
end
local rv = self.func(tool, value)
if rv == nil then
return true
end
return U.type_assert(rv, "boolean")
end
M.base_options = {
M.Option("--log", nil, [=[
--log=error | info | debug
set log level
default: info
]=],
function(_, value)
local given = value
if U.is_type(value, "string") then
value = M.LogLevel[value]
end
if U.is_type(value, "number") and value >= M.LogLevel.info and value <= M.LogLevel.debug then
M.log_level = value
return true
end
return M.log_error("--log is invalid: %s", tostring(given))
end),
}
M.help_command = M("help", {}, {}, [=[
help [(command_name | option_name) [...]]
prints help for commands and options
]=],
function(self, parent, options, params)
if #options == 0 and #params == 0 then
parent:print_help(-1)
return true
end
local hitlist = {}
function do_bucket(list)
for _, p in ipairs(list) do
local name, thing, kind
if p.name then
name = p.name
thing = parent.options[name]
kind = "option"
else
name = p.value
thing = parent.commands[name]
kind = "command"
end
if not thing then
M.log_error(
"%s %s: %s not recognized: %s",
parent.name, self.name,
kind, name
)
elseif not hitlist[thing] then
table.insert(hitlist, thing)
hitlist[thing] = true
end
end
end
do_bucket(options)
do_bucket(params)
for i, thing in ipairs(hitlist) do
thing:print_help(0)
if i < #hitlist then
print()
end
end
end)
M.help_command.auto_read_options = false
M.base_commands = {
M.help_command,
}
M.base_tool = M("main", M.base_options, M.base_commands, [=[
main [options] command [command_options] [command_params]
]=],
function(self, parent, options, params)
return self:run_command(params)
end)
function M.add_tools(tools)
M.base_tool:add_commands(tools)
end
local function concat_params(to, from)
for _, p in ipairs(from) do
table.insert(to, p)
end
end
local function nilify_params(params)
for _, p in ipairs(params) do
if p.name == "" then
p.name = nil
end
if p.value == "" then
p.value = nil
end
end
end
function M.run_tool(tool, args)
local _, opts, cmd_opts, cmd_params = U.parse_args(args)
local params = {}
opts.name = nil
cmd_opts.name = nil
if cmd_params.name ~= "" then
table.insert(params, {value = cmd_params.name})
end
cmd_params.name = nil
concat_params(params, cmd_opts)
concat_params(params, cmd_params)
nilify_params(opts)
nilify_params(params)
return tool:run(nil, opts, params)
end
function M.run_base(args)
return M.run(M.base_tool, args)
end
return M
)"__RAW_STRING__" | {
"content_hash": "c2f9d8486561173234df28ef796d38fb",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 94,
"avg_line_length": 21.237333333333332,
"alnum_prop": 0.6621044701155199,
"repo_name": "komiga/togo",
"id": "da5afb1d3d8d066d700afa5456eb85c9d519814d",
"size": "7964",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/core/src/togo/core/tool/Tool.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1171649"
},
{
"name": "GLSL",
"bytes": "1321"
},
{
"name": "Lua",
"bytes": "59517"
},
{
"name": "Makefile",
"bytes": "1648"
},
{
"name": "Python",
"bytes": "424"
},
{
"name": "Shell",
"bytes": "1025"
}
],
"symlink_target": ""
} |
//
// RKParamsAttachment.m
// RestKit
//
// Created by Blake Watters on 8/6/09.
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "RKParamsAttachment.h"
#import "RKLog.h"
#import "NSData+RKAdditions.h"
#import "FileMD5Hash.h"
#import "NSString+RKAdditions.h"
// Set Logging Component
#undef RKLogComponent
#define RKLogComponent lcl_cRestKitNetwork
/**
* The multi-part boundary. See RKParams.m
*/
extern NSString* const kRKStringBoundary;
@implementation RKParamsAttachment
@synthesize filePath = _filePath;
@synthesize fileName = _fileName;
@synthesize MIMEType = _MIMEType;
@synthesize name = _name;
@synthesize value = _value;
- (id)initWithName:(NSString *)name {
self = [self init];
if (self) {
self.name = name;
self.fileName = name;
}
return self;
}
- (id)initWithName:(NSString *)name value:(id<NSObject>)value {
if ((self = [self initWithName:name])) {
if ([value respondsToSelector:@selector(dataUsingEncoding:)]) {
_body = [[(NSString*)value dataUsingEncoding:NSUTF8StringEncoding] retain];
} else {
_body = [[[NSString stringWithFormat:@"%@", value] dataUsingEncoding:NSUTF8StringEncoding] retain];
}
_bodyStream = [[NSInputStream alloc] initWithData:_body];
_bodyLength = [_body length];
_value = [value retain];
}
return self;
}
- (id)initWithName:(NSString*)name data:(NSData*)data {
self = [self initWithName:name];
if (self) {
_body = [data retain];
_bodyStream = [[NSInputStream alloc] initWithData:data];
_bodyLength = [data length];
}
return self;
}
- (id)initWithName:(NSString*)name file:(NSString*)filePath {
self = [self initWithName:name];
if (self) {
NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:filePath], @"Expected file to exist at path: %@", filePath);
_filePath = [filePath retain];
_fileName = [[filePath lastPathComponent] retain];
NSString *MIMEType = [filePath MIMETypeForPathExtension];
if (! MIMEType) MIMEType = @"application/octet-stream";
_MIMEType = [MIMEType retain];
_bodyStream = [[NSInputStream alloc] initWithFileAtPath:filePath];
NSError* error;
NSDictionary* attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
if (attributes) {
_bodyLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue];
}
else {
RKLogError(@"Encountered an error while determining file size: %@", error);
}
}
return self;
}
- (void)dealloc {
[_value release];
[_name release];
[_body release];
[_filePath release];
[_fileName release];
[_MIMEType release];
[_MIMEHeader release];
_MIMEHeader = nil;
[_bodyStream close];
[_bodyStream release];
_bodyStream = nil;
[super dealloc];
}
- (NSString*)MIMEBoundary {
return kRKStringBoundary;
}
#pragma mark NSStream methods
- (void)open {
// Generate the MIME header for this part
if (self.fileName && self.MIMEType) {
// Typical for file attachments
_MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; "
@"filename=\"%@\"\r\nContent-Type: %@\r\n\r\n",
[self MIMEBoundary], self.name, self.fileName, self.MIMEType] dataUsingEncoding:NSUTF8StringEncoding] retain];
} else if (self.MIMEType) {
// Typical for data values
_MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n"
@"Content-Type: %@\r\n\r\n",
[self MIMEBoundary], self.name, self.MIMEType] dataUsingEncoding:NSUTF8StringEncoding] retain];
} else {
// Typical for raw values
_MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n",
[self MIMEBoundary], self.name]
dataUsingEncoding:NSUTF8StringEncoding] retain];
}
// Calculate lengths
_MIMEHeaderLength = [_MIMEHeader length];
_length = _MIMEHeaderLength + _bodyLength + 2; // \r\n is the + 2
// Open the stream
[_bodyStream open];
}
- (NSUInteger)length {
return _length;
}
- (NSUInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength {
NSUInteger sent = 0, read;
// We are done with the read
if (_delivered >= _length) {
return 0;
}
// First we send back the MIME headers
if (_delivered < _MIMEHeaderLength && sent < maxLength) {
NSUInteger headerBytesRemaining, bytesRemainingInBuffer;
headerBytesRemaining = _MIMEHeaderLength - _delivered;
bytesRemainingInBuffer = maxLength;
// Send the entire header if there is room
read = (headerBytesRemaining < bytesRemainingInBuffer) ? headerBytesRemaining : bytesRemainingInBuffer;
[_MIMEHeader getBytes:buffer range:NSMakeRange(_delivered, read)];
sent += read;
_delivered += sent;
}
// Read the attachment body out of our underlying stream
while (_delivered >= _MIMEHeaderLength && _delivered < (_length - 2) && sent < maxLength) {
if ((read = [_bodyStream read:(buffer + sent) maxLength:(maxLength - sent)]) == 0) {
break;
}
sent += read;
_delivered += read;
}
// Append the \r\n
if (_delivered >= (_length - 2) && sent < maxLength) {
if (_delivered == (_length - 2)) {
*(buffer + sent) = '\r';
sent ++;
_delivered ++;
}
*(buffer + sent) = '\n';
sent ++;
_delivered ++;
}
return sent;
}
- (NSString *)MD5 {
if (_body) {
return [_body MD5];
} else if (_filePath) {
CFStringRef fileAttachmentMD5 = FileMD5HashCreateWithPath((CFStringRef)_filePath,
FileHashDefaultChunkSizeForReadingData);
return [(NSString *)fileAttachmentMD5 autorelease];
} else {
RKLogWarning(@"Failed to generate MD5 for attachment: unknown data type.");
return nil;
}
}
@end
| {
"content_hash": "4f92a7f14f86e2a45a7893cd35d2b84c",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 135,
"avg_line_length": 31.36036036036036,
"alnum_prop": 0.6093076702097099,
"repo_name": "bendyworks/TravisCI.app",
"id": "e62413f623756d9baa2373d44f976b40f45f9537",
"size": "6962",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Pods/RestKit/Code/Network/RKParamsAttachment.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "139810"
},
{
"name": "C++",
"bytes": "16086"
},
{
"name": "CoffeeScript",
"bytes": "10036"
},
{
"name": "JavaScript",
"bytes": "28531"
},
{
"name": "Objective-C",
"bytes": "1450544"
},
{
"name": "Ruby",
"bytes": "9415"
},
{
"name": "Shell",
"bytes": "3454"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_63b.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-63b.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sinks: w32_execvp
* BadSink : execute command with wexecvp
* Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#include <process.h>
#define EXECVP _wexecvp
#ifndef OMITBAD
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_63b_badSink(wchar_t * * dataPtr)
{
wchar_t * data = *dataPtr;
{
wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* wexecvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_63b_goodG2BSink(wchar_t * * dataPtr)
{
wchar_t * data = *dataPtr;
{
wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* wexecvp - searches for the location of the command among
* the directories specified by the PATH environment variable */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECVP(COMMAND_INT, args);
}
}
#endif /* OMITGOOD */
| {
"content_hash": "ef8991c7bb39a5875a0af4e697a21863",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 108,
"avg_line_length": 30.42222222222222,
"alnum_prop": 0.6869978086194303,
"repo_name": "maurer/tiamat",
"id": "176a536199e164c56b050252d00ada4c954349ab",
"size": "2738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE78_OS_Command_Injection/s08/CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_63b.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>founify: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.0 / founify - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
founify
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-25 03:20:09 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-25 03:20:09 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.13.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.13.1 Official release 4.13.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/founify"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/FOUnify"]
depends: [
"camlp5"
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: First-order Unification"
"keyword: Robinson"
"category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms"
"category: Miscellaneous/Extracted Programs/Type checking unification and normalization"
]
authors: [
"Jocelyne Rouyer"
]
bug-reports: "https://github.com/coq-contribs/founify/issues"
dev-repo: "git+https://github.com/coq-contribs/founify.git"
synopsis: "Correctness and extraction of the unification algorithm"
description: """
A notion of terms based on symbols without fixed arities is defined
and an extended unification problem is proved solvable on these terms.
An algorithm, close from Robinson algorithm, can be extracted from the
proof."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/founify/archive/v8.10.0.tar.gz"
checksum: "md5=2f68b8dc8c863e75077d1667a36cf10f"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-founify.8.10.0 coq.8.13.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0).
The following dependencies couldn't be met:
- coq-founify -> coq < 8.11~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-founify.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "6ab5044fc1b3a92772721c4ab112c827",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 159,
"avg_line_length": 41.794285714285714,
"alnum_prop": 0.5542794640415641,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e63dc9202c1f37152cf26e8bf2aab1747ae4ad35",
"size": "7339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.13.1-2.0.10/released/8.13.0/founify/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
/** Zend_Controller_Router_Abstract */
require_once 'Zend/Controller/Router/Abstract.php';
/** Zend_Controller_Router_Route */
require_once 'Zend/Controller/Router/Route.php';
/**
* Ruby routing based Router.
*
* @package Zend_Controller
* @subpackage Router
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @see http://manuals.rubyonrails.com/read/chapter/65
*/
class Zend_Controller_Router_Rewrite extends Zend_Controller_Router_Abstract
{
/**
* Whether or not to use default routes
*
* @var boolean
*/
protected $_useDefaultRoutes = true;
/**
* Array of routes to match against
*
* @var array
*/
protected $_routes = array();
/**
* Currently matched route
*
* @var Zend_Controller_Router_Route_Interface
*/
protected $_currentRoute = null;
/**
* Global parameters given to all routes
*
* @var array
*/
protected $_globalParams = array();
/**
* Separator to use with chain names
*
* @var string
*/
protected $_chainNameSeparator = '-';
/**
* Determines if request parameters should be used as global parameters
* inside this router.
*
* @var boolean
*/
protected $_useCurrentParamsAsGlobal = false;
/**
* Add default routes which are used to mimic basic router behaviour
*
* @return Zend_Controller_Router_Rewrite
*/
public function addDefaultRoutes()
{
if (!$this->hasRoute('default')) {
$dispatcher = $this->getFrontController()->getDispatcher();
$request = $this->getFrontController()->getRequest();
require_once 'Zend/Controller/Router/Route/Module.php';
$compat = new Zend_Controller_Router_Route_Module(array(), $dispatcher, $request);
$this->_routes = array('default' => $compat) + $this->_routes;
}
return $this;
}
/**
* Add route to the route chain
*
* If route contains method setRequest(), it is initialized with a request object
*
* @param string $name Name of the route
* @param Zend_Controller_Router_Route_Interface $route Instance of the route
* @return Zend_Controller_Router_Rewrite
*/
public function addRoute($name, Zend_Controller_Router_Route_Interface $route)
{
if (method_exists($route, 'setRequest')) {
$route->setRequest($this->getFrontController()->getRequest());
}
$this->_routes[$name] = $route;
return $this;
}
/**
* Add routes to the route chain
*
* @param array $routes Array of routes with names as keys and routes as values
* @return Zend_Controller_Router_Rewrite
*/
public function addRoutes($routes) {
foreach ($routes as $name => $route) {
$this->addRoute($name, $route);
}
return $this;
}
/**
* Create routes out of Zend_Config configuration
*
* Example INI:
* routes.archive.route = "archive/:year/*"
* routes.archive.defaults.controller = archive
* routes.archive.defaults.action = show
* routes.archive.defaults.year = 2000
* routes.archive.reqs.year = "\d+"
*
* routes.news.type = "Zend_Controller_Router_Route_Static"
* routes.news.route = "news"
* routes.news.defaults.controller = "news"
* routes.news.defaults.action = "list"
*
* And finally after you have created a Zend_Config with above ini:
* $router = new Zend_Controller_Router_Rewrite();
* $router->addConfig($config, 'routes');
*
* @param Zend_Config $config Configuration object
* @param string $section Name of the config section containing route's definitions
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Rewrite
*/
public function addConfig(Zend_Config $config, $section = null)
{
if ($section !== null) {
if ($config->{$section} === null) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("No route configuration in section '{$section}'");
}
$config = $config->{$section};
}
foreach ($config as $name => $info) {
$route = $this->_getRouteFromConfig($info);
if ($route instanceof Zend_Controller_Router_Route_Chain) {
if (!isset($info->chain)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("No chain defined");
}
if ($info->chain instanceof Zend_Config) {
$childRouteNames = $info->chain;
} else {
$childRouteNames = explode(',', $info->chain);
}
foreach ($childRouteNames as $childRouteName) {
$childRoute = $this->getRoute(trim($childRouteName));
$route->chain($childRoute);
}
$this->addRoute($name, $route);
} elseif (isset($info->chains) && $info->chains instanceof Zend_Config) {
$this->_addChainRoutesFromConfig($name, $route, $info->chains);
} else {
$this->addRoute($name, $route);
}
}
return $this;
}
/**
* Get a route frm a config instance
*
* @param Zend_Config $info
* @return Zend_Controller_Router_Route_Interface
*/
protected function _getRouteFromConfig(Zend_Config $info)
{
$class = (isset($info->type)) ? $info->type : 'Zend_Controller_Router_Route';
if (!class_exists($class)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($class);
}
$route = call_user_func(array($class, 'getInstance'), $info);
if (isset($info->abstract) && $info->abstract && method_exists($route, 'isAbstract')) {
$route->isAbstract(true);
}
return $route;
}
/**
* Add chain routes from a config route
*
* @param string $name
* @param Zend_Controller_Router_Route_Interface $route
* @param Zend_Config $childRoutesInfo
* @return void
*/
protected function _addChainRoutesFromConfig($name,
Zend_Controller_Router_Route_Interface $route,
Zend_Config $childRoutesInfo)
{
foreach ($childRoutesInfo as $childRouteName => $childRouteInfo) {
if (is_string($childRouteInfo)) {
$childRouteName = $childRouteInfo;
$childRoute = $this->getRoute($childRouteName);
} else {
$childRoute = $this->_getRouteFromConfig($childRouteInfo);
}
if ($route instanceof Zend_Controller_Router_Route_Chain) {
$chainRoute = clone $route;
$chainRoute->chain($childRoute);
} else {
$chainRoute = $route->chain($childRoute);
}
$chainName = $name . $this->_chainNameSeparator . $childRouteName;
if (isset($childRouteInfo->chains)) {
$this->_addChainRoutesFromConfig($chainName, $chainRoute, $childRouteInfo->chains);
} else {
$this->addRoute($chainName, $chainRoute);
}
}
}
/**
* Remove a route from the route chain
*
* @param string $name Name of the route
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Rewrite
*/
public function removeRoute($name)
{
if (!isset($this->_routes[$name])) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Route $name is not defined");
}
unset($this->_routes[$name]);
return $this;
}
/**
* Remove all standard default routes
*
* @param Zend_Controller_Router_Route_Interface Route
* @return Zend_Controller_Router_Rewrite
*/
public function removeDefaultRoutes()
{
$this->_useDefaultRoutes = false;
return $this;
}
/**
* Check if named route exists
*
* @param string $name Name of the route
* @return boolean
*/
public function hasRoute($name)
{
return isset($this->_routes[$name]);
}
/**
* Retrieve a named route
*
* @param string $name Name of the route
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Route_Interface Route object
*/
public function getRoute($name)
{
if (!isset($this->_routes[$name])) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Route $name is not defined");
}
return $this->_routes[$name];
}
/**
* Retrieve a currently matched route
*
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Route_Interface Route object
*/
public function getCurrentRoute()
{
if (!isset($this->_currentRoute)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Current route is not defined");
}
return $this->getRoute($this->_currentRoute);
}
/**
* Retrieve a name of currently matched route
*
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Router_Route_Interface Route object
*/
public function getCurrentRouteName()
{
if (!isset($this->_currentRoute)) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception("Current route is not defined");
}
return $this->_currentRoute;
}
/**
* Retrieve an array of routes added to the route chain
*
* @return array All of the defined routes
*/
public function getRoutes()
{
return $this->_routes;
}
/**
* Find a matching route to the current PATH_INFO and inject
* returning values to the Request object.
*
* @throws Zend_Controller_Router_Exception
* @return Zend_Controller_Request_Abstract Request object
*/
public function route(Zend_Controller_Request_Abstract $request)
{
if (!$request instanceof Zend_Controller_Request_Http) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Zend_Controller_Router_Rewrite requires a Zend_Controller_Request_Http-based request object');
}
if ($this->_useDefaultRoutes) {
$this->addDefaultRoutes();
}
// Find the matching route
$routeMatched = false;
foreach (array_reverse($this->_routes, true) as $name => $route) {
// TODO: Should be an interface method. Hack for 1.0 BC
if (method_exists($route, 'isAbstract') && $route->isAbstract()) {
continue;
}
// TODO: Should be an interface method. Hack for 1.0 BC
if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) {
$match = $request->getPathInfo();
} else {
$match = $request;
}
if ($params = $route->match($match)) {
$this->_setRequestParams($request, $params);
$this->_currentRoute = $name;
$routeMatched = true;
break;
}
}
if (!$routeMatched) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('No route matched the request', 404);
}
if($this->_useCurrentParamsAsGlobal) {
$params = $request->getParams();
foreach($params as $param => $value) {
$this->setGlobalParam($param, $value);
}
}
return $request;
}
protected function _setRequestParams($request, $params)
{
foreach ($params as $param => $value) {
$request->setParam($param, $value);
if ($param === $request->getModuleKey()) {
$request->setModuleName($value);
}
if ($param === $request->getControllerKey()) {
$request->setControllerName($value);
}
if ($param === $request->getActionKey()) {
$request->setActionName($value);
}
}
}
/**
* Generates a URL path that can be used in URL creation, redirection, etc.
*
* @param array $userParams Options passed by a user used to override parameters
* @param mixed $name The name of a Route to use
* @param bool $reset Whether to reset to the route defaults ignoring URL params
* @param bool $encode Tells to encode URL parts on output
* @throws Zend_Controller_Router_Exception
* @return string Resulting absolute URL path
*/
public function assemble($userParams, $name = null, $reset = false, $encode = true)
{
if ($name == null) {
try {
$name = $this->getCurrentRouteName();
} catch (Zend_Controller_Router_Exception $e) {
$name = 'default';
}
}
// Use UNION (+) in order to preserve numeric keys
$params = $userParams + $this->_globalParams;
$route = $this->getRoute($name);
$url = $route->assemble($params, $reset, $encode);
if (!preg_match('|^[a-z]+://|', $url)) {
$url = rtrim($this->getFrontController()->getBaseUrl(), '/') . '/' . $url;
}
return $url;
}
/**
* Set a global parameter
*
* @param string $name
* @param mixed $value
* @return Zend_Controller_Router_Rewrite
*/
public function setGlobalParam($name, $value)
{
$this->_globalParams[$name] = $value;
return $this;
}
/**
* Set the separator to use with chain names
*
* @param string $separator The separator to use
* @return Zend_Controller_Router_Rewrite
*/
public function setChainNameSeparator($separator) {
$this->_chainNameSeparator = $separator;
return $this;
}
/**
* Get the separator to use for chain names
*
* @return string
*/
public function getChainNameSeparator() {
return $this->_chainNameSeparator;
}
/**
* Determines/returns whether to use the request parameters as global parameters.
*
* @param boolean|null $use
* Null/unset when you want to retrieve the current state.
* True when request parameters should be global, false otherwise
* @return boolean|Zend_Controller_Router_Rewrite
* Returns a boolean if first param isn't set, returns an
* instance of Zend_Controller_Router_Rewrite otherwise.
*
*/
public function useRequestParametersAsGlobal($use = null) {
if($use === null) {
return $this->_useCurrentParamsAsGlobal;
}
$this->_useCurrentParamsAsGlobal = (bool) $use;
return $this;
}
}
| {
"content_hash": "2c12d829578296ee655bcb33538a8e68",
"timestamp": "",
"source": "github",
"line_count": 510,
"max_line_length": 150,
"avg_line_length": 30.978431372549018,
"alnum_prop": 0.5623140705107919,
"repo_name": "esteit/ZendFramework-1.11.1-minimal",
"id": "4687ff370fcfb9d09c7600f5ef59b179ce72ff63",
"size": "16568",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "library/Zend/Controller/Router/Rewrite.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "14960330"
},
{
"name": "Shell",
"bytes": "2667"
}
],
"symlink_target": ""
} |
import React, {PropTypes} from 'react';
const CallRep = (props) => {
const styles = require('./CallRep.scss');
const largeClass = props.large ? 'btn-lg' : '';
return (
<div>
{props.phones && props.phones[0] &&
<button className={styles.btn + ' ' + largeClass + ' btn btn-primary'}>Call {props.name} at {props.phones[0]}</button>
}
</div>
);
};
CallRep.propTypes = {
name: PropTypes.string,
phones: PropTypes.array,
large: PropTypes.bool,
};
export default CallRep;
| {
"content_hash": "86fb57554422086851ca7dd599c0310c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 124,
"avg_line_length": 24.19047619047619,
"alnum_prop": 0.6161417322834646,
"repo_name": "NetEffective/net-effective",
"id": "c4837a625cefbae1a146600275ca2f5ad495e34b",
"size": "508",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/Rep/CallRep.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3003"
},
{
"name": "JavaScript",
"bytes": "90339"
},
{
"name": "Shell",
"bytes": "637"
}
],
"symlink_target": ""
} |
package com.feilong.manager;
public interface MemberManager{
}
| {
"content_hash": "2b9a551fa05caf0695b755909b6d483d",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 31,
"avg_line_length": 11,
"alnum_prop": 0.7878787878787878,
"repo_name": "venusdrogon/feilong-spring",
"id": "84fb0c3055068c3a09a3e441fc07be67d35721bd",
"size": "664",
"binary": false,
"copies": "1",
"ref": "refs/heads/spring4",
"path": "feilong-spring-core/src/test/java/com/feilong/manager/MemberManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "808421"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/SimpleAudio.iml" filepath="$PROJECT_DIR$/SimpleAudio.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/library/library.iml" filepath="$PROJECT_DIR$/library/library.iml" />
</modules>
</component>
</project> | {
"content_hash": "4426903cfc1f576567873ba44f9f9573",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 112,
"avg_line_length": 47.2,
"alnum_prop": 0.6716101694915254,
"repo_name": "lrannn/SimpleRecorder",
"id": "aa22dd8ba75f3fe44b682a8ee1a6b9f6d6c30a68",
"size": "472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "11564"
}
],
"symlink_target": ""
} |
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32L0xx_HAL_FIREWALL_H
#define __STM32L0xx_HAL_FIREWALL_H
#ifdef __cplusplus
extern "C" {
#endif
#if !defined (STM32L011xx) && !defined (STM32L021xx) && !defined (STM32L031xx) && !defined (STM32L041xx)
/* Includes ------------------------------------------------------------------*/
#include "stm32l0xx_hal_def.h"
/** @addtogroup STM32L0xx_HAL_Driver
* @{
*/
/** @defgroup FIREWALL FIREWALL
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup FIREWALL_Exported_Types FIREWALL Exported Types
* @{
*/
/**
* @brief FIREWALL Initialization Structure definition
*/
typedef struct
{
uint32_t CodeSegmentStartAddress; /*!< Protected code segment start address. This value is 24-bit long, the 8 LSB bits are
reserved and forced to 0 in order to allow a 256-byte granularity. */
uint32_t CodeSegmentLength; /*!< Protected code segment length in bytes. This value is 22-bit long, the 8 LSB bits are
reserved and forced to 0 for the length to be a multiple of 256 bytes. */
uint32_t NonVDataSegmentStartAddress; /*!< Protected non-volatile data segment start address. This value is 24-bit long, the 8 LSB
bits are reserved and forced to 0 in order to allow a 256-byte granularity. */
uint32_t NonVDataSegmentLength; /*!< Protected non-volatile data segment length in bytes. This value is 22-bit long, the 8 LSB
bits are reserved and forced to 0 for the length to be a multiple of 256 bytes. */
uint32_t VDataSegmentStartAddress; /*!< Protected volatile data segment start address. This value is 17-bit long, the 6 LSB bits
are reserved and forced to 0 in order to allow a 64-byte granularity. */
uint32_t VDataSegmentLength; /*!< Protected volatile data segment length in bytes. This value is 17-bit long, the 6 LSB
bits are reserved and forced to 0 for the length to be a multiple of 64 bytes. */
uint32_t VolatileDataExecution; /*!< Set VDE bit specifying whether or not the volatile data segment can be executed.
When VDS = 1 (set by parameter VolatileDataShared), VDE bit has no meaning.
This parameter can be a value of @ref FIREWALL_VolatileData_Executable */
uint32_t VolatileDataShared; /*!< Set VDS bit in specifying whether or not the volatile data segment can be shared with a
non-protected application code.
This parameter can be a value of @ref FIREWALL_VolatileData_Shared */
}FIREWALL_InitTypeDef;
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup FIREWALL_Exported_Constants FIREWALL Exported Constants
* @{
*/
/** @defgroup FIREWALL_VolatileData_Executable FIREWALL volatile data segment execution status
* @{
*/
#define FIREWALL_VOLATILEDATA_NOT_EXECUTABLE ((uint32_t)0x0000U)
#define FIREWALL_VOLATILEDATA_EXECUTABLE ((uint32_t)FW_CR_VDE)
/**
* @}
*/
/** @defgroup FIREWALL_VolatileData_Shared FIREWALL volatile data segment share status
* @{
*/
#define FIREWALL_VOLATILEDATA_NOT_SHARED ((uint32_t)0x0000U)
#define FIREWALL_VOLATILEDATA_SHARED ((uint32_t)FW_CR_VDS)
/**
* @}
*/
/** @defgroup FIREWALL_Pre_Arm FIREWALL pre arm status
* @{
*/
#define FIREWALL_PRE_ARM_RESET ((uint32_t)0x0000U)
#define FIREWALL_PRE_ARM_SET ((uint32_t)FW_CR_FPA)
/**
* @}
*/
/**
* @}
*/
/* Private macros --------------------------------------------------------*/
/** @addtogroup FIREWALL_Private
* @{
*/
#define IS_FIREWALL_CODE_SEGMENT_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && ((ADDRESS) < (FLASH_BASE + FLASH_SIZE)))
#define IS_FIREWALL_CODE_SEGMENT_LENGTH(ADDRESS, LENGTH) (((ADDRESS) + (LENGTH)) <= (FLASH_BASE + FLASH_SIZE))
#define IS_FIREWALL_NONVOLATILEDATA_SEGMENT_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && ((ADDRESS) < (FLASH_BASE + FLASH_SIZE)))
#define IS_FIREWALL_NONVOLATILEDATA_SEGMENT_LENGTH(ADDRESS, LENGTH) (((ADDRESS) + (LENGTH)) <= (FLASH_BASE + FLASH_SIZE))
#define IS_FIREWALL_VOLATILEDATA_SEGMENT_ADDRESS(ADDRESS) (((ADDRESS) >= SRAM_BASE) && ((ADDRESS) < (SRAM_BASE + SRAM_SIZE_MAX)))
#define IS_FIREWALL_VOLATILEDATA_SEGMENT_LENGTH(ADDRESS, LENGTH) (((ADDRESS) + (LENGTH)) <= (SRAM_BASE + SRAM_SIZE_MAX))
#define IS_FIREWALL_VOLATILEDATA_SHARE(SHARE) (((SHARE) == FIREWALL_VOLATILEDATA_NOT_SHARED) || \
((SHARE) == FIREWALL_VOLATILEDATA_SHARED))
#define IS_FIREWALL_VOLATILEDATA_EXECUTE(EXECUTE) (((EXECUTE) == FIREWALL_VOLATILEDATA_NOT_EXECUTABLE) || \
((EXECUTE) == FIREWALL_VOLATILEDATA_EXECUTABLE))
/**
* @}
*/
/* Exported macros -----------------------------------------------------------*/
/** @defgroup FIREWALL_Exported_Macros FIREWALL Exported Macros
* @{
*/
/** @brief Check whether the FIREWALL is enabled or not.
* @retval FIREWALL enabling status (TRUE or FALSE).
*/
#define __HAL_FIREWALL_IS_ENABLED() HAL_IS_BIT_CLR(SYSCFG->CFGR2, SYSCFG_CFGR2_FWDISEN)
/** @brief Enable FIREWALL pre arm.
* @note When FPA bit is set, any code executed outside the protected segment
* closes the Firewall, otherwise it generates a system reset.
* @note This macro provides the same service as HAL_FIREWALL_EnablePreArmFlag() API
* but can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
*/
#define __HAL_FIREWALL_PREARM_ENABLE() \
do { \
__IO uint32_t tmpreg; \
SET_BIT(FIREWALL->CR, FW_CR_FPA) ; \
/* Read bit back to ensure it is taken into account by IP */ \
/* (introduce proper delay inside macro execution) */ \
tmpreg = READ_BIT(FIREWALL->CR, FW_CR_FPA) ; \
UNUSED(tmpreg); \
} while(0)
/** @brief Disable FIREWALL pre arm.
* @note When FPA bit is set, any code executed outside the protected segment
* closes the Firewall, otherwise, it generates a system reset.
* @note This macro provides the same service as HAL_FIREWALL_DisablePreArmFlag() API
* but can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
*/
#define __HAL_FIREWALL_PREARM_DISABLE() \
do { \
__IO uint32_t tmpreg; \
CLEAR_BIT(FIREWALL->CR, FW_CR_FPA) ; \
/* Read bit back to ensure it is taken into account by IP */ \
/* (introduce proper delay inside macro execution) */ \
tmpreg = READ_BIT(FIREWALL->CR, FW_CR_FPA) ; \
UNUSED(tmpreg); \
} while(0)
/** @brief Enable volatile data sharing in setting VDS bit.
* @note When VDS bit is set, the volatile data segment is shared with non-protected
* application code. It can be accessed whatever the Firewall state (opened or closed).
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
*/
#define __HAL_FIREWALL_VOLATILEDATA_SHARED_ENABLE() \
do { \
__IO uint32_t tmpreg; \
SET_BIT(FIREWALL->CR, FW_CR_VDS) ; \
/* Read bit back to ensure it is taken into account by IP */ \
/* (introduce proper delay inside macro execution) */ \
tmpreg = READ_BIT(FIREWALL->CR, FW_CR_VDS) ; \
UNUSED(tmpreg); \
} while(0)
/** @brief Disable volatile data sharing in resetting VDS bit.
* @note When VDS bit is reset, the volatile data segment is not shared and cannot be
* hit by a non protected executable code when the Firewall is closed. If it is
* accessed in such a condition, a system reset is generated by the Firewall.
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
*/
#define __HAL_FIREWALL_VOLATILEDATA_SHARED_DISABLE() \
do { \
__IO uint32_t tmpreg; \
CLEAR_BIT(FIREWALL->CR, FW_CR_VDS) ; \
/* Read bit back to ensure it is taken into account by IP */ \
/* (introduce proper delay inside macro execution) */ \
tmpreg = READ_BIT(FIREWALL->CR, FW_CR_VDS) ; \
UNUSED(tmpreg); \
} while(0)
/** @brief Enable volatile data execution in setting VDE bit.
* @note VDE bit is ignored when VDS is set. IF VDS = 1, the Volatile data segment can be
* executed whatever the VDE bit value.
* @note When VDE bit is set (with VDS = 0), the volatile data segment is executable. When
* the Firewall call is closed, a "call gate" entry procedure is required to open
* first the Firewall.
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
*/
#define __HAL_FIREWALL_VOLATILEDATA_EXECUTION_ENABLE() \
do { \
__IO uint32_t tmpreg; \
SET_BIT(FIREWALL->CR, FW_CR_VDE) ; \
/* Read bit back to ensure it is taken into account by IP */ \
/* (introduce proper delay inside macro execution) */ \
tmpreg = READ_BIT(FIREWALL->CR, FW_CR_VDE) ; \
UNUSED(tmpreg); \
} while(0)
/** @brief Disable volatile data execution in resetting VDE bit.
* @note VDE bit is ignored when VDS is set. IF VDS = 1, the Volatile data segment can be
* executed whatever the VDE bit value.
* @note When VDE bit is reset (with VDS = 0), the volatile data segment cannot be executed.
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
*/
#define __HAL_FIREWALL_VOLATILEDATA_EXECUTION_DISABLE() \
do { \
__IO uint32_t tmpreg; \
CLEAR_BIT(FIREWALL->CR, FW_CR_VDE) ; \
/* Read bit back to ensure it is taken into account by IP */ \
/* (introduce proper delay inside macro execution) */ \
tmpreg = READ_BIT(FIREWALL->CR, FW_CR_VDE) ; \
UNUSED(tmpreg); \
} while(0)
/** @brief Check whether or not the volatile data segment is shared.
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
* @retval VDS bit setting status (TRUE or FALSE).
*/
#define __HAL_FIREWALL_GET_VOLATILEDATA_SHARED() ((FIREWALL->CR & FW_CR_VDS) == FW_CR_VDS)
/** @brief Check whether or not the volatile data segment is declared executable.
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
* @retval VDE bit setting status (TRUE or FALSE).
*/
#define __HAL_FIREWALL_GET_VOLATILEDATA_EXECUTION() ((FIREWALL->CR & FW_CR_VDE) == FW_CR_VDE)
/** @brief Check whether or not the Firewall pre arm bit is set.
* @note This macro can be executed inside a code area protected by the Firewall.
* @note This macro can be executed whatever the Firewall state (opened or closed) when
* NVDSL register is equal to 0. Otherwise (when NVDSL register is different from
* 0, that is, when the non volatile data segment is defined), the macro can be
* executed only when the Firewall is opened.
* @retval FPA bit setting status (TRUE or FALSE).
*/
#define __HAL_FIREWALL_GET_PREARM() ((FIREWALL->CR & FW_CR_FPA) == FW_CR_FPA)
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup FIREWALL_Exported_Functions FIREWALL Exported Functions
* @{
*/
/** @defgroup FIREWALL_Exported_Functions_Group1 Initialization Functions
* @brief Initialization and Configuration Functions
* @{
*/
/* Initialization functions ********************************/
HAL_StatusTypeDef HAL_FIREWALL_Config(FIREWALL_InitTypeDef * fw_init);
void HAL_FIREWALL_GetConfig(FIREWALL_InitTypeDef * fw_config);
void HAL_FIREWALL_EnableFirewall(void);
void HAL_FIREWALL_EnablePreArmFlag(void);
void HAL_FIREWALL_DisablePreArmFlag(void);
/**
* @}
*/
/**
* @}
*/
/* Define the private group ***********************************/
/**************************************************************/
/** @defgroup FIREWALL_Private FIREWALL Private
* @{
*/
/**
* @}
*/
/**************************************************************/
/**
* @}
*/
/**
* @}
*/
#endif /* #if !defined (STM32L011xx) && !defined (STM32L021xx) && !defined (STM32L031xx) && !defined (STM32L041xx) */
#ifdef __cplusplus
}
#endif
#endif /* __STM32L0xx_HAL_FIREWALL_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"content_hash": "b771e1b455928f038d74f6ec91f22c07",
"timestamp": "",
"source": "github",
"line_count": 351,
"max_line_length": 189,
"avg_line_length": 50.56410256410256,
"alnum_prop": 0.5349335136353391,
"repo_name": "LordOfDorks/miniDICE",
"id": "393195a8351261b5e7c1b15b95a898a01f6f6770",
"size": "19807",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "TCPSApp/Drivers/STM32L0xx_HAL_Driver/Inc/stm32l0xx_hal_firewall.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "564257"
},
{
"name": "Batchfile",
"bytes": "1485"
},
{
"name": "C",
"bytes": "28873998"
},
{
"name": "C++",
"bytes": "1374837"
}
],
"symlink_target": ""
} |
import re
import six
from cassandra.util import OrderedDict
from cassandra.cqlengine import CQLEngineException
from cassandra.cqlengine import columns
from cassandra.cqlengine import connection
from cassandra.cqlengine import models
class UserTypeException(CQLEngineException):
pass
class UserTypeDefinitionException(UserTypeException):
pass
class BaseUserType(object):
"""
The base type class; don't inherit from this, inherit from UserType, defined below
"""
__type_name__ = None
_fields = None
_db_map = None
def __init__(self, **values):
self._values = {}
for name, field in self._fields.items():
value = values.get(name, None)
if value is not None or isinstance(field, columns.BaseContainerColumn):
value = field.to_python(value)
value_mngr = field.value_manager(self, field, value)
if name in values:
value_mngr.explicit = True
self._values[name] = value_mngr
def __eq__(self, other):
if self.__class__ != other.__class__:
return False
keys = set(self._fields.keys())
other_keys = set(other._fields.keys())
if keys != other_keys:
return False
for key in other_keys:
if getattr(self, key, None) != getattr(other, key, None):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return "{{{0}}}".format(', '.join("'{0}': {1}".format(k, getattr(self, k)) for k, v in six.iteritems(self._values)))
def has_changed_fields(self):
return any(v.changed for v in self._values.values())
def reset_changed_fields(self):
for v in self._values.values():
v.reset_previous_value()
def __iter__(self):
for field in self._fields.keys():
yield field
def __getitem__(self, key):
if not isinstance(key, six.string_types):
raise TypeError
if key not in self._fields.keys():
raise KeyError
return getattr(self, key)
def __setitem__(self, key, val):
if not isinstance(key, six.string_types):
raise TypeError
if key not in self._fields.keys():
raise KeyError
return setattr(self, key, val)
def __len__(self):
try:
return self._len
except:
self._len = len(self._columns.keys())
return self._len
def keys(self):
""" Returns a list of column IDs. """
return [k for k in self]
def values(self):
""" Returns list of column values. """
return [self[k] for k in self]
def items(self):
""" Returns a list of column ID/value tuples. """
return [(k, self[k]) for k in self]
@classmethod
def register_for_keyspace(cls, keyspace):
connection.register_udt(keyspace, cls.type_name(), cls)
@classmethod
def type_name(cls):
"""
Returns the type name if it's been defined
otherwise, it creates it from the class name
"""
if cls.__type_name__:
type_name = cls.__type_name__.lower()
else:
camelcase = re.compile(r'([a-z])([A-Z])')
ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s)
type_name = ccase(cls.__name__)
# trim to less than 48 characters or cassandra will complain
type_name = type_name[-48:]
type_name = type_name.lower()
type_name = re.sub(r'^_+', '', type_name)
cls.__type_name__ = type_name
return type_name
def validate(self):
"""
Cleans and validates the field values
"""
pass
for name, field in self._fields.items():
v = getattr(self, name)
if v is None and not self._values[name].explicit and field.has_default:
v = field.get_default()
val = field.validate(v)
setattr(self, name, val)
class UserTypeMetaClass(type):
def __new__(cls, name, bases, attrs):
field_dict = OrderedDict()
field_defs = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)]
field_defs = sorted(field_defs, key=lambda x: x[1].position)
def _transform_column(field_name, field_obj):
field_dict[field_name] = field_obj
field_obj.set_column_name(field_name)
attrs[field_name] = models.ColumnDescriptor(field_obj)
# transform field definitions
for k, v in field_defs:
# don't allow a field with the same name as a built-in attribute or method
if k in BaseUserType.__dict__:
raise UserTypeDefinitionException("field '{0}' conflicts with built-in attribute/method".format(k))
_transform_column(k, v)
# create db_name -> model name map for loading
db_map = {}
for field_name, field in field_dict.items():
db_map[field.db_field_name] = field_name
attrs['_fields'] = field_dict
attrs['_db_map'] = db_map
klass = super(UserTypeMetaClass, cls).__new__(cls, name, bases, attrs)
return klass
@six.add_metaclass(UserTypeMetaClass)
class UserType(BaseUserType):
"""
This class is used to model User Defined Types. To define a type, declare a class inheriting from this,
and assign field types as class attributes:
.. code-block:: python
# connect with default keyspace ...
from cassandra.cqlengine.columns import Text, Integer
from cassandra.cqlengine.usertype import UserType
class address(UserType):
street = Text()
zipcode = Integer()
from cassandra.cqlengine import management
management.sync_type(address)
Please see :ref:`user_types` for a complete example and discussion.
"""
__type_name__ = None
"""
*Optional.* Sets the name of the CQL type for this type.
If not specified, the type name will be the name of the class, with it's module name as it's prefix.
"""
| {
"content_hash": "8a17b9a0683b679c2a51bc979cc6e056",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 124,
"avg_line_length": 30.524509803921568,
"alnum_prop": 0.5829452384775976,
"repo_name": "jregovic/python-driver",
"id": "88ec033ba8e26600349f385cebd97b04e3e96eec",
"size": "6227",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "cassandra/cqlengine/usertype.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "28918"
},
{
"name": "Python",
"bytes": "1710751"
}
],
"symlink_target": ""
} |
/* eslint-disable */
var path = require("path");
var express = require("express");
var webpack = require("webpack");
var config = require("./webpack.config");
var app = express();
var compiler = webpack(config);
var serverPort = process.env.PORT || 3000;
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use(express.static('assets'));
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "index.html"));
});
app.listen(serverPort, "localhost", function (err) {
if (err) {
console.log(err);
return;
}
console.log("Listening at http://localhost:" + serverPort);
});
| {
"content_hash": "ae4fb712773a2cc9d7ac3f3396331e37",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 61,
"avg_line_length": 21.41176470588235,
"alnum_prop": 0.6689560439560439,
"repo_name": "mathieulesniak/presentation-reactjs",
"id": "9617aafa9d83451e250e9795bc8fac523597511d",
"size": "728",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9076"
},
{
"name": "HTML",
"bytes": "1547"
},
{
"name": "JavaScript",
"bytes": "85630"
}
],
"symlink_target": ""
} |
package org.apache.syncope.core.provisioning.api.data;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.syncope.common.lib.request.UserCR;
import org.apache.syncope.common.lib.request.UserUR;
import org.apache.syncope.common.lib.to.LinkedAccountTO;
import org.apache.syncope.common.lib.to.UserTO;
import org.apache.syncope.core.persistence.api.entity.user.LinkedAccount;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.provisioning.api.PropagationByResource;
public interface UserDataBinder {
UserTO getAuthenticatedUserTO();
UserTO getUserTO(String key);
UserTO getUserTO(User user, boolean details);
LinkedAccountTO getLinkedAccountTO(LinkedAccount account);
void create(User user, UserCR userCR);
/**
* Update user, given {@link UserUR}.
*
* @param toBeUpdated user to be updated
* @param userUR bean containing update request
* @return updated user + propagation by resource
* @see PropagationByResource
*/
Pair<PropagationByResource<String>, PropagationByResource<Pair<String, String>>> update(
User toBeUpdated, UserUR userUR);
}
| {
"content_hash": "480ef50c3a03b74a54df69159d8fdcaa",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 92,
"avg_line_length": 33.74285714285714,
"alnum_prop": 0.7569856054191363,
"repo_name": "apache/syncope",
"id": "05987f4b8d14a9e6d94edf4ad9e3f445f29bfaf1",
"size": "1988",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/provisioning-api/src/main/java/org/apache/syncope/core/provisioning/api/data/UserDataBinder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1932"
},
{
"name": "Batchfile",
"bytes": "1044"
},
{
"name": "CSS",
"bytes": "44883"
},
{
"name": "Dockerfile",
"bytes": "8716"
},
{
"name": "Groovy",
"bytes": "78474"
},
{
"name": "HTML",
"bytes": "549487"
},
{
"name": "Java",
"bytes": "13523162"
},
{
"name": "JavaScript",
"bytes": "36620"
},
{
"name": "PLpgSQL",
"bytes": "20311"
},
{
"name": "SCSS",
"bytes": "65724"
},
{
"name": "Shell",
"bytes": "6231"
},
{
"name": "TSQL",
"bytes": "11632"
},
{
"name": "XSLT",
"bytes": "5158"
}
],
"symlink_target": ""
} |
package org.apache.fop.afp.goca;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.apache.fop.afp.fonts.CharacterSet;
import org.apache.fop.afp.fonts.CharacterSetBuilder;
import org.apache.fop.fonts.Typeface;
public class GraphicsCharacterStringTestCase {
private GraphicsCharacterString gcsCp500;
private GraphicsCharacterString gcsCp1146;
// consider the EBCDIC code page variants Cp500 and Cp1146
// the <A3> (pound sign) corresponds to byte 5B (position 91) in the CCSID 285 and CCSID 1146
// the $ corresponds to byte 5B (position 91) in the CCSID 500
private final String poundsText = "\u00A3\u00A3\u00A3\u00A3";
private final String dollarsText = "$$$$";
private final byte[] bytesToCheck = {(byte) 0x5b, (byte) 0x5b, (byte) 0x5b, (byte) 0x5b};
@Before
public void setUp() throws Exception {
CharacterSetBuilder csb = CharacterSetBuilder.getSingleByteInstance();
CharacterSet cs1146 = csb.build("C0H200B0", "T1V10500", "Cp1146",
Class.forName("org.apache.fop.fonts.base14.Helvetica").asSubclass(Typeface.class)
.getDeclaredConstructor().newInstance(), null);
gcsCp1146 = new GraphicsCharacterString(poundsText, 0, 0, cs1146);
CharacterSet cs500 = csb.build("C0H200B0", "T1V10500", "Cp500",
Class.forName("org.apache.fop.fonts.base14.Helvetica").asSubclass(Typeface.class)
.getDeclaredConstructor().newInstance(), null);
gcsCp500 = new GraphicsCharacterString(dollarsText, 0, 0, cs500);
}
@Test
public void testWriteToStream() throws IOException {
// check pounds
ByteArrayOutputStream baos1146 = new ByteArrayOutputStream();
gcsCp1146.writeToStream(baos1146);
byte[] bytes1146 = baos1146.toByteArray();
for (int i = 0; i < bytesToCheck.length; i++) {
assertEquals(bytesToCheck[i], bytes1146[6 + i]);
}
assertEquals(bytesToCheck.length + 6, bytes1146.length);
// check dollars
ByteArrayOutputStream baos500 = new ByteArrayOutputStream();
gcsCp500.writeToStream(baos500);
byte[] bytes500 = baos500.toByteArray();
for (int i = 0; i < bytesToCheck.length; i++) {
assertEquals(bytesToCheck[i], bytes500[6 + i]);
}
assertEquals(bytesToCheck.length + 6, bytes500.length);
}
}
| {
"content_hash": "ec5e711ccc8132b5735c914c500fc07f",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 97,
"avg_line_length": 43.37931034482759,
"alnum_prop": 0.6784578696343402,
"repo_name": "chunlinyao/fop",
"id": "edd777a1ce4d31a5a2fdd5ed2240d5f334495ff1",
"size": "3318",
"binary": false,
"copies": "4",
"ref": "refs/heads/yao",
"path": "fop-core/src/test/java/org/apache/fop/afp/goca/GraphicsCharacterStringTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7179"
},
{
"name": "HTML",
"bytes": "70784"
},
{
"name": "Java",
"bytes": "13720910"
},
{
"name": "JavaScript",
"bytes": "10800"
},
{
"name": "PostScript",
"bytes": "1032"
},
{
"name": "Python",
"bytes": "21418"
},
{
"name": "Shell",
"bytes": "15679"
},
{
"name": "XSLT",
"bytes": "145566"
}
],
"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("UsbDummyProtectGui")]
[assembly: AssemblyDescription("Utility for protecting USB drives from viruses")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Igor Kostenko")]
[assembly: AssemblyProduct("UsbDummyProtectGui")]
[assembly: AssemblyCopyright("Copyright © Igor Kostenko 2010")]
[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("0f187eeb-0adf-44c4-a3e2-9cf3e6ac0997")]
// 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.2.0.4")]
[assembly: AssemblyFileVersion("1.2.0.4")]
| {
"content_hash": "92f57dbf3b0321a61b3d454823cfb00b",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 41.138888888888886,
"alnum_prop": 0.7542201215395004,
"repo_name": "isanych/usbdummyprotect",
"id": "1587a4de3e8de6948e70bfb2ff05c0a57c4af6bd",
"size": "1484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UsbDummyProtectGui/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "10692"
},
{
"name": "C++",
"bytes": "9592"
}
],
"symlink_target": ""
} |
/**
*
*/
package org.apache.cassandra.service;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import java.net.InetAddress;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.Table;
import org.apache.cassandra.locator.IEndpointSnitch;
import org.apache.cassandra.locator.NetworkTopologyStrategy;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.UnavailableException;
import com.google.common.collect.Multimap;
import org.apache.cassandra.utils.FBUtilities;
/**
* This class blocks for a quorum of responses _in all datacenters_ (CL.EACH_QUORUM).
*/
public class DatacenterSyncWriteResponseHandler extends AbstractWriteResponseHandler
{
private static final IEndpointSnitch snitch = DatabaseDescriptor.getEndpointSnitch();
private static final String localdc;
static
{
localdc = snitch.getDatacenter(FBUtilities.getLocalAddress());
}
private final NetworkTopologyStrategy strategy;
private HashMap<String, AtomicInteger> responses = new HashMap<String, AtomicInteger>();
protected DatacenterSyncWriteResponseHandler(Collection<InetAddress> writeEndpoints, Multimap<InetAddress, InetAddress> hintedEndpoints, ConsistencyLevel consistencyLevel, String table)
{
// Response is been managed by the map so make it 1 for the superclass.
super(writeEndpoints, hintedEndpoints, consistencyLevel);
assert consistencyLevel == ConsistencyLevel.LOCAL_QUORUM;
strategy = (NetworkTopologyStrategy) Table.open(table).getReplicationStrategy();
for (String dc : strategy.getDatacenters())
{
int rf = strategy.getReplicationFactor(dc);
responses.put(dc, new AtomicInteger((rf / 2) + 1));
}
}
public static IWriteResponseHandler create(Collection<InetAddress> writeEndpoints, Multimap<InetAddress, InetAddress> hintedEndpoints, ConsistencyLevel consistencyLevel, String table)
{
return new DatacenterSyncWriteResponseHandler(writeEndpoints, hintedEndpoints, consistencyLevel, table);
}
public void response(Message message)
{
String dataCenter = message == null
? localdc
: snitch.getDatacenter(message.getFrom());
responses.get(dataCenter).getAndDecrement();
for (AtomicInteger i : responses.values())
{
if (0 < i.get())
return;
}
// all the quorum conditions are met
condition.signal();
}
public void assureSufficientLiveNodes() throws UnavailableException
{
Map<String, AtomicInteger> dcEndpoints = new HashMap<String, AtomicInteger>();
for (String dc: strategy.getDatacenters())
dcEndpoints.put(dc, new AtomicInteger());
for (InetAddress destination : hintedEndpoints.keySet())
{
assert writeEndpoints.contains(destination);
// figure out the destination dc
String destinationDC = snitch.getDatacenter(destination);
dcEndpoints.get(destinationDC).incrementAndGet();
}
// Throw exception if any of the DC doesn't have livenodes to accept write.
for (String dc: strategy.getDatacenters())
{
if (dcEndpoints.get(dc).get() != responses.get(dc).get())
throw new UnavailableException();
}
}
}
| {
"content_hash": "80f99e68f70b107f6ebe218a5f156441",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 189,
"avg_line_length": 37.00847457627118,
"alnum_prop": 0.7068926036180444,
"repo_name": "stuhood/cassandra-old",
"id": "86278f4d25b8d5428d1871852038fef89d5c6d26",
"size": "4367",
"binary": false,
"copies": "1",
"ref": "refs/heads/bitidx",
"path": "src/java/org/apache/cassandra/service/DatacenterSyncWriteResponseHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4036723"
},
{
"name": "PHP",
"bytes": "414"
},
{
"name": "Python",
"bytes": "179989"
},
{
"name": "Shell",
"bytes": "7890"
}
],
"symlink_target": ""
} |
from rest_framework import viewsets
from rest_framework import pagination
from django_filters.rest_framework import DjangoFilterBackend
from .models import SkosConcept, SkosConceptScheme, SkosLabel, SkosNamespace
from .serializers import (
SkosLabelSerializer, SkosNamespaceSerializer, SkosConceptSchemeSerializer, SkosConceptSerializer
)
from .filters import SkosConceptFilter
from .api_renderers import RDFRenderer
from rest_framework.settings import api_settings
class LargeResultsSetPagination(pagination.PageNumberPagination):
page_size = 25
page_size_query_param = 'page_size'
max_page_size = 10000
class SkosLabelViewSet(viewsets.ModelViewSet):
queryset = SkosLabel.objects.all()
serializer_class = SkosLabelSerializer
class SkosNamespaceViewSet(viewsets.ModelViewSet):
queryset = SkosNamespace.objects.all()
serializer_class = SkosNamespaceSerializer
class SkosConceptSchemeViewSet(viewsets.ModelViewSet):
queryset = SkosConceptScheme.objects.all()
serializer_class = SkosConceptSchemeSerializer
class SkosConceptViewSet(viewsets.ModelViewSet):
queryset = SkosConcept.objects.all()
serializer_class = SkosConceptSerializer
filter_backends = (DjangoFilterBackend,)
filter_class = SkosConceptFilter
pagination_class = LargeResultsSetPagination
renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + (RDFRenderer,)
| {
"content_hash": "94a4eb0c27ad0674318b6c9202e94632",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 100,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.8028368794326242,
"repo_name": "acdh-oeaw/vhioe",
"id": "6264881fd6db04c6b802fd4a6f639f65fadac7f1",
"size": "1410",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vocabs/api_views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25850"
},
{
"name": "HTML",
"bytes": "105907"
},
{
"name": "JavaScript",
"bytes": "220270"
},
{
"name": "Python",
"bytes": "91715"
}
],
"symlink_target": ""
} |
title: Prime pair connection
localeTitle: Соединение с главной парой
---
## Проблема 134: Соединение с главной парой
Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-134-prime-pair-connection/index.md) .
[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) . | {
"content_hash": "b0df0e36721b2b43b45c0c0e24699333",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 214,
"avg_line_length": 59,
"alnum_prop": 0.8072033898305084,
"repo_name": "HKuz/FreeCodeCamp",
"id": "5d86323b27cff1e4f450124d2929a46ddb202644",
"size": "638",
"binary": false,
"copies": "4",
"ref": "refs/heads/fix/JupyterNotebook",
"path": "guide/russian/certifications/coding-interview-prep/project-euler/problem-134-prime-pair-connection/index.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "193850"
},
{
"name": "HTML",
"bytes": "100244"
},
{
"name": "JavaScript",
"bytes": "522369"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using Webshop.Infrastructure.Data.Entities;
namespace Webshop.Models
{
public class ArticleModel
{
public IEnumerable<Category> Categories { get; set; }
public int SelectedCategoryId { get; set; }
public Product Product { get; set; }
}
} | {
"content_hash": "bd98fc976d3931aff883f56c17cf3dd7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 61,
"avg_line_length": 25.75,
"alnum_prop": 0.686084142394822,
"repo_name": "JuergenGutsch/dotnetpro-node-vs-net",
"id": "805a61d18b57c7971006149e2e290fb9d46f05c3",
"size": "311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Aufgabe02/Webshop/Webshop/Models/ArticleModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "313"
},
{
"name": "C#",
"bytes": "307298"
},
{
"name": "CSS",
"bytes": "9106"
},
{
"name": "JavaScript",
"bytes": "154886"
},
{
"name": "PowerShell",
"bytes": "40145"
}
],
"symlink_target": ""
} |
class AddCountryCodeToPickup < ActiveRecord::Migration
def change
add_column :pickups, :country_code, :string, :default => "+1"
end
end
| {
"content_hash": "fabfe3844dc70a3a575346a64810b2e9",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 65,
"avg_line_length": 28.8,
"alnum_prop": 0.7222222222222222,
"repo_name": "teamhacksmiths/food-drivr",
"id": "6c4dce40c7dd0d2b58d40bf828da699acfd36f9b",
"size": "144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20160506235045_add_country_code_to_pickup.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3806"
},
{
"name": "CoffeeScript",
"bytes": "2983"
},
{
"name": "HTML",
"bytes": "5652"
},
{
"name": "JavaScript",
"bytes": "661"
},
{
"name": "Ruby",
"bytes": "183091"
}
],
"symlink_target": ""
} |
<?php
namespace Helper;
/**
* Class DebugUtils
*
* @package Helper
*/
class DebugUtils
{
/**
* Print information about class that called this method
*
* @param int $index
*/
public static function printCallClassInfo($index = null)
{
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
if ($index && isset($backtrace[$index])) {
hd_print(
sprintf(
'%s::%s():%d',
$backtrace[$index]['class'],
$backtrace[$index]['function'],
$backtrace[$index]['line']
)
);
return;
}
foreach ($backtrace as $i => $item) {
hd_print(sprintf('%d. %s::%s():%d', $i, $item['class'], $item['function'], $item['line']));
}
}
/**
* @param object $input
*/
public static function logUserInput($input)
{
if (!Utils::isDebugMode()) {
return;
}
self::drawSeparateLine();
self::printCallClassInfo(2);
$lengths = array_map('strlen', array_keys((array) $input));
$maxLength = max($lengths);
foreach ($input as $key => $value) {
hd_print("\t" . str_pad($key, $maxLength, ' ') . ": (string) $value");
}
self::drawSeparateLine();
}
/**
* Draw the separate line
*/
public static function drawSeparateLine()
{
hd_print(str_repeat('-', 80));
}
/**
* @param mixed $value
* @param bool $showTrace
*/
public static function print_r($value, $showTrace = false)
{
if (!Utils::isDebugMode()) {
return;
}
self::drawSeparateLine();
if ($showTrace) {
self::printCallClassInfo();
}
hd_print(var_export($value, true));
}
}
| {
"content_hash": "c0ad19f00552057dbf9cf8dbc7b30324",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 103,
"avg_line_length": 21.556818181818183,
"alnum_prop": 0.4765419082762256,
"repo_name": "fluxuator/dune_plugin_menu_manager",
"id": "6c295f515bbd978fbe09248ba2e2cef0f1ce51fc",
"size": "1897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Helper/DebugUtils.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "105994"
}
],
"symlink_target": ""
} |
from ..helpers.search_helpers import get_filters_from_request
def sections_for_lot(lot, builder):
if lot is None or lot == 'all':
sections = builder.filter(
{'lot': 'iaas'}).filter(
{'lot': 'paas'}).filter(
{'lot': 'saas'}).filter(
{'lot': 'scs'}).sections
else:
sections = builder.filter({'lot': lot}).sections
return sections
def filters_for_lot(lot, builder):
sections = sections_for_lot(lot, builder)
lot_filters = []
for section in sections:
section_filter = {
"label": section["name"],
"filters": [],
}
for question in section["questions"]:
section_filter["filters"].extend(
filters_for_question(question)
)
lot_filters.append(section_filter)
return lot_filters
def filters_for_question(question):
question_filters = []
if question['type'] == 'boolean':
question_filters.append({
'label': question['question'],
'name': question['id'],
'id': question['id'],
'value': 'true',
})
elif question['type'] in ['checkboxes', 'radios']:
for option in question['options']:
question_filters.append({
'label': option['label'],
'name': question['id'],
'id': '{}-{}'.format(
question['id'],
option['label'].lower().replace(' ', '-')),
'value': option['label'].lower(),
})
return question_filters
def set_filter_states(filter_groups, request):
"""Sets a flag on each filter to mark it as set or not"""
request_filters = get_filters_from_request(request)
for filter_group in filter_groups:
for filter in filter_group['filters']:
filter['checked'] = False
param_values = request_filters.getlist(
filter['name'],
type=str
)
if len(param_values) > 0:
filter['checked'] = (
filter['value'] in param_values
)
| {
"content_hash": "f758565c69eac4184a48278cb434e56e",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 63,
"avg_line_length": 29.256756756756758,
"alnum_prop": 0.5108545034642032,
"repo_name": "AusDTO/dto-digitalmarketplace-buyer-frontend",
"id": "56c82725fb620d1c30758d485f1966271ee30eac",
"size": "2165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/presenters/search_presenters.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "904"
},
{
"name": "Gherkin",
"bytes": "6490"
},
{
"name": "HTML",
"bytes": "314252"
},
{
"name": "JavaScript",
"bytes": "38480"
},
{
"name": "Makefile",
"bytes": "1461"
},
{
"name": "Python",
"bytes": "414306"
},
{
"name": "SCSS",
"bytes": "140490"
},
{
"name": "Shell",
"bytes": "5964"
}
],
"symlink_target": ""
} |
<?php
namespace AppBundle\Legacy\Util\Validation\Validator;
use AppBundle\Entity\Community;
use AppBundle\Entity\Participant;
use AppBundle\Entity\Player;
use AppBundle\Legacy\Util\General\ErrorCodes;
use AppBundle\Repository\CommunityRepository;
use AppBundle\Repository\ParticipantRepository;
use AppBundle\Repository\PlayerRepository;
use Doctrine\Common\Persistence\ObjectManager;
/**
* Validate data existence.
*/
class ExistenceValidator extends AbstractValidator
{
/**
* @var ObjectManager
*/
private $manager;
/**
* ExistenceValidator constructor.
* @param ObjectManager $manager
*/
public function __construct(
ObjectManager $manager
) {
parent::__construct();
$this->manager = $manager;
}
/**
* Check if nickname of player is already in use.
*
* @param Player $player
* @return $this
*/
public function checkIfNicknameExists(Player $player)
{
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->manager->getRepository(Player::class);
try {
$existsNickname = $playerRepository->checkNickameExists($player->getNickname());
if ($existsNickname) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::PLAYER_USERNAME_ALREADY_EXISTS,
"Ya existe un usuario con ese nickname."
);
}
} catch (\Throwable $e) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::DEFAULT_ERROR,
"Error comprobando la existencia del nickname."
);
}
return $this;
}
/**
* Check if email is already in use.
*
* @param Player $player
* @return $this
*/
public function checkIfEmailExists(Player $player)
{
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->manager->getRepository(Player::class);
try {
$existsEmail = $playerRepository->checkEmailExists($player->getEmail());
if ($existsEmail) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::PLAYER_EMAIL_ALREADY_EXISTS,
"Ya existe un usuario con ese email."
);
}
} catch (\Throwable $e) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::DEFAULT_ERROR,
"Error comprobando la existencia del email."
);
}
return $this;
}
/**
* Check if community name is already in use.
*
* @param Community $community
* @return $this
*/
public function checkIfNameExists(Community $community)
{
/** @var CommunityRepository $communityRepository */
$communityRepository = $this->manager->getRepository(Community::class);
try {
$existsName = $communityRepository->checkIfNameExists($community->getName());
if ($existsName) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::COMMUNITY_NAME_ALREADY_EXISTS,
"Ya existe una comunidad con ese nombre."
);
}
} catch (\Throwable $e) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::DEFAULT_ERROR,
"Error comprobando la existencia del nombre de la comunidad."
);
}
return $this;
}
/**
* Check if player is already a member from community.
*
* @param Player $player
* @param Community $community
* @return $this
*/
public function checkIfPlayerIsAlreadyFromCommunity(Player $player, Community $community)
{
/** @var ParticipantRepository $participantRepo */
$participantRepo = $this->manager->getRepository(Participant::class);
try {
$exists = $participantRepo->checkIfPlayerIsAlreadyFromCommunity($player, $community);
if ($exists) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::PLAYER_IS_ALREADY_MEMBER,
sprintf(
'El jugador %s ya es miembro de la comunidad %s.',
$player->getNickname(),
$community->getName()
)
);
}
} catch (\Throwable $e) {
$this->result->isError();
$this->result->addMessageWithCode(
ErrorCodes::DEFAULT_ERROR,
"Error comprobando si el jugador ya participa en la comunidad pasada."
);
}
return $this;
}
/**
* @inheritdoc
*/
public function validate(): void
{
if ($this->result->hasError()) {
$this->result->setDescription("Error registro existente");
}
parent::validate();
}
}
| {
"content_hash": "875aaa50faa19a5be0a350e1a5e21b14",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 97,
"avg_line_length": 29.29608938547486,
"alnum_prop": 0.5501525553012967,
"repo_name": "rjcorflo/pronosticapp-backend",
"id": "ae76f73f2cb95f0862008b3f77482b83d2bed617",
"size": "5244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppBundle/Legacy/Util/Validation/Validator/ExistenceValidator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "CSS",
"bytes": "1105"
},
{
"name": "HTML",
"bytes": "9436"
},
{
"name": "PHP",
"bytes": "352596"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Reset src after setMediaKeys()</title>
<script src="encrypted-media-utils.js"></script>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
</head>
<body>
<video></video>
<script>
async_test(function(test)
{
var mediaKeys;
var encryptedEventIndex = 0;
var video = document.querySelector('video');
assert_not_equals(video, null);
// Content to be played. These files must be the same format.
var content = '../content/test-encrypted.webm';
var alternateContent = '../content/test-encrypted-different-av-keys.webm';
var onEncrypted = function(event)
{
++encryptedEventIndex;
assert_not_equals(video.mediaKeys, null);
assert_true(video.mediaKeys === mediaKeys);
// This event is fired once for the audio stream and once
// for the video stream each time .src is set.
if (encryptedEventIndex == 2) {
// Finished first video; set src to a different video.
video.src = alternateContent;
} else if (encryptedEventIndex == 4) {
// Finished second video.
test.done();
}
};
// Create a MediaKeys object and assign it to video.
navigator.requestMediaKeySystemAccess('org.w3.clearkey', getConfigurationForFile(content))
.then(function(access) {
assert_equals(access.keySystem, 'org.w3.clearkey');
return access.createMediaKeys();
}).then(function(result) {
mediaKeys = result;
assert_not_equals(mediaKeys, null);
return video.setMediaKeys(mediaKeys);
}).then(function(result) {
assert_not_equals(video.mediaKeys, null, 'not set initially');
assert_true(video.mediaKeys === mediaKeys);
// Set src to a video.
waitForEventAndRunStep('encrypted', video, onEncrypted, test);
video.src = content;
}).catch(function(error) {
forceTestFailureFromPromise(test, error);
});
}, 'Reset src after setMediaKeys().');
</script>
</body>
</html>
| {
"content_hash": "d5b42cac0c6f329ae2e43638a0c3283b",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 106,
"avg_line_length": 43.225806451612904,
"alnum_prop": 0.5014925373134328,
"repo_name": "ric2b/Vivaldi-browser",
"id": "6361926cb913b254b8cd58001dccf109c2f7c56c",
"size": "2680",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "chromium/third_party/blink/web_tests/media/encrypted-media/encrypted-media-reset-src-after-setmediakeys.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace EC2
{
namespace Model
{
enum class ReservedInstanceState
{
NOT_SET,
payment_pending,
active,
payment_failed,
retired,
queued,
queued_deleted
};
namespace ReservedInstanceStateMapper
{
AWS_EC2_API ReservedInstanceState GetReservedInstanceStateForName(const Aws::String& name);
AWS_EC2_API Aws::String GetNameForReservedInstanceState(ReservedInstanceState value);
} // namespace ReservedInstanceStateMapper
} // namespace Model
} // namespace EC2
} // namespace Aws
| {
"content_hash": "dd56eca6a828e9f54ee6ed88620c12f0",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 91,
"avg_line_length": 19.53125,
"alnum_prop": 0.7504,
"repo_name": "jt70471/aws-sdk-cpp",
"id": "590d013185b72a739208b1175588024c067affa8",
"size": "744",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-ec2/include/aws/ec2/model/ReservedInstanceState.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "13452"
},
{
"name": "C++",
"bytes": "278594037"
},
{
"name": "CMake",
"bytes": "653931"
},
{
"name": "Dockerfile",
"bytes": "5555"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "302182"
},
{
"name": "Python",
"bytes": "110380"
},
{
"name": "Shell",
"bytes": "4674"
}
],
"symlink_target": ""
} |
package org.springframework.social.showcase.signin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class SigninController {
@RequestMapping(value="/signin", method=RequestMethod.GET)
public void signin() {
}
}
| {
"content_hash": "2c1006bd9946c1363358db616b4f030a",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 62,
"avg_line_length": 26,
"alnum_prop": 0.8186813186813187,
"repo_name": "tanvirshuvo/spring-social-samples",
"id": "c443b362178d079ae0838347471ed4f2f22a910b",
"size": "979",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "spring-social-showcase/src/main/java/org/springframework/social/showcase/signin/SigninController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17264"
},
{
"name": "HTML",
"bytes": "118890"
},
{
"name": "Java",
"bytes": "508116"
}
],
"symlink_target": ""
} |
using FclEx.Extensions;
namespace FclEx.Http.Core
{
/// <summary>
/// Contains the standard set of headers applicable to an HTTP request.
/// </summary>
public static class HttpKnownHeaderNames
{
public const string Accept = "Accept";
public const string AcceptCharset = "Accept-Charset";
public const string AcceptEncoding = "Accept-Encoding";
public const string AcceptLanguage = "Accept-Language";
public const string AcceptPatch = "Accept-Patch";
public const string AcceptRanges = "Accept-Ranges";
public const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
public const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
public const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
public const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
public const string AccessControlExposeHeaders = "Access-Control-Expose-Headers";
public const string AccessControlMaxAge = "Access-Control-Max-Age";
public const string Age = "Age";
public const string Allow = "Allow";
public const string AltSvc = "Alt-Svc";
public const string Authorization = "Authorization";
public const string CacheControl = "Cache-Control";
public const string Connection = "Connection";
public const string ContentDisposition = "Content-Disposition";
public const string ContentEncoding = "Content-Encoding";
public const string ContentLanguage = "Content-Language";
public const string ContentLength = "Content-Length";
public const string ContentLocation = "Content-Location";
public const string ContentMd5 = "Content-MD5";
public const string ContentRange = "Content-Range";
public const string ContentSecurityPolicy = "Content-Security-Policy";
public const string ContentType = "Content-Type";
public const string Cookie = "Cookie";
public const string Cookie2 = "Cookie2";
public const string Date = "Date";
public const string ETag = "ETag";
public const string Expect = "Expect";
public const string Expires = "Expires";
public const string From = "From";
public const string Host = "Host";
public const string IfMatch = "If-Match";
public const string IfModifiedSince = "If-Modified-Since";
public const string IfNoneMatch = "If-None-Match";
public const string IfRange = "If-Range";
public const string IfUnmodifiedSince = "If-Unmodified-Since";
public const string KeepAlive = "Keep-Alive";
public const string LastModified = "Last-Modified";
public const string Link = "Link";
public const string Location = "Location";
public const string MaxForwards = "Max-Forwards";
public const string Origin = "Origin";
public const string P3P = "P3P";
public const string Pragma = "Pragma";
public const string ProxyAuthenticate = "Proxy-Authenticate";
public const string ProxyAuthorization = "Proxy-Authorization";
public const string ProxyConnection = "Proxy-Connection";
public const string PublicKeyPins = "Public-Key-Pins";
public const string Range = "Range";
public const string Referrer = "Referer"; // NB: The spelling-mistake "Referer" for "Referrer" must be matched.
public const string RetryAfter = "Retry-After";
public const string SecWebSocketAccept = "Sec-WebSocket-Accept";
public const string SecWebSocketExtensions = "Sec-WebSocket-Extensions";
public const string SecWebSocketKey = "Sec-WebSocket-Key";
public const string SecWebSocketProtocol = "Sec-WebSocket-Protocol";
public const string SecWebSocketVersion = "Sec-WebSocket-Version";
public const string Server = "Server";
public const string SetCookie = "Set-Cookie";
public const string SetCookie2 = "Set-Cookie2";
public const string StrictTransportSecurity = "Strict-Transport-Security";
public const string Te = "TE";
public const string Tsv = "TSV";
public const string Trailer = "Trailer";
public const string TransferEncoding = "Transfer-Encoding";
public const string Upgrade = "Upgrade";
public const string UpgradeInsecureRequests = "Upgrade-Insecure-Requests";
public const string UserAgent = "User-Agent";
public const string Vary = "Vary";
public const string Via = "Via";
public const string WwwAuthenticate = "WWW-Authenticate";
public const string Warning = "Warning";
public const string XAspNetVersion = "X-AspNet-Version";
public const string XContentDuration = "X-Content-Duration";
public const string XContentTypeOptions = "X-Content-Type-Options";
public const string XFrameOptions = "X-Frame-Options";
public const string XmsEdgeRef = "X-MSEdge-Ref";
public const string XPoweredBy = "X-Powered-By";
public const string XRequestId = "X-Request-ID";
public const string XuaCompatible = "X-UA-Compatible";
}
public static class HttpConstants
{
public const string DefaultGetContentType = "text/html";
public const string DefaultPostContentType = FormContentType;
public const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3236.0 Safari/537.36";
public const string JsonContentType = "application/json";
public const string FormContentType = "application/x-www-form-urlencoded";
public const string MultiPartContentType = "multipart/form-data";
public const string ByteArrayContentType = "application/octet-stream";
public const string Boundary = "boundary";
public const string NewLine = "\r\n";
public static byte[] NewLineBytes { get; } = NewLine.ToUtf8Bytes();
public static string EncapsulationBoundary { get; } = "--";
public static byte[] EncapsulationBoundaryBytes { get; } = EncapsulationBoundary.ToUtf8Bytes();
}
}
| {
"content_hash": "cab8429874c6a7948599a5ba4c8f62bf",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 163,
"avg_line_length": 56.34234234234234,
"alnum_prop": 0.68324272465622,
"repo_name": "huoshan12345/FclEx",
"id": "9653b34fc7169a472a6a8b8a6c948b0dbe116682",
"size": "6256",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/FclEx.Http/FclEx/Http/Core/HttpConstants.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "779335"
},
{
"name": "PowerShell",
"bytes": "2558"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>TableTools example - Ajax loaded data</title>
<link rel="stylesheet" type="text/css" href="../../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../css/dataTables.tableTools.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../js/dataTables.tableTools.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable( {
dom: 'T<"clear">lfrtip',
"ajax": "../../../../examples/ajax/data/objects.txt",
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
deferRender: true
} );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>TableTools example <span>Ajax loaded data</span></h1>
<div class="info">
<p>This TableTools example shows DataTables using its ability to <a href="//datatables.net/manual/data#Objects">Ajax load object based data</a> and operate in
exactly the same manner as when the data is read directly from the document.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
$('#example').DataTable( {
dom: 'T<"clear">lfrtip',
"ajax": "../../../../examples/ajax/data/objects.txt",
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
deferRender: true
} );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li><a href="../../../media/js/jquery.js">../../../media/js/jquery.js</a></li>
<li><a href="../../../media/js/jquery.dataTables.js">../../../media/js/jquery.dataTables.js</a></li>
<li><a href="../js/dataTables.tableTools.js">../js/dataTables.tableTools.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li><a href="../../../media/css/jquery.dataTables.css">../../../media/css/jquery.dataTables.css</a></li>
<li><a href="../css/dataTables.tableTools.css">../css/dataTables.tableTools.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="index.html">Examples</a></h3>
<ul class="toc active">
<li><a href="simple.html">Basic initialisation</a></li>
<li><a href="swf_path.html">Setting the SWF path</a></li>
<li><a href="new_init.html">Initialisation with `new`</a></li>
<li><a href="defaults.html">Defaults</a></li>
<li><a href="select_single.html">Row selection - single row select</a></li>
<li><a href="select_multi.html">Row selection - multi-row select</a></li>
<li><a href="select_os.html">Row selection - operating system style</a></li>
<li><a href="select_column.html">Row selection - row selector on specific cells</a></li>
<li><a href="multiple_tables.html">Multiple tables</a></li>
<li><a href="multi_instance.html">Multiple toolbars</a></li>
<li><a href="collection.html">Button collections</a></li>
<li><a href="plug-in.html">Plug-in button types</a></li>
<li><a href="button_text.html">Custom button text</a></li>
<li><a href="alter_buttons.html">Button arrangement</a></li>
<li class="active"><a href="./ajax.html">Ajax loaded data</a></li>
<li><a href="pdf_message.html">PDF message</a></li>
<li><a href="bootstrap.html">Bootstrap styling</a></li>
<li><a href="jqueryui.html">jQuery UI styling</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a>
which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2015<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | {
"content_hash": "69768bef6550a962b80246a8ebfbe2ef",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 163,
"avg_line_length": 38.92631578947368,
"alnum_prop": 0.6258788534342888,
"repo_name": "hashcv/ZendSkeletonApplication",
"id": "81fe8089f46dacdde0380a677dceeb1c87def4c4",
"size": "7396",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "public/DataTables/extensions/TableTools/examples/ajax.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "711"
},
{
"name": "CSS",
"bytes": "57718"
},
{
"name": "HTML",
"bytes": "1707294"
},
{
"name": "JavaScript",
"bytes": "789576"
},
{
"name": "PHP",
"bytes": "44385"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<mapped-superclass name="SpecShaper\CalendarBundle\Model\CalendarEvent">
<!-- <lifecycle-callbacks>
<lifecycle-callback type="preFlush" method="updateDateTimes" />
<lifecycle-callback type="preFlush" method="storeEndDatetime" />
</lifecycle-callbacks>-->
<id name="id" type="integer">
<generator strategy="AUTO" />
</id>
<field name="title" type="string" />
<field name="startDatetime" type="datetime" nullable="false"/>
<field name="endDatetime" type="datetime" nullable="false"/>
<field name="url" type="string" length="255" nullable="true"/>
<field name="isAllDay" type="boolean" />
<field name="isReoccuring" type="boolean" />
<field name="text" type="text" nullable="true" />
<field name="bgColor" type="string" />
</mapped-superclass>
</doctrine-mapping>
| {
"content_hash": "be8110d525d9bf47d19a35ab2fa0ab02",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 94,
"avg_line_length": 47.48148148148148,
"alnum_prop": 0.6209048361934477,
"repo_name": "mogilvie/CalendarBundle",
"id": "2e477658da979ca7e7659612ea59f3162e79294a",
"size": "1282",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Resources/config/doctrine-mapping/model/CalendarEvent.orm.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8727"
},
{
"name": "HTML",
"bytes": "9409"
},
{
"name": "JavaScript",
"bytes": "25187"
},
{
"name": "PHP",
"bytes": "124848"
}
],
"symlink_target": ""
} |
package org.newdawn.noodles.chat;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.newdawn.noodles.message.Message;
import org.newdawn.noodles.message.MessageChannel;
/**
* Tiny client for a quick chat example. Creates and maintains a connection. Displays
* a test entry and text area for chat.
*
* @author kevin
*/
public class ChatClient extends JFrame {
/** The text output */
private JTextArea area = new JTextArea(80,20);
/** The text input */
private JTextField in = new JTextField();
/** The channel we're using to communicate with the server */
private MessageChannel channel;
/** The generated user name */
private String name = "User"+System.currentTimeMillis();
/**
* Create a new chat client
*/
public ChatClient() {
JPanel panel = new JPanel();
panel.setLayout(null);
JScrollPane scroll = new JScrollPane(area);
scroll.setBounds(0,0,600,375);
in.setBounds(0,375,600,25);
panel.add(scroll);
panel.add(in);
area.setEditable(false);
in.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendChat();
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
setSize(600,450);
setResizable(false);
}
/**
* Send a chat message based on the text in the input field
*/
private void sendChat() {
String text = in.getText();
in.setText("");
// do local echo
append(name, text);
// send remote chat
try {
channel.write(new ChatMessage(name, text), true);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Append text to the text area working round Swing failings.
*
* @param sender The name of the person sending
* @param text The text the person sent
*/
private void append(String sender, String text) {
String line = sender+":"+text+"\n";
area.append(line);
area.select(area.getText().length(), area.getText().length());
}
/**
* Connect to the server
*
* @throws IOException Indicates a failure to connect
*/
public void connect() throws IOException {
channel = new MessageChannel(new ChatMessageFactory(), "localhost", 12345);
System.out.println("Connected with ID: "+channel.getChannelID());
setVisible(true);
while (!channel.isClosed()) {
Message message = channel.read();
if (message != null) {
if (message.getID() == ChatMessage.ID) {
ChatMessage chat = (ChatMessage) message;
append(chat.getSender(), chat.getText());
}
}
try { Thread.sleep(5); } catch (Exception e) {};
}
}
/**
* Entry point to the client
*
* @param argv The arguments passed in
* @throws IOException Indicates a failure to connect
*/
public static void main(String[] argv) throws IOException {
ChatClient client = new ChatClient();
client.connect();
}
}
| {
"content_hash": "7720c61ea8a70b1e9fc23642ace5bcb6",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 85,
"avg_line_length": 25.950413223140497,
"alnum_prop": 0.6582802547770701,
"repo_name": "SenshiSentou/SourceFight",
"id": "44cacd0dd15b4bbf162e0da9ee76e7ebd78df833",
"size": "3140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "slick_dev/trunk/commet/test/org/newdawn/noodles/chat/ChatClient.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "2377"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "CSS",
"bytes": "2782"
},
{
"name": "GAP",
"bytes": "24471"
},
{
"name": "Java",
"bytes": "11819037"
},
{
"name": "JavaScript",
"bytes": "22036"
},
{
"name": "Scala",
"bytes": "76"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<T3locallangExt>
<data type="array">
<languageKey index="de" type="array">
<label index="mlang_labels_tablabel">Dateiverwaltung auf dem Server</label>
<label index="mlang_tabs_tab">Datei</label>
<label index="sys_file_storage.isOffline">offline</label>
</languageKey>
</data>
</T3locallangExt>
| {
"content_hash": "0544833ed34e4c22e64e8c4389ac0a0e",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 81,
"avg_line_length": 36.3,
"alnum_prop": 0.6749311294765841,
"repo_name": "georgringer/TYPO3.base",
"id": "a7181d1fdb89b1f9122ea2f0b23f652884e6d664",
"size": "363",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "typo3conf/l10n/de/lang/de.locallang_mod_file.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "149147"
},
{
"name": "JavaScript",
"bytes": "142134"
},
{
"name": "PHP",
"bytes": "60253"
},
{
"name": "TypeScript",
"bytes": "48317"
}
],
"symlink_target": ""
} |
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from mse.constants import *
from mse.charset import fix_charset_collation
class EqualityMixin:
def __eq__(self, other):
return (type(other) is type(self)) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
class Table(EqualityMixin):
def __init__(self, name, engine=None, charset=None, collation=None):
self.name = name
self.columns = OrderedDict()
self.indexes = OrderedDict()
self.engine = engine
self.charset, self.collation = fix_charset_collation(charset, collation)
def add_or_update_column(self, column):
assert isinstance(column, Column)
self.columns[column.name] = column
def add_or_update_index(self, index):
assert isinstance(index, Index)
for index_column in index.columns:
if not self.columns.get(index_column.name):
raise ValueError(
"unable to create index [{0}], column [{1}] does not exists in table"
.format(index, index_column.name))
self.indexes[index.name] = index
class IndexColumn(EqualityMixin):
def __init__(self, name, length=0, direction=DIRECTION_ASC):
self.name = name
self.length = length
self.direction = direction
def __repr__(self):
return self.__str__()
def __str__(self):
base = self.name
if self.length > 0:
base += "({0})".format(self.length)
if self.direction == DIRECTION_DESC:
base += " {0}".format(DIRECTION_DESC)
return base
class Index(EqualityMixin):
def __init__(self, name, columns, is_primary=False, is_unique=False):
name = name.strip()
assert name
assert isinstance(columns, list)
assert len(columns) >= 1
self.name = name
self.columns = []
for col in columns:
if isinstance(col, IndexColumn):
self.columns.append(col)
elif isinstance(col, str):
self.columns.append(IndexColumn(col))
else:
raise ValueError("unknown index column {0}".format(col))
self.is_primary = is_primary
# Overwrite is_unique when it's primary
self.is_unique = is_primary or is_unique
def __repr__(self):
return self.__str__()
def __str__(self):
col_str = [str(x) for x in self.columns]
cols = ", ".join(col_str)
if self.is_primary:
return "PRIMARY KEY ({0})".format(cols)
elif self.is_unique:
return "UNIQUE KEY {0} ({1})".format(self.name, cols)
else:
return "KEY {0} ({1})".format(self.name, cols)
class Column(EqualityMixin):
def __init__(self, name, data_type, length=0, decimal=None, nullable=True, charset=None, collation=None):
name = name.strip()
data_type = data_type.strip().upper()
assert name
assert data_type in STRING_TYPES or data_type in NUMERIC_TYPES or data_type in DATE_TYPES
self.name = name
self.data_type = data_type
self.length = length
self.decimal = decimal
self.nullable = nullable
self.charset, self.collation = fix_charset_collation(charset, collation)
def __repr__(self):
return self.__str__()
def __str__(self):
nn = "" if self.nullable else "NOT NULL"
if self.decimal is not None:
return "{0} {1}({2},{3}) {4}".format(self.name, self.data_type, self.length, self.decimal, nn).strip()
elif self.data_type in DATE_TYPES or self.data_type in NUMERIC_TYPES:
return "{0} {1} {2}".format(self.name, self.data_type, nn).strip()
elif self.data_type in STRING_TYPES:
cs = "CHARACTER SET {0} COLLATION {1}".format(self.charset, self.collation) if self.charset else ""
return "{0} {1}({2}) {3} {4}".format(self.name, self.data_type, self.length, cs, nn).strip()
| {
"content_hash": "f46c42d4316cf2e01d0094e931ac9498",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 114,
"avg_line_length": 34.42857142857143,
"alnum_prop": 0.5887234561874543,
"repo_name": "frail/mysql-size-estimator",
"id": "11d51ce66d2d64bca35238a2556a5648331cc6b1",
"size": "4097",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mse/base.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "55159"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<link href="resources/flexbox.css" rel="stylesheet">
<style>
body {
margin: 0;
}
.flexbox {
background-color: #aaa;
position: relative;
}
.flexbox div {
border: 0;
}
.flexbox > :nth-child(1) {
background-color: blue;
}
.flexbox > :nth-child(2) {
background-color: green;
}
.flexbox > :nth-child(3) {
background-color: red;
}
.absolute {
position: absolute;
width: 50px;
height: 50px;
background-color: yellow !important;
}
</style>
<script src="../../resources/check-layout.js"></script>
<body onload="checkLayout('.flexbox')">
<div class="flexbox" style="width: 600px">
<div data-expected-height="100" class="flex-one" style="position: relative">
<div data-offset-x="0" data-offset-y="50" class="absolute" style="bottom:0;"></div>
</div>
<div data-expected-height="100" class="flex-one" style="height: 100px"></div>
<div data-expected-height="100" class="flex-one" style="position: relative">
<div data-offset-x="0" data-offset-y="50" class="absolute" style="bottom:0;"></div>
</div>
</div>
<div style="-webkit-writing-mode: vertical-rl">
<div class="flexbox" style="height: 200px">
<div data-expected-width="100" class="flex-one" style="position: relative">
<div data-offset-x="0" data-offset-y="0" class="absolute" style="left:0;"></div>
</div>
<div data-expected-width="100" class="flex-one" style="width: 100px"></div>
<div data-expected-width="100" class="flex-one" style="position: relative">
<div data-offset-x="0" data-offset-y="0" class="absolute" style="left:0;"></div>
</div>
</div>
</div>
<div style="-webkit-writing-mode: vertical-lr">
<div class="flexbox" style="height: 200px">
<div data-expected-width="100" class="flex-one" style="position: relative">
<div data-offset-x="50" data-offset-y="0" class="absolute" style="right:0;"></div>
</div>
<div data-expected-width="100" class="flex-one" style="width: 100px"></div>
<div data-expected-width="100" class="flex-one" style="position: relative">
<div data-offset-x="0" data-offset-y="0" class="absolute" style="left:0;"></div>
</div>
</div>
</div>
<div class="flexbox" style="height: 50px; width: 600px;">
<div data-expected-height="50" style="background-color: yellow; width: 300px">
<div data-expected-height="60" style="height: 60px; width: 10px; background-color: orange"></div>
</div>
</div>
<div class="flexbox column" style="width: 100px;">
<div data-expected-width="100" data-expected-height="50" style="background-color: yellow;">
<div data-expected-width="200" style="height: 50px; width: 200px; background-color: orange"></div>
</div>
</div>
</html>
| {
"content_hash": "2656c14eef09977353e6b5066937f8dd",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 102,
"avg_line_length": 32.876543209876544,
"alnum_prop": 0.6609087495306046,
"repo_name": "Bysmyyr/chromium-crosswalk",
"id": "9c1fe29954ac4ad578ed0f2ee7b190eb1f8c1dd4",
"size": "2663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third_party/WebKit/LayoutTests/css3/flexbox/flex-align-stretch.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php declare(strict_types = 1);
namespace Templado\Engine;
use DOMNode;
use DOMNodeList;
/**
* Iterating over a DOMNodeList in PHP does not work when the list
* changes during the iteration process. This Wrapper around NodeList
* takes a snapshot of the list first and then allows iterating over it.
*/
class SnapshotDOMNodelist {
/** @var DOMNode[] */
private $items = [];
/** @var int */
private $pos = 0;
public function __construct(DOMNodeList $list) {
$this->extractItemsFromNodeList($list);
}
public function hasNode(DOMNode $node): bool {
foreach ($this->items as $pos => $item) {
if ($item->isSameNode($node)) {
return true;
}
}
return false;
}
public function hasNext(): bool {
$count = \count($this->items);
return $count > 0 && $this->pos < $count;
}
public function getNext(): DOMNode {
$node = $this->current();
$this->pos++;
return $node;
}
public function removeNode(DOMNode $node): void {
/** @psalm-var int $pos */
foreach ($this->items as $pos => $item) {
if ($item->isSameNode($node)) {
\array_splice($this->items, $pos, 1);
if ($this->pos > 0 && $pos <= $this->pos) {
$this->pos--;
}
return;
}
}
throw new SnapshotDOMNodelistException('Node not found in list');
}
private function current(): DOMNode {
if (!$this->valid()) {
throw new SnapshotDOMNodelistException('No current node available');
}
return $this->items[$this->pos];
}
private function valid(): bool {
$count = \count($this->items);
return $count > 0 && $count > $this->pos;
}
private function extractItemsFromNodeList(DOMNodeList $list): void {
foreach ($list as $item) {
$this->items[] = $item;
}
}
}
| {
"content_hash": "0863b913ed1f72e58ccbcdf28e76335b",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 80,
"avg_line_length": 24.36144578313253,
"alnum_prop": 0.5346191889218596,
"repo_name": "templado/engine",
"id": "4717c20843cd35f3a45a7413412df787f2875d17",
"size": "2022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/viewmodel/SnapshotDOMNodelist.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "23081"
},
{
"name": "PHP",
"bytes": "181179"
}
],
"symlink_target": ""
} |
package com.google.android.exoplayer2.transformer;
import static com.google.android.exoplayer2.util.Assertions.checkArgument;
import static com.google.common.truth.Truth.assertThat;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.audio.AudioProcessor;
import com.google.android.exoplayer2.util.Util;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit tests for {@link SpeedChangingAudioProcessor}. */
@RunWith(AndroidJUnit4.class)
public class SpeedChangingAudioProcessorTest {
private static final AudioProcessor.AudioFormat AUDIO_FORMAT =
new AudioProcessor.AudioFormat(
/* sampleRate= */ 44100, /* channelCount= */ 2, /* encoding= */ C.ENCODING_PCM_16BIT);
@Test
public void queueInput_noSpeedChange_doesNotOverwriteInput() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {1});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
assertThat(inputBuffer).isEqualTo(getInputBuffer(/* frameCount= */ 5));
}
@Test
public void queueInput_speedChange_doesNotOverwriteInput() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
assertThat(inputBuffer).isEqualTo(getInputBuffer(/* frameCount= */ 5));
}
@Test
public void queueInput_noSpeedChange_copiesSamples() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {1});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer outputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
inputBuffer.rewind();
assertThat(outputBuffer).isEqualTo(inputBuffer);
}
@Test
public void queueInput_speedChange_modifiesSamples() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer outputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
inputBuffer.rewind();
assertThat(outputBuffer.hasRemaining()).isTrue();
assertThat(outputBuffer).isNotEqualTo(inputBuffer);
}
@Test
public void queueInput_noSpeedChangeAfterSpeedChange_copiesSamples() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5, 5}, /* speeds= */ new float[] {2, 1});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer outputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
inputBuffer.rewind();
assertThat(outputBuffer).isEqualTo(inputBuffer);
}
@Test
public void queueInput_speedChangeAfterNoSpeedChange_producesSameOutputAsSingleSpeedChange()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5, 5}, /* speeds= */ new float[] {1, 2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer outputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
speedChangingAudioProcessor = getConfiguredSpeedChangingAudioProcessor(speedProvider);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer expectedOutputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(outputBuffer.hasRemaining()).isTrue();
assertThat(outputBuffer).isEqualTo(expectedOutputBuffer);
}
@Test
public void queueInput_speedChangeAfterSpeedChange_producesSameOutputAsSingleSpeedChange()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5, 5}, /* speeds= */ new float[] {3, 2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer outputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
speedChangingAudioProcessor = getConfiguredSpeedChangingAudioProcessor(speedProvider);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer expectedOutputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(outputBuffer.hasRemaining()).isTrue();
assertThat(outputBuffer).isEqualTo(expectedOutputBuffer);
}
@Test
public void queueInput_speedChangeBeforeSpeedChange_producesSameOutputAsSingleSpeedChange()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5, 5}, /* speeds= */ new float[] {2, 3});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
ByteBuffer outputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
speedChangingAudioProcessor = getConfiguredSpeedChangingAudioProcessor(speedProvider);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
ByteBuffer expectedOutputBuffer = getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(outputBuffer.hasRemaining()).isTrue();
assertThat(outputBuffer).isEqualTo(expectedOutputBuffer);
}
@Test
public void queueInput_multipleSpeedsInBufferWithLimitAtFrameBoundary_readsDataUntilSpeedLimit()
throws Exception {
long speedChangeTimeUs = 4 * C.MICROS_PER_SECOND / AUDIO_FORMAT.sampleRate;
SpeedProvider speedProvider =
TestSpeedProvider.createWithStartTimes(
/* startTimesUs= */ new long[] {0L, speedChangeTimeUs},
/* speeds= */ new float[] {1, 2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
int inputBufferLimit = inputBuffer.limit();
speedChangingAudioProcessor.queueInput(inputBuffer);
assertThat(inputBuffer.position()).isEqualTo(4 * AUDIO_FORMAT.bytesPerFrame);
assertThat(inputBuffer.limit()).isEqualTo(inputBufferLimit);
}
@Test
public void queueInput_multipleSpeedsInBufferWithLimitInsideFrame_readsDataUntilSpeedLimit()
throws Exception {
long speedChangeTimeUs = (long) (3.5 * C.MICROS_PER_SECOND / AUDIO_FORMAT.sampleRate);
SpeedProvider speedProvider =
TestSpeedProvider.createWithStartTimes(
/* startTimesUs= */ new long[] {0L, speedChangeTimeUs},
/* speeds= */ new float[] {1, 2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
int inputBufferLimit = inputBuffer.limit();
speedChangingAudioProcessor.queueInput(inputBuffer);
assertThat(inputBuffer.position()).isEqualTo(4 * AUDIO_FORMAT.bytesPerFrame);
assertThat(inputBuffer.limit()).isEqualTo(inputBufferLimit);
}
@Test
public void queueEndOfStream_afterNoSpeedChangeAndWithOutputRetrieved_endsProcessor()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5, 5}, /* speeds= */ new float[] {2, 1});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(speedChangingAudioProcessor.isEnded()).isTrue();
}
@Test
public void queueEndOfStream_afterSpeedChangeAndWithOutputRetrieved_endsProcessor()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5, 5}, /* speeds= */ new float[] {1, 2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
inputBuffer.rewind();
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(speedChangingAudioProcessor.isEnded()).isTrue();
}
@Test
public void queueEndOfStream_afterNoSpeedChangeAndWithOutputNotRetrieved_doesNotEndProcessor()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {1});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
assertThat(speedChangingAudioProcessor.isEnded()).isFalse();
}
@Test
public void queueEndOfStream_afterSpeedChangeAndWithOutputNotRetrieved_doesNotEndProcessor()
throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
speedChangingAudioProcessor.queueEndOfStream();
assertThat(speedChangingAudioProcessor.isEnded()).isFalse();
}
@Test
public void queueEndOfStream_noInputQueued_endsProcessor() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
speedChangingAudioProcessor.queueEndOfStream();
assertThat(speedChangingAudioProcessor.isEnded()).isTrue();
}
@Test
public void isEnded_afterNoSpeedChangeAndOutputRetrieved_isFalse() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {1});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(speedChangingAudioProcessor.isEnded()).isFalse();
}
@Test
public void isEnded_afterSpeedChangeAndOutputRetrieved_isFalse() throws Exception {
SpeedProvider speedProvider =
TestSpeedProvider.createWithFrameCounts(
/* frameCounts= */ new int[] {5}, /* speeds= */ new float[] {2});
SpeedChangingAudioProcessor speedChangingAudioProcessor =
getConfiguredSpeedChangingAudioProcessor(speedProvider);
ByteBuffer inputBuffer = getInputBuffer(/* frameCount= */ 5);
speedChangingAudioProcessor.queueInput(inputBuffer);
getAudioProcessorOutput(speedChangingAudioProcessor);
assertThat(speedChangingAudioProcessor.isEnded()).isFalse();
}
private static SpeedChangingAudioProcessor getConfiguredSpeedChangingAudioProcessor(
SpeedProvider speedProvider) throws AudioProcessor.UnhandledAudioFormatException {
SpeedChangingAudioProcessor speedChangingAudioProcessor =
new SpeedChangingAudioProcessor(speedProvider);
speedChangingAudioProcessor.configure(AUDIO_FORMAT);
speedChangingAudioProcessor.flush();
return speedChangingAudioProcessor;
}
private static ByteBuffer getInputBuffer(int frameCount) {
int bufferSize = frameCount * AUDIO_FORMAT.bytesPerFrame;
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.nativeOrder());
for (int i = 0; i < bufferSize; i++) {
buffer.put((byte) (i % (Byte.MAX_VALUE + 1)));
}
buffer.rewind();
return buffer;
}
private static ByteBuffer getAudioProcessorOutput(AudioProcessor audioProcessor) {
ByteBuffer concatenatedOutputBuffers =
ByteBuffer.allocateDirect(0).order(ByteOrder.nativeOrder());
while (true) {
ByteBuffer outputBuffer = audioProcessor.getOutput();
if (!outputBuffer.hasRemaining()) {
break;
}
ByteBuffer temp =
ByteBuffer.allocateDirect(
concatenatedOutputBuffers.remaining() + outputBuffer.remaining())
.order(ByteOrder.nativeOrder());
temp.put(concatenatedOutputBuffers);
temp.put(outputBuffer);
temp.rewind();
concatenatedOutputBuffers = temp;
}
return concatenatedOutputBuffers;
}
private static final class TestSpeedProvider implements SpeedProvider {
private final long[] startTimesUs;
private final float[] speeds;
/**
* Creates a {@code TestSpeedProvider} instance.
*
* @param startTimesUs The speed change start times, in microseconds. The values must be
* distinct and in increasing order.
* @param speeds The speeds corresponding to each start time. Consecutive values must be
* distinct.
* @return A {@code TestSpeedProvider}.
*/
public static TestSpeedProvider createWithStartTimes(long[] startTimesUs, float[] speeds) {
return new TestSpeedProvider(startTimesUs, speeds);
}
/**
* Creates a {@code TestSpeedProvider} instance.
*
* @param frameCounts The frame counts for which the same speed should be applied.
* @param speeds The speeds corresponding to each frame count. The values must be distinct.
* @return A {@code TestSpeedProvider}.
*/
public static TestSpeedProvider createWithFrameCounts(int[] frameCounts, float[] speeds) {
long[] startTimesUs = new long[frameCounts.length];
int totalFrameCount = 0;
for (int i = 0; i < frameCounts.length; i++) {
startTimesUs[i] = totalFrameCount * C.MICROS_PER_SECOND / AUDIO_FORMAT.sampleRate;
totalFrameCount += frameCounts[i];
}
return new TestSpeedProvider(startTimesUs, speeds);
}
private TestSpeedProvider(long[] startTimesUs, float[] speeds) {
checkArgument(startTimesUs.length == speeds.length);
this.startTimesUs = startTimesUs;
this.speeds = speeds;
}
@Override
public float getSpeed(long timeUs) {
int index =
Util.binarySearchFloor(
startTimesUs, timeUs, /* inclusive= */ true, /* stayInBounds= */ true);
return speeds[index];
}
@Override
public long getNextSpeedChangeTimeUs(long timeUs) {
int index =
Util.binarySearchCeil(
startTimesUs, timeUs, /* inclusive= */ false, /* stayInBounds= */ false);
return index < startTimesUs.length ? startTimesUs[index] : C.TIME_UNSET;
}
}
}
| {
"content_hash": "8b9ea7a645e59f5d23f9a24a37f9ce98",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 98,
"avg_line_length": 42.169724770642205,
"alnum_prop": 0.7381703470031545,
"repo_name": "google/ExoPlayer",
"id": "4039906692536cf36b13107083bd717b7a18cc8f",
"size": "19001",
"binary": false,
"copies": "1",
"ref": "refs/heads/release-v2",
"path": "library/transformer/src/test/java/com/google/android/exoplayer2/transformer/SpeedChangingAudioProcessorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "112860"
},
{
"name": "CMake",
"bytes": "3728"
},
{
"name": "GLSL",
"bytes": "24937"
},
{
"name": "Java",
"bytes": "15604745"
},
{
"name": "Makefile",
"bytes": "11496"
},
{
"name": "Shell",
"bytes": "25523"
}
],
"symlink_target": ""
} |
package com.raizlabs.android.dbflow.test.structure;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.test.FlowTestCase;
import com.raizlabs.android.dbflow.test.TestDatabase;
/**
* Description:
*/
public class ModelAutoIncrementTest extends FlowTestCase {
public void testModelAutoIncrement() {
TestModelAI testModelAI = new TestModelAI();
testModelAI.name = "Test";
testModelAI.save(false);
assertTrue(testModelAI.exists());
testModelAI.delete(false);
assertTrue(!testModelAI.exists());
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
getContext().deleteDatabase(TestDatabase.NAME);
FlowManager.destroy();
}
@Override
protected void setUp() throws Exception {
super.setUp();
FlowManager.init(getContext());
}
}
| {
"content_hash": "1c15c25ef39c0767e76d567d6580af19",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 58,
"avg_line_length": 25.25,
"alnum_prop": 0.682068206820682,
"repo_name": "omegasoft7/DBFlow",
"id": "ff79e804abd19acce0927dc48ee0f376fc575b83",
"size": "909",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "library/src/androidTest/java/com/raizlabs/android/dbflow/test/structure/ModelAutoIncrementTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "528006"
}
],
"symlink_target": ""
} |
class ReferrersController < ApplicationController
def set_referrer
cookies[:reflink] = reflink
redirect_to root_path
end
private
def reflink
params[:code]
end
end
| {
"content_hash": "608673e3d05b2b0ba42bc700efdbd4c5",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 49,
"avg_line_length": 15.583333333333334,
"alnum_prop": 0.7165775401069518,
"repo_name": "smartvpnbiz/smartvpn-billing",
"id": "b022140413e308eaa85b47fc5f2179ebfc7a1dc5",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/referrers_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "15982"
},
{
"name": "CSS",
"bytes": "941874"
},
{
"name": "CoffeeScript",
"bytes": "1862"
},
{
"name": "HTML",
"bytes": "676002"
},
{
"name": "JavaScript",
"bytes": "2152021"
},
{
"name": "PHP",
"bytes": "2274"
},
{
"name": "Ruby",
"bytes": "820927"
},
{
"name": "Shell",
"bytes": "44281"
}
],
"symlink_target": ""
} |
struct ptrace_lwpinfo;
unsigned char* ptrace_get_xsave(int tid, size_t *len);
int ptrace_get_lwp_list(int pid, int *tids, size_t len);
int ptrace_get_num_lwps(int pid);
| {
"content_hash": "6f88e76b2d8aa2b9fc0bf12b0b303ef0",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 56,
"avg_line_length": 34,
"alnum_prop": 0.7294117647058823,
"repo_name": "alexbrainman/delve",
"id": "8d06d2d0c92afbd0dbfd9e7fbb0e1c2390527802",
"size": "191",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pkg/proc/native/ptrace_freebsd_amd64.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1855"
},
{
"name": "C",
"bytes": "75784"
},
{
"name": "Go",
"bytes": "1643068"
},
{
"name": "Makefile",
"bytes": "499"
},
{
"name": "Shell",
"bytes": "1910"
}
],
"symlink_target": ""
} |
<html>
<head></head>
<body>
An HTML page with mock X-Frame-Options headers which are misconfigured with
an invalid value (foo).
</body>
</html>
| {
"content_hash": "6d5d2a74bdd4e32ccd6bb0dd7d245849",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 79,
"avg_line_length": 22.571428571428573,
"alnum_prop": 0.6582278481012658,
"repo_name": "chromium/chromium",
"id": "077e6ea3892ee90b3520d0d6828359cda384a4a4",
"size": "158",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "chrome/test/data/extensions/webstore/xfo_header_misconfigured.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.asakusafw.compiler.bulkloader.testing.model;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import com.asakusafw.compiler.bulkloader.testing.io.Ex1Input;
import com.asakusafw.compiler.bulkloader.testing.io.Ex1Output;
import com.asakusafw.runtime.model.DataModel;
import com.asakusafw.runtime.model.DataModelKind;
import com.asakusafw.runtime.model.ModelInputLocation;
import com.asakusafw.runtime.model.ModelOutputLocation;
import com.asakusafw.runtime.model.PropertyOrder;
import com.asakusafw.runtime.value.IntOption;
import com.asakusafw.runtime.value.LongOption;
import com.asakusafw.runtime.value.StringOption;
import com.asakusafw.vocabulary.bulkloader.ColumnOrder;
import com.asakusafw.vocabulary.bulkloader.OriginalName;
import com.asakusafw.vocabulary.bulkloader.PrimaryKey;
/**
* ex1を表すデータモデルクラス。
*/
@ColumnOrder(value = {"SID", "VALUE", "STRING"})@DataModelKind("DMDL")@ModelInputLocation(Ex1Input.class)@
ModelOutputLocation(Ex1Output.class)@OriginalName(value = "EX1")@PrimaryKey(value = {"sid"})@PropertyOrder({
"sid", "value", "string"}) public class Ex1 implements DataModel<Ex1>, Writable {
private final LongOption sid = new LongOption();
private final IntOption value = new IntOption();
private final StringOption string = new StringOption();
@Override@SuppressWarnings("deprecation") public void reset() {
this.sid.setNull();
this.value.setNull();
this.string.setNull();
}
@Override@SuppressWarnings("deprecation") public void copyFrom(Ex1 other) {
this.sid.copyFrom(other.sid);
this.value.copyFrom(other.value);
this.string.copyFrom(other.string);
}
/**
* sidを返す。
* @return sid
* @throws NullPointerException sidの値が<code>null</code>である場合
*/
public long getSid() {
return this.sid.get();
}
/**
* sidを設定する。
* @param value0 設定する値
*/
@SuppressWarnings("deprecation") public void setSid(long value0) {
this.sid.modify(value0);
}
/**
* <code>null</code>を許すsidを返す。
* @return sid
*/
@OriginalName(value = "SID") public LongOption getSidOption() {
return this.sid;
}
/**
* sidを設定する。
* @param option 設定する値、<code>null</code>の場合にはこのプロパティが<code>null</code>を表すようになる
*/
@SuppressWarnings("deprecation") public void setSidOption(LongOption option) {
this.sid.copyFrom(option);
}
/**
* valueを返す。
* @return value
* @throws NullPointerException valueの値が<code>null</code>である場合
*/
public int getValue() {
return this.value.get();
}
/**
* valueを設定する。
* @param value0 設定する値
*/
@SuppressWarnings("deprecation") public void setValue(int value0) {
this.value.modify(value0);
}
/**
* <code>null</code>を許すvalueを返す。
* @return value
*/
@OriginalName(value = "VALUE") public IntOption getValueOption() {
return this.value;
}
/**
* valueを設定する。
* @param option 設定する値、<code>null</code>の場合にはこのプロパティが<code>null</code>を表すようになる
*/
@SuppressWarnings("deprecation") public void setValueOption(IntOption option) {
this.value.copyFrom(option);
}
/**
* stringを返す。
* @return string
* @throws NullPointerException stringの値が<code>null</code>である場合
*/
public Text getString() {
return this.string.get();
}
/**
* stringを設定する。
* @param value0 設定する値
*/
@SuppressWarnings("deprecation") public void setString(Text value0) {
this.string.modify(value0);
}
/**
* <code>null</code>を許すstringを返す。
* @return string
*/
@OriginalName(value = "STRING") public StringOption getStringOption() {
return this.string;
}
/**
* stringを設定する。
* @param option 設定する値、<code>null</code>の場合にはこのプロパティが<code>null</code>を表すようになる
*/
@SuppressWarnings("deprecation") public void setStringOption(StringOption option) {
this.string.copyFrom(option);
}
@Override public String toString() {
StringBuilder result = new StringBuilder();
result.append("{");
result.append("class=ex1");
result.append(", sid=");
result.append(this.sid);
result.append(", value=");
result.append(this.value);
result.append(", string=");
result.append(this.string);
result.append("}");
return result.toString();
}
@Override public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + sid.hashCode();
result = prime * result + value.hashCode();
result = prime * result + string.hashCode();
return result;
}
@Override public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(this.getClass()!= obj.getClass()) {
return false;
}
Ex1 other = (Ex1) obj;
if(this.sid.equals(other.sid)== false) {
return false;
}
if(this.value.equals(other.value)== false) {
return false;
}
if(this.string.equals(other.string)== false) {
return false;
}
return true;
}
/**
* stringを返す。
* @return string
* @throws NullPointerException stringの値が<code>null</code>である場合
*/
public String getStringAsString() {
return this.string.getAsString();
}
/**
* stringを設定する。
* @param string0 設定する値
*/
@SuppressWarnings("deprecation") public void setStringAsString(String string0) {
this.string.modify(string0);
}
@Override public void write(DataOutput out) throws IOException {
sid.write(out);
value.write(out);
string.write(out);
}
@Override public void readFields(DataInput in) throws IOException {
sid.readFields(in);
value.readFields(in);
string.readFields(in);
}
} | {
"content_hash": "0f61f690af29d4a94fdeeef769516fe5",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 116,
"avg_line_length": 31.218274111675125,
"alnum_prop": 0.6256910569105691,
"repo_name": "asakusafw/asakusafw-legacy",
"id": "c76bec6fa6018fe4e6c80fef74ab65422be20f8d",
"size": "7212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "thundergate-project/asakusa-thundergate-plugin/src/test/java/com/asakusafw/compiler/bulkloader/testing/model/Ex1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "67713"
},
{
"name": "Java",
"bytes": "4441131"
}
],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
public class BrownBear extends StdMOB
{
public String ID(){return "BrownBear";}
public BrownBear()
{
super();
Random randomizer = new Random(System.currentTimeMillis());
Username="a Brown Bear";
setDescription("A bear, large and husky with brown fur.");
setDisplayText("A brown bear hunts here.");
CMLib.factions().setAlignment(this,Faction.ALIGN_NEUTRAL);
setMoney(0);
baseEnvStats.setWeight(20 + Math.abs(randomizer.nextInt() % 45));
setWimpHitPoint(2);
baseEnvStats.setWeight(450 + Math.abs(randomizer.nextInt() % 55));
baseCharStats().setStat(CharStats.STAT_INTELLIGENCE,1);
baseCharStats().setStat(CharStats.STAT_STRENGTH,18);
baseCharStats().setStat(CharStats.STAT_DEXTERITY,16);
baseCharStats().setMyRace(CMClass.getRace("Bear"));
baseCharStats().getMyRace().startRacing(this,false);
baseEnvStats().setDamage(8);
baseEnvStats().setSpeed(2.0);
baseEnvStats().setAbility(0);
baseEnvStats().setLevel(5);
baseEnvStats().setArmor(60);
baseState.setHitPoints(CMLib.dice().roll(baseEnvStats().level(),20,baseEnvStats().level()));
recoverMaxState();
resetToMaxState();
recoverEnvStats();
recoverCharStats();
}
}
| {
"content_hash": "89a2cf0e59390e9536319934ff316e02",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 94,
"avg_line_length": 34.293103448275865,
"alnum_prop": 0.7300150829562594,
"repo_name": "robjcaskey/Unofficial-Coffee-Mud-Upstream",
"id": "681a7f3f406f2fc05508f2b0cd36564b5f26e1da",
"size": "2597",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/MOBS/BrownBear.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "21082141"
},
{
"name": "JavaScript",
"bytes": "16596"
},
{
"name": "Shell",
"bytes": "7865"
}
],
"symlink_target": ""
} |
module FbGraph
module Connections
module Posts
def posts(options = {})
posts = self.connection :posts, options
posts.map! do |post|
Post.new post[:id], post.merge(
:access_token => options[:access_token] || self.access_token
)
end
end
end
end
end | {
"content_hash": "67adb794d6fe6c1b36a9406e4aedca11",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 72,
"avg_line_length": 23.285714285714285,
"alnum_prop": 0.558282208588957,
"repo_name": "nov/fb_graph",
"id": "9afcb922bd537c670ad143bcc5bfd12a73026d64",
"size": "326",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "lib/fb_graph/connections/posts.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "439344"
}
],
"symlink_target": ""
} |
<h1><code ng:non-bindable="">changeTitleForm</code>
<div><span class="hint"></span>
</div>
</h1>
<div><h2 id="description">Description</h2>
<div class="description"><div class="changetitleform-page"><p>asd</p>
</div></div>
<h2 id="usage">Usage</h2>
<div class="usage"><pre class="prettyprint linenums">changeTitleForm();</pre>
</div>
</div>
| {
"content_hash": "f1f582bbf67e4825e28a1698c16ce6fc",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 77,
"avg_line_length": 31,
"alnum_prop": 0.6774193548387096,
"repo_name": "davidsonalencar/pagarme-challenge",
"id": "df9b9199d2d168f492d656753f6b288155500a43",
"size": "341",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/partials/api/changeTitleForm.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "667"
},
{
"name": "HTML",
"bytes": "28152"
},
{
"name": "JavaScript",
"bytes": "58338"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sr" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Tricoin</source>
<translation>О Tricoin-у</translation>
</message>
<message>
<location line="+39"/>
<source><b>Tricoin</b> version</source>
<translation><b>Tricoin</b> верзија</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Tricoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Адресар</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Кликните два пута да промените адресу и/или етикету</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Прави нову адресу</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копира изабрану адресу на системски клипборд</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Нова адреса</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Tricoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Ово су Ваше Tricoin адресе за примање уплата. Можете да сваком пошиљаоцу дате другачију адресу да би пратили ко је вршио уплате.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Prikaži &QR kod</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Tricoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Tricoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Избриши</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Tricoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Извоз података из адресара</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Зарезом одвојене вредности (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Грешка током извоза</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Није могуће писати у фајл %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Етикета</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адреса</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(без етикете)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Унесите лозинку</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Нова лозинка</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Поновите нову лозинку</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Унесите нову лозинку за приступ новчанику.<br/>Молимо Вас да лозинка буде <b>10 или више насумице одабраних знакова</b>, или <b>осам или више речи</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Шифровање новчаника</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ова акција захтева лозинку Вашег новчаника да би га откључала.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Откључавање новчаника</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ова акција захтева да унесете лозинку да би дешифловала новчаник.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Дешифровање новчаника</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Промена лозинке</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Унесите стару и нову лозинку за шифровање новчаника.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Одобрите шифровање новчаника</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ANONCOINS</b>!</source>
<translation>Упозорење: Ако се ваш новчаник шифрује а потом изгубите лозинкзу, ви ћете <b>ИЗГУБИТИ СВЕ ANONCOIN-Е</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Да ли сте сигурни да желите да се новчаник шифује?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Новчаник је шифрован</translation>
</message>
<message>
<location line="-56"/>
<source>Tricoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your tricoins from being stolen by malware infecting your computer.</source>
<translation>Tricoin će se sad zatvoriti da bi završio proces enkripcije. Zapamti da enkripcija tvog novčanika ne može u potpunosti da zaštiti tvoje tricoine da ne budu ukradeni od malawarea koji bi inficirao tvoj kompjuter.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Неуспело шифровање новчаника</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Настала је унутрашња грешка током шифровања новчаника. Ваш новчаник није шифрован.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Лозинке које сте унели се не подударају.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Неуспело откључавање новчаника</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Лозинка коју сте унели за откључавање новчаника је нетачна.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Неуспело дешифровање новчаника</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Лозинка за приступ новчанику је успешно промењена.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Синхронизација са мрежом у току...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Општи преглед</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Погледајте општи преглед новчаника</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Трансакције</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Претражите историјат трансакција</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Уредите запамћене адресе и њихове етикете</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Прегледајте листу адреса на којима прихватате уплате</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>I&zlaz</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Напустите програм</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Tricoin</source>
<translation>Прегледајте информације о Tricoin-у</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>О &Qt-у</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Прегледајте информације о Qt-у</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>П&оставке...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Шифровање новчаника...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup новчаника</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Промени &лозинку...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Tricoin address</source>
<translation>Пошаљите новац на tricoin адресу</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Tricoin</source>
<translation>Изаберите могућности tricoin-а</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Мењање лозинке којом се шифрује новчаник</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Tricoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>новчаник</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Tricoin</source>
<translation>&О Tricoin-у</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Tricoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Tricoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Фајл</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Подешавања</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>П&омоћ</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Трака са картицама</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Tricoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Tricoin network</source>
<translation><numerusform>%n активна веза са Tricoin мрежом</numerusform><numerusform>%n активне везе са Tricoin мрежом</numerusform><numerusform>%n активних веза са Tricoin мрежом</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ажурно</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ажурирање у току...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Послана трансакција</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Придошла трансакција</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1⏎ Iznos: %2⏎ Tip: %3⏎ Adresa: %4⏎</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Tricoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Новчаник јс <b>шифрован</b> и тренутно <b>откључан</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Новчаник јс <b>шифрован</b> и тренутно <b>закључан</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Tricoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Измени адресу</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Етикета</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Адреса</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Унешена адреса "%1" се већ налази у адресару.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Tricoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Немогуће откључати новчаник.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Tricoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>верзија</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Korišćenje:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Поставке</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Tricoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Tricoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Tricoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Tricoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Tricoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Јединица за приказивање износа:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Tricoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Tricoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Tricoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Непотврђено:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>новчаник</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Недавне трансакције</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start tricoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Zatraži isplatu</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Iznos:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>&Етикета</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Poruka:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Snimi kao...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Tricoin-Qt help message to get a list with possible Tricoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Tricoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Tricoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Tricoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Tricoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Слање новца</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Ukloni sva polja sa transakcijama</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Потврди акцију слања</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Пошаљи</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Да ли сте сигурни да желите да пошаљете %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>и</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Етикета</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Izaberite adresu iz adresara</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Tricoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Unesite Tricoin adresu (n.pr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Tricoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Tricoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Tricoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Unesite Tricoin adresu (n.pr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Tricoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Tricoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Otvorite do %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nepotvrdjeno</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 potvrde</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>етикета</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>iznos</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, nije još uvek uspešno emitovan</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nepoznato</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>detalji transakcije</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ovaj odeljak pokazuje detaljan opis transakcije</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>tip</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адреса</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>iznos</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Otvoreno do %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline * van mreže (%1 potvrdjenih)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nepotvrdjeno (%1 of %2 potvrdjenih)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Potvrdjena (%1 potvrdjenih)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ovaj blok nije primljen od ostalih čvorova (nodova) i verovatno neće biti prihvaćen!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generisan ali nije prihvaćen</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Primljen sa</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Primljeno od</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Poslat ka</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Isplata samom sebi</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minirano</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status vaše transakcije. Predjite mišem preko ovog polja da bi ste videli broj konfirmacija</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum i vreme primljene transakcije.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tip transakcije</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Destinacija i adresa transakcije</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Iznos odbijen ili dodat balansu.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Sve</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Danas</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>ove nedelje</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Ovog meseca</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Prošlog meseca</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Ove godine</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Opseg...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Primljen sa</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Poslat ka</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Vama - samom sebi</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minirano</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Drugi</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Navedite adresu ili naziv koji bi ste potražili</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min iznos</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>kopiraj adresu</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>kopiraj naziv</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>kopiraj iznos</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>promeni naziv</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Izvezi podatke o transakcijama</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Зарезом одвојене вредности (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Potvrdjen</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>tip</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Етикета</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Адреса</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>iznos</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Грешка током извоза</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Није могуће писати у фајл %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Opseg:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>do</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Слање новца</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Tricoin version</source>
<translation>Tricoin верзија</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Korišćenje:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or tricoind</source>
<translation>Pošalji naredbu na -server ili tricoinid
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Listaj komande</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Zatraži pomoć za komande</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opcije</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: tricoin.conf)</source>
<translation>Potvrdi željeni konfiguracioni fajl (podrazumevani:tricoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: tricoind.pid)</source>
<translation>Konkretizuj pid fajl (podrazumevani: tricoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Gde je konkretni data direktorijum </translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Slušaj konekcije na <port> (default: 9333 or testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Održavaj najviše <n> konekcija po priključku (default: 125)
</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Prihvati komandnu liniju i JSON-RPC komande</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Radi u pozadini kao daemon servis i prihvati komande</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Koristi testnu mrežu</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=tricoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Tricoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Tricoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Tricoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Tricoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Korisničko ime za JSON-RPC konekcije</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Lozinka za JSON-RPC konekcije</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Dozvoli JSON-RPC konekcije sa posebne IP adrese</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Pošalji komande to nodu koji radi na <ip> (default: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Odredi veličinu zaštićenih ključeva na <n> (default: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Ponovo skeniraj lanac blokova za nedostajuće transakcije iz novčanika</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Koristi OpenSSL (https) za JSON-RPC konekcije</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>privatni ključ za Server (podrazumevan: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Prihvatljive cifre (podrazumevano: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Ova poruka Pomoći</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>učitavam adrese....</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Tricoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Tricoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Učitavam blok indeksa...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Tricoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Новчаник се учитава...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Ponovo skeniram...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Završeno učitavanje</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | {
"content_hash": "f2ba032453dd69cc4c431e25369da45d",
"timestamp": "",
"source": "github",
"line_count": 2919,
"max_line_length": 395,
"avg_line_length": 34.64028776978417,
"alnum_prop": 0.5987835632695446,
"repo_name": "tricoin/tricoin",
"id": "dbb08569712c62b68fddbffc69ade15a0466ce6b",
"size": "103301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_sr.ts",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
◦ [FilteredRequest](FilteredRequest.md)
◦ [PaginatedRequest](PaginatedRequest.md)
◦ [RequestOptions](RequestOptions.md)
| {
"content_hash": "37e063dfaee7a633219623d083b58fe7",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 43,
"avg_line_length": 31.75,
"alnum_prop": 0.7559055118110236,
"repo_name": "auth0/auth0-PHP",
"id": "2dd984bc2b690e6aa019c7b4a2d1bb79f4dc87bb",
"size": "167",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/API/Utility/Request/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "890189"
}
],
"symlink_target": ""
} |
#import "cocos2d.h"
#import "Box2D.h"
#import "GLES-Render.h"
#import "GameObject.h"
#import "GameItem.h"
#import "GameDecoration.h"
#import "GameTank.h"
#import "GameStartCoordsManager.h"
#import "GameStartCoords.h"
/* sprite index aus menu_levels.png */
static const int LEVEL_FRAGTEMPLE_IMAGE_INDEX = 0;
static const int LEVEL_YERLETHALMETAL_IMAGE_INDEX = 1;
static const int LEVEL_HAUNTEDHALLS_IMAGE_INDEX = 2;
static const int LEVEL_OVERKILLZ_IMAGE_INDEX = 3;
@interface GameLevel : GameObject
{
b2Body *levBody;
b2EdgeShape levBox;
GameStartCoordsManager *startCoordsManager;
NSMutableArray *decorations;
NSMutableArray *items;
CGPoint lastLocation;
}
- (CGSize)getSize;
- (NSString *)getFilename;
- (void)createCollisionMap;
- (void)createItems;
- (void)registerItemWithCoords:(CGPoint)coords type:(GameItemType)aType;
- (void)registerPlayerStartCoords:(CGPoint)coords rotate:(float)rotate;
- (void)registerDecorationWithCoords:(CGPoint)coords type:(GameDecorationType)aType;
+ (NSString *)getLabel;
+ (int)menuImageIndex;
@property (assign) GameStartCoordsManager *startCoordsManager;
@end
| {
"content_hash": "e41dfa39fe919693f6d4af754c079d7a",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 84,
"avg_line_length": 26.488372093023255,
"alnum_prop": 0.7594381035996488,
"repo_name": "johndpope/FinalFighter-mac",
"id": "22eebed9c30d5294e7a37e378f8154a705e15d27",
"size": "1139",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "FinalFighter-mac/Source/GameLevel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "263643"
},
{
"name": "C++",
"bytes": "977718"
},
{
"name": "CMake",
"bytes": "6592"
},
{
"name": "Matlab",
"bytes": "1875"
},
{
"name": "Objective-C",
"bytes": "1466178"
},
{
"name": "Objective-C++",
"bytes": "162622"
},
{
"name": "PHP",
"bytes": "14077"
},
{
"name": "Shell",
"bytes": "764"
}
],
"symlink_target": ""
} |
set(costmap_2d_MSG_INCLUDE_DIRS "/home/trevor/ROS/catkin_ws/src/navigation/costmap_2d/msg")
set(costmap_2d_MSG_DEPENDENCIES std_msgs;geometry_msgs;map_msgs)
| {
"content_hash": "5bce42a0e3a7618f15963c05c7a65198",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 91,
"avg_line_length": 78.5,
"alnum_prop": 0.7961783439490446,
"repo_name": "siketh/ASR",
"id": "851360082a9d924e554990ddeddef4de662c6aa1",
"size": "222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "catkin_ws/devel/share/costmap_2d/cmake/costmap_2d-msg-paths.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "11935"
},
{
"name": "C++",
"bytes": "569516"
},
{
"name": "CMake",
"bytes": "1336057"
},
{
"name": "Common Lisp",
"bytes": "110778"
},
{
"name": "Makefile",
"bytes": "814522"
},
{
"name": "NewLisp",
"bytes": "23003"
},
{
"name": "Python",
"bytes": "309810"
},
{
"name": "Shell",
"bytes": "11688"
}
],
"symlink_target": ""
} |
/*jshint globalstrict:false, strict:false */
/* global assertEqual */
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Lars Maier
/// @author Copyright 2022, ArangoDB Inc, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
const jsunity = require('jsunity');
const _ = require('lodash');
const rh = require('@arangodb/testutils/restart-helper');
const {db, errors} = require('@arangodb');
const { getCtrlDBServers } = require('@arangodb/test-helper');
const retryWithExceptions = function (check) {
let i = 0, lastError = null;
while (true) {
try {
check();
break;
} catch (err) {
lastError = err;
}
i += 1;
if (i >= 100) {
throw Error("repeated error conditions: " + lastError);
}
require('internal').sleep(1);
}
};
const getSnapshotStatus = function (logId) {
const response = db._connection.GET(`/_api/replicated-state/${logId}/snapshot-status`);
if (response.code !== 200) {
throw new Error("Snapshot status returned invalid response code: " + response.code);
}
return response.result;
};
const disableMaintenanceMode = function () {
const response = db._connection.PUT("/_admin/cluster/maintenance", "\"off\"");
};
function testSuite() {
return {
tearDown: function () {
rh.restartAllServers();
},
testRestartDatabaseServers: function () {
disableMaintenanceMode();
const dbServers = getCtrlDBServers();
const servers = _.sampleSize(dbServers, 3);
const state = db._createPrototypeState({servers});
state.write({"foo": "bar"});
const sstatus = getSnapshotStatus(state.id());
rh.shutdownServers(dbServers);
rh.restartAllServers();
retryWithExceptions(function () {
assertEqual(state.read("foo"), "bar");
});
// we expect the snapshost status to be unchanged
assertEqual(sstatus, getSnapshotStatus(state.id()));
},
};
}
jsunity.run(testSuite);
return jsunity.done();
| {
"content_hash": "8eb9fbfdaa7e03588192b194ec289df6",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 89,
"avg_line_length": 29.97872340425532,
"alnum_prop": 0.627750177430802,
"repo_name": "wiltonlazary/arangodb",
"id": "182a291a99f61158f1255e986ee50bad042d3782",
"size": "2818",
"binary": false,
"copies": "2",
"ref": "refs/heads/devel",
"path": "tests/js/client/restart/test-restart-replication2-prototype-state-cluster-grey.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "61827"
},
{
"name": "C",
"bytes": "309788"
},
{
"name": "C++",
"bytes": "34723629"
},
{
"name": "CMake",
"bytes": "383904"
},
{
"name": "CSS",
"bytes": "210549"
},
{
"name": "EJS",
"bytes": "231166"
},
{
"name": "HTML",
"bytes": "23114"
},
{
"name": "JavaScript",
"bytes": "33741286"
},
{
"name": "LLVM",
"bytes": "14975"
},
{
"name": "NASL",
"bytes": "269512"
},
{
"name": "NSIS",
"bytes": "47138"
},
{
"name": "Pascal",
"bytes": "75391"
},
{
"name": "Perl",
"bytes": "9811"
},
{
"name": "PowerShell",
"bytes": "7869"
},
{
"name": "Python",
"bytes": "184352"
},
{
"name": "SCSS",
"bytes": "255542"
},
{
"name": "Shell",
"bytes": "134504"
},
{
"name": "TypeScript",
"bytes": "179074"
},
{
"name": "Yacc",
"bytes": "79620"
}
],
"symlink_target": ""
} |
package uk.co.littlemike.bitshadow.web.appinstances;
import uk.co.littlemike.bitshadow.appinstances.AppInstance;
import uk.co.littlemike.bitshadow.appinstances.RegisterAppInstance;
import uk.co.littlemike.bitshadow.apps.App;
import uk.co.littlemike.bitshadow.apps.AppUpdate;
import uk.co.littlemike.bitshadow.hosts.Host;
import uk.co.littlemike.bitshadow.hosts.HostUpdate;
import javax.validation.constraints.NotNull;
public class RegisterAppInstanceRepresentation implements RegisterAppInstance, AppUpdate, HostUpdate {
@NotNull
private String appName;
private String appDescription;
private String hostname;
public void setAppName(String appName) {
this.appName = appName;
}
public void setAppDescription(String appDescription) {
this.appDescription = appDescription;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
@Override
public String getAppName() {
return appName;
}
@Override
public String getHostname() {
return hostname;
}
@Override
public AppUpdate getAppUpdate() {
return this;
}
@Override
public HostUpdate getHostUpdate() {
return this;
}
@Override
public void applyTo(AppInstance appInstance) {
}
@Override
public void applyTo(App app) {
app.setDescription(appDescription);
}
@Override
public void applyTo(Host host) {
}
}
| {
"content_hash": "29e6549c7a3baa270344d5c0ba38c4df",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 102,
"avg_line_length": 23.629032258064516,
"alnum_prop": 0.7030716723549488,
"repo_name": "LittleMikeDev/bitshadow",
"id": "387435f96fc47b9f8e1009c19483bb3f8d6f5122",
"size": "1465",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bitshadow-web/src/main/java/uk/co/littlemike/bitshadow/web/appinstances/RegisterAppInstanceRepresentation.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "62061"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using System.Web.Mvc;
using Sdl.Web.Common;
using Sdl.Web.Common.Configuration;
using Sdl.Web.Common.Logging;
using Sdl.Web.Common.Models;
using Sdl.Web.Mvc.Configuration;
using Sdl.Web.Mvc.Html;
namespace Sdl.Web.Mvc.OutputCache
{
/// <summary>
/// Allows view rendering output caching using the Dxa caching mechanism. Any Entity Models that should not be cached
/// on the page can be annotated with the [DxaNoOutputCache] attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class DxaOutputCacheAttribute : ActionFilterAttribute
{
[Serializable]
private sealed class OutputCacheItem
{
public string ContentType { get; set; }
public Encoding ContentEncoding { get; set; }
public string Content { get; set; }
}
private static readonly object CacheKeyStack = new object();
private static readonly object DisablePageOutputCacheKey = new object();
private readonly bool _enabled;
private readonly bool _ignorePreview;
public DxaOutputCacheAttribute()
{
string setting = WebConfigurationManager.AppSettings["output-caching-enabled"];
_enabled = !string.IsNullOrEmpty(setting) && setting.Equals("true", StringComparison.InvariantCultureIgnoreCase);
// used to override our check for being in a preview session. if this property is found in the
// configuration we ignore preview sessions
setting = WebConfigurationManager.AppSettings["output-caching-in-preview"];
_ignorePreview = !string.IsNullOrEmpty(setting) && setting.Equals("true", StringComparison.InvariantCultureIgnoreCase);
}
public override void OnActionExecuting(ActionExecutingContext ctx)
{
if (!_enabled) return;
if(ctx.Controller.ViewData[DxaViewDataItems.DisableOutputCache] != null && (bool)ctx.Controller.ViewData[DxaViewDataItems.DisableOutputCache]) return;
if (IgnoreCaching(ctx.Controller))
{
return;
}
OutputCacheItem cachedOutput = null;
string cacheKey = CalcCacheKey(ctx);
PushCacheKey(ctx, cacheKey);
SiteConfiguration.CacheProvider.TryGet(cacheKey, CacheRegions.RenderedOutput, out cachedOutput);
if (cachedOutput != null)
{
ctx.Result = new ContentResult
{
Content = cachedOutput.Content,
ContentType = cachedOutput.ContentType,
ContentEncoding = cachedOutput.ContentEncoding
};
}
}
public override void OnResultExecuting(ResultExecutingContext ctx)
{
if (!_enabled) return;
if(ctx.Result is ContentResult) return;
if (IgnoreCaching(ctx.Controller))
{
SetDisablePageOutputCache(ctx, true);
}
string cacheKey = PopCacheKey(ctx);
if (cacheKey == null) return;
OutputCacheItem cachedOutput;
SiteConfiguration.CacheProvider.TryGet(cacheKey, CacheRegions.RenderedOutput, out cachedOutput);
if (cachedOutput == null)
{
StringWriter cachingWriter = new StringWriter((IFormatProvider) CultureInfo.InvariantCulture);
TextWriter originalWriter = ctx.HttpContext.Response.Output;
ViewModel model = ctx.Controller.ViewData.Model as ViewModel;
ctx.HttpContext.Response.Output = cachingWriter;
SetCallback(ctx, (viewModel, commitCache) =>
{
ctx.HttpContext.Response.Output = originalWriter;
string html = cachingWriter.ToString();
ctx.HttpContext.Response.Write(html);
if (!commitCache) return;
// since our model is cached we need to make sure we decorate the markup with XPM markup
// as this is done outside the child action normally on a non-cached entity.
// n.b. we should only do this if our text/html content
if (ctx.HttpContext.Response.ContentType.Equals("text/html"))
{
if (model != null && WebRequestContext.Localization.IsXpmEnabled)
{
html = Markup.TransformXpmMarkupAttributes(html);
}
html = Markup.DecorateMarkup(new MvcHtmlString(html), model).ToString();
}
OutputCacheItem cacheItem = new OutputCacheItem
{
Content = html,
ContentType = ctx.HttpContext.Response.ContentType,
ContentEncoding = ctx.HttpContext.Response.ContentEncoding
};
// we finally have a fully rendered model's html that we can cache to our region
SiteConfiguration.CacheProvider.Store(cacheKey, CacheRegions.RenderedOutput, cacheItem);
if(viewModel!=null) Log.Trace($"ViewModel={viewModel.MvcData} added to DxaOutputCache.");
});
}
}
public override void OnResultExecuted(ResultExecutedContext ctx)
{
if (!_enabled) return;
if (ctx.Result is ContentResult) return;
if (IgnoreCaching(ctx.Controller))
{
//var controller = GetTopLevelController(ctx);
//controller.TempData[DxaDisableOutputCache] = true;
SetDisablePageOutputCache(ctx, true);
}
if (ctx.Exception != null)
{
RemoveCallback(ctx);
return;
}
bool commitCache = ctx.IsChildAction || !DisablePageOutputCache(ctx);
ViewModel model = ctx.Controller.ViewData.Model as ViewModel;
if (ctx.IsChildAction)
{
// since we are dealing with a child action it's likely we are working with an entity model. if so we should
// check if the entity is marked for no output caching or returns volatile. in this case we tell our parent
// controller which would be the page controller not to perform output caching at the page level and instead
// we just switch over to entity level caching but not for this particular model.
if (model != null && (IgnoreCaching(model) || model.IsVolatile))
{
SetDisablePageOutputCache(ctx, true);
commitCache = false;
Log.Trace($"ViewModel={model.MvcData} is marked not to be added to DxaOutputCache.");
}
}
// we normally do not want view rendered output cached in preview but we can have the option to turn this off if set in the
// web.config (for debug/testing purposes)
commitCache = (_ignorePreview || !WebRequestContext.IsSessionPreview) && (!IgnoreCaching(ctx.Controller)) && commitCache;
Action<ViewModel,bool> callback = GetCallback(ctx);
if (callback == null) return;
RemoveCallback(ctx);
callback(model, commitCache);
}
private static string CalcCacheKey(ActionExecutingContext ctx)
{
var sb = new StringBuilder();
sb.Append($"{ctx.ActionDescriptor.UniqueId}-{ctx.HttpContext.Request.Url}-{ctx.HttpContext.Request.UserAgent}:{WebRequestContext.CacheKeySalt}");
foreach (var p in ctx.ActionParameters.Where(p => p.Value != null))
{
sb.Append($"{p.Key.GetHashCode()}:{p.Value.GetHashCode()}-");
}
return sb.ToString();
}
private static bool DisablePageOutputCache(ControllerContext ctx)
{
bool result = false;
if (ctx.HttpContext.Items.Contains(DisablePageOutputCacheKey))
{
result = (bool)ctx.HttpContext.Items[DisablePageOutputCacheKey];
}
return result;
}
private static void SetDisablePageOutputCache(ControllerContext ctx, bool disable)
{
ctx.HttpContext.Items[DisablePageOutputCacheKey] = disable;
}
private static string GetKey(ControllerContext ctx)
{
string key = "__dxa__";
if (ctx.IsChildAction) key += "c";
ViewModel model = ctx.Controller.ViewData.Model as ViewModel;
if (model == null) return key;
key += model.GetHashCode();
return key;
}
private static object GetCallbackKeyObject(ControllerContext ctx) => GetKey(ctx) + "__cb_";
private static void RemoveCallback(ControllerContext ctx) => ctx.HttpContext.Items.Remove(GetCallbackKeyObject(ctx));
private static Action<ViewModel,bool> GetCallback(ControllerContext ctx) => ctx.HttpContext.Items[GetCallbackKeyObject(ctx)] as Action<ViewModel,bool>;
private static void SetCallback(ControllerContext ctx, Action<ViewModel,bool> callback) => ctx.HttpContext.Items[GetCallbackKeyObject(ctx)] = (object)callback;
private static void PushCacheKey(ControllerContext ctx, string key)
{
Stack<string> stack = ctx.HttpContext.Items[CacheKeyStack] as Stack<string>;
if (stack == null)
{
stack = new Stack<string>();
ctx.HttpContext.Items[CacheKeyStack] = stack;
}
stack.Push(key);
}
private static string PopCacheKey(ControllerContext ctx)
{
Stack<string> stack = ctx.HttpContext.Items[CacheKeyStack] as Stack<string>;
if (stack == null || stack.Count == 0) return null;
return stack?.Pop();
}
private static bool IgnoreCaching(object obj) => Attribute.GetCustomAttribute(obj.GetType(), typeof (DxaNoOutputCacheAttribute)) != null;
}
}
| {
"content_hash": "ea338eea17103374098f4f605e674179",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 167,
"avg_line_length": 45.8646288209607,
"alnum_prop": 0.5984004570122822,
"repo_name": "sdl/dxa-web-application-dotnet",
"id": "6827c9663e5bb45999c46ffa84ed009ad66ef58f",
"size": "10505",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Sdl.Web.Mvc/OutputCache/DXAOutputCache.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "Batchfile",
"bytes": "204"
},
{
"name": "C#",
"bytes": "1003797"
},
{
"name": "HTML",
"bytes": "5093"
},
{
"name": "Smalltalk",
"bytes": "1986"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2013 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
<identity>
<version number="$Revision: 9750 $"/>
<generation date="$Date: 2014-02-20 23:52:44 -0600 (Thu, 20 Feb 2014) $"/>
<language type="ksb"/>
</identity>
<metadata>
<casingData>
<casingItem type="calendar_field">titlecase</casingItem>
<casingItem type="currencyName">lowercase</casingItem>
<casingItem type="day_format_except_narrow">titlecase</casingItem>
<casingItem type="day_standalone_except_narrow">titlecase</casingItem>
<casingItem type="era_abbr">titlecase</casingItem>
<casingItem type="era_name">titlecase</casingItem>
<casingItem type="era_narrow">titlecase</casingItem>
<casingItem type="language">titlecase</casingItem>
<casingItem type="month_format_except_narrow">titlecase</casingItem>
<casingItem type="month_narrow">titlecase</casingItem>
<casingItem type="month_standalone_except_narrow">titlecase</casingItem>
<casingItem type="quarter_abbreviated">titlecase</casingItem>
<casingItem type="quarter_format_wide">titlecase</casingItem>
<casingItem type="quarter_standalone_wide">titlecase</casingItem>
<casingItem type="relative">titlecase</casingItem>
<casingItem type="symbol">titlecase</casingItem>
<casingItem type="territory">titlecase</casingItem>
</casingData>
</metadata>
</ldml>
| {
"content_hash": "2dddb9490a01741ab44b3c3c8164a923",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 102,
"avg_line_length": 46.55882352941177,
"alnum_prop": 0.7353126974099811,
"repo_name": "reznikmm/matreshka",
"id": "48626433cf4ae3d4057a4e06b1ae87828f99ea97",
"size": "1584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/cldr/27.0.1/common/casing/ksb.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "77822094"
},
{
"name": "C",
"bytes": "50705"
},
{
"name": "CSS",
"bytes": "2253"
},
{
"name": "HTML",
"bytes": "780653"
},
{
"name": "JavaScript",
"bytes": "24113"
},
{
"name": "Lex",
"bytes": "117165"
},
{
"name": "Makefile",
"bytes": "27341"
},
{
"name": "Perl",
"bytes": "4796"
},
{
"name": "Python",
"bytes": "10482"
},
{
"name": "Roff",
"bytes": "13069"
},
{
"name": "Shell",
"bytes": "3034"
},
{
"name": "TeX",
"bytes": "116491"
},
{
"name": "XSLT",
"bytes": "6108"
},
{
"name": "Yacc",
"bytes": "96865"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Prototype</title>
<!-- Bootstrap -->
<link href="/Style/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1 style="padding:10px 20px;margin-top:20px;">MySQL TESTing</h1>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<div class="well">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active"><a href="">链接查询</a></li>
<li role="presentation"><a href="#">更新</a></li>
<li role="presentation"><a href="#">删除</a></li>
<li role="presentation"><a href="#">项目设置</a></li>
</ul>
</div>
</div>
<div class="col-md-10" >
<form method="post" action="Mysql/Mysqltest/select"><input type="submit" class="btn btn-default" value="selection"/></form>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/Style/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "c833289cca3d88c57f67d495ca55d323",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 133,
"avg_line_length": 41.53333333333333,
"alnum_prop": 0.5831995719636169,
"repo_name": "zalath/PHP_CI_trial",
"id": "25c6cca07319016b4cb85524ce2d1959d26703b2",
"size": "1947",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/templates/Mysql/Mysql.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "419"
},
{
"name": "CSS",
"bytes": "12194"
},
{
"name": "HTML",
"bytes": "5395441"
},
{
"name": "JavaScript",
"bytes": "51459"
},
{
"name": "PHP",
"bytes": "1729332"
}
],
"symlink_target": ""
} |
package com.haskforce.parsing.jsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.haskforce.parsing.srcExtsDatatypes.ExpTopType;
import com.haskforce.parsing.srcExtsDatatypes.GuardedAlt;
import com.haskforce.parsing.srcExtsDatatypes.SrcInfoSpan;
import com.haskforce.parsing.srcExtsDatatypes.StmtTopType;
import java.lang.reflect.Type;
/**
* Deserializes guarded alternatives.
*/
public class GuardedAltDeserializer implements JsonDeserializer<GuardedAlt> {
@Override
public GuardedAlt deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject objType = jsonElement.getAsJsonObject();
JsonArray stuff;
if ((stuff = objType.getAsJsonArray("GuardedAlt")) != null) {
GuardedAlt guardedAlt = new GuardedAlt();
guardedAlt.srcInfoSpan = jsonDeserializationContext.deserialize(stuff.get(0), SrcInfoSpan.class);
guardedAlt.stmts = jsonDeserializationContext.deserialize(stuff.get(1), StmtTopType[].class);
guardedAlt.exp = jsonDeserializationContext.deserialize(stuff.get(2), ExpTopType.class);
return guardedAlt;
}
throw new JsonParseException("Unexpected object type: " + objType.toString());
}
}
| {
"content_hash": "cc5448422296e85d4855e23528e3bdab",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 119,
"avg_line_length": 45.294117647058826,
"alnum_prop": 0.75,
"repo_name": "charleso/intellij-haskforce",
"id": "ec2132f0193a2d64d8bf5782657d77d87ad451a7",
"size": "1540",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/com/haskforce/parsing/jsonParser/GuardedAltDeserializer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "435"
},
{
"name": "Haskell",
"bytes": "109431"
},
{
"name": "Java",
"bytes": "1295286"
},
{
"name": "Lex",
"bytes": "44643"
},
{
"name": "Scala",
"bytes": "53347"
},
{
"name": "Shell",
"bytes": "585"
}
],
"symlink_target": ""
} |
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author Andy Clark
* @version $Id$
*/
public class DesignDoc {
//
// MAIN
//
public static void main(String argv[]) {
if (argv.length != 2) {
System.err.println("usage: DesignDoc xml_file zip_file");
System.exit(1);
}
Document document = readDesign(argv[0]);
if (document == null) {
System.err.println("error: Unable to read design.");
System.exit(1);
}
Element root = document.getDocumentElement();
if (root == null || !root.getNodeName().equals("design")) {
System.err.println("error: Design not found.");
System.exit(1);
}
DesignDoc design = new DesignDoc();
try {
design.generateDesign(argv[1], root);
}
catch (Exception e) {
System.err.println("error: Error building stubs.");
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
//
// Constants
//
public static final String GENERATOR_NAME = "DesignDoc";
private static final String GENERATION_TIMESTAMP = new java.util.Date().toString();
//
// Static data
//
private static DOMParser parser;
//
// Data
//
private IndentingWriter out;
private ZipOutputStream zip;
//
// Public static methods
//
// reading
public static Document readDesign(String systemId) {
if (parser == null) {
parser = new DOMParser();
try {
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}
catch (Exception e) {
throw new RuntimeException("unable to set parser features");
}
}
try {
parser.parse(systemId);
}
catch (Exception e) {
return null;
}
return parser.getDocument();
}
//
// Public methods
//
// generation
public void generateDesign(String filename, Element design) throws IOException {
/***
int index = filename.lastIndexOf('.');
String basename = index != -1 ? filename.substring(0, index) : filename;
zip = new ZipOutputStream(new FileOutputStream(basename+".zip"));
/***/
zip = new ZipOutputStream(new FileOutputStream(filename));
/***/
out = new IndentingWriter(new PrintWriter(zip, true));
Element child = getFirstChildElement(design);
while (child != null) {
if (child.getNodeName().equals("category")) {
generateCategory(child);
}
child = getNextSiblingElement(child);
}
zip.finish();
zip.close();
}
public void generateCategory(Element category) throws IOException {
Element child = getFirstChildElement(category);
while (child != null) {
String name = child.getNodeName();
if (name.equals("class")) {
generateClass(child);
}
else if (name.equals("interface")) {
generateInterface(child);
}
child = getNextSiblingElement(child);
}
}
public void generateClass(Element cls) throws IOException {
zip.putNextEntry(new ZipEntry(makeFilename(cls)));
printCopyright();
/***
printClassProlog(cls);
/***/
printObjectProlog(cls);
/***/
printClassHeader(cls);
out.indent();
printConstants(cls);
printFields(cls);
printConstructors(cls);
printMethods(cls, true);
printImplementedMethods(cls);
out.outdent();
printClassFooter(cls);
zip.closeEntry();
}
public void generateInterface(Element inter) throws IOException {
zip.putNextEntry(new ZipEntry(makeFilename(inter)));
printCopyright();
/***
printInterfaceProlog(inter);
/***/
printObjectProlog(inter);
/***/
printInterfaceHeader(inter);
out.indent();
printConstants(inter);
printMethods(inter, false);
out.outdent();
printInterfaceFooter(inter);
zip.closeEntry();
}
// print: general
public void printCopyright() {
out.println("/*");
out.println(" * The Apache Software License, Version 1.1");
out.println(" *");
out.println(" *");
out.println(" * Copyright (c) 1999,2000 The Apache Software Foundation. All rights ");
out.println(" * reserved.");
out.println(" *");
out.println(" * Redistribution and use in source and binary forms, with or without");
out.println(" * modification, are permitted provided that the following conditions");
out.println(" * are met:");
out.println(" *");
out.println(" * 1. Redistributions of source code must retain the above copyright");
out.println(" * notice, this list of conditions and the following disclaimer. ");
out.println(" *");
out.println(" * 2. Redistributions in binary form must reproduce the above copyright");
out.println(" * notice, this list of conditions and the following disclaimer in");
out.println(" * the documentation and/or other materials provided with the");
out.println(" * distribution.");
out.println(" *");
out.println(" * 3. The end-user documentation included with the redistribution,");
out.println(" * if any, must include the following acknowledgment: ");
out.println(" * \"This product includes software developed by the");
out.println(" * Apache Software Foundation (http://www.apache.org/).\"");
out.println(" * Alternately, this acknowledgment may appear in the software itself,");
out.println(" * if and wherever such third-party acknowledgments normally appear.");
out.println(" *");
out.println(" * 4. The names \"Xerces\" and \"Apache Software Foundation\" must");
out.println(" * not be used to endorse or promote products derived from this");
out.println(" * software without prior written permission. For written ");
out.println(" * permission, please contact [email protected].");
out.println(" *");
out.println(" * 5. Products derived from this software may not be called \"Apache\",");
out.println(" * nor may \"Apache\" appear in their name, without prior written");
out.println(" * permission of the Apache Software Foundation.");
out.println(" *");
out.println(" * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED");
out.println(" * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES");
out.println(" * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE");
out.println(" * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR");
out.println(" * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,");
out.println(" * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT");
out.println(" * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF");
out.println(" * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND");
out.println(" * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,");
out.println(" * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT");
out.println(" * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF");
out.println(" * SUCH DAMAGE.");
out.println(" * ====================================================================");
out.println(" *");
out.println(" * This software consists of voluntary contributions made by many");
out.println(" * individuals on behalf of the Apache Software Foundation and was");
out.println(" * originally based on software copyright (c) 1999, International");
out.println(" * Business Machines, Inc., http://www.apache.org. For more");
out.println(" * information on the Apache Software Foundation, please see");
out.println(" * <http://www.apache.org/>.");
out.println(" */");
out.println();
}
public void printObjectProlog(Element object) {
Element category = getParentNodeElement(object, "category");
String objectPackageName = "";
if (category != null) {
objectPackageName = category.getAttribute("package");
if (objectPackageName.length() > 0) {
out.print("package ");
out.print(objectPackageName);
out.print(';');
out.println();
out.println();
}
}
Vector references = new Vector();
collectImports(object, objectPackageName, references);
if (object.getNodeName().equals("class")) {
Element implementsElement = getFirstChildElement(object, "implements");
while (implementsElement != null) {
Element referenceElement = getLastChildElement(implementsElement, "reference");
String referenceIdref = referenceElement.getAttribute("idref");
Element interfaceElement = object.getOwnerDocument().getElementById(referenceIdref);
collectImports(interfaceElement, objectPackageName, references);
implementsElement = getNextSiblingElement(implementsElement, "implements");
}
int referenceCount = references.size();
if (referenceCount > 0) {
for (int i = 0; i < referenceCount; i++) {
out.print("import ");
out.print(String.valueOf(references.elementAt(i)));
out.print(';');
out.println();
}
out.println();
}
}
}
public void printObjectComment(Element object) {
out.println("/**");
Element note = getFirstChildElement(object, "note");
if (note != null) {
while (note != null) {
out.print(" * ");
out.println(getElementText(note));
note = getNextSiblingElement(note, "note");
if (note != null) {
out.println(" * <p>");
}
}
out.println();
}
out.print(" * @author Stubs generated by ");
out.print(GENERATOR_NAME);
out.print(" on ");
out.println(GENERATION_TIMESTAMP);
out.println(" * @version $Id$");
out.println(" */");
}
// print: constants
public void printConstants(Element object) {
Element constant = getFirstChildElement(object, "constant");
if (constant != null) {
out.println("//");
out.println("// Constants");
out.println("//");
out.println();
while (constant != null) {
printConstant(constant);
constant = getNextSiblingElement(constant, "constant");
}
}
}
public void printConstant(Element constant) {
printConstantComment(constant);
out.print(constant.getAttribute("visibility"));
out.print(" static final ");
String defaultValue = printType(out, getLastChildElement(constant));
out.print(' ');
out.print(constant.getAttribute("name"));
out.print(" = ");
out.print(defaultValue);
out.println(';');
out.println();
}
public void printConstantComment(Element constant) {
out.print("/** ");
out.print(constant.getAttribute("name"));
out.print(" */");
out.println();
}
// print: fields
public void printFields(Element object) {
Element field = getFirstChildElement(object, "field");
if (field != null) {
out.println("//");
out.println("// Data");
out.println("//");
out.println();
while (field != null) {
printField(field);
field = getNextSiblingElement(field, "field");
}
}
}
public void printField(Element field) {
printFieldComment(field);
out.print(field.getAttribute("visibility"));
out.print(' ');
printType(out, getLastChildElement(field));
out.print(' ');
out.print(field.getAttribute("name"));
out.println(';');
out.println();
}
public void printFieldComment(Element field) {
out.print("/** ");
out.print(field.getAttribute("name"));
out.print(" */");
out.println();
}
// print: constructors
public void printConstructors(Element cls) {
Element constructor = getFirstChildElement(cls, "constructor");
if (constructor != null) {
out.println("//");
out.println("// Constructors");
out.println("//");
out.println();
while (constructor != null) {
printConstructor(constructor);
constructor = getNextSiblingElement(constructor, "constructor");
}
}
}
public void printConstructor(Element constructor) {
printConstructorComment(constructor);
out.print(constructor.getAttribute("visibility"));
out.print(' ');
String name = getParentNodeElement(constructor, "class").getAttribute("name");
out.print(name);
out.print('(');
Element param = getFirstChildElement(constructor, "param");
while (param != null) {
printType(out, getLastChildElement(param));
out.print(' ');
out.print(param.getAttribute("name"));
param = getNextSiblingElement(param, "param");
if (param != null) {
out.print(", ");
}
}
out.print(')');
Element throwsElement = getFirstChildElement(constructor, "throws");
if (throwsElement != null) {
Element packageElement = getParentNodeElement(constructor, "category");
String packageName = packageElement != null ? packageElement.getAttribute("package") : "";
out.println();
out.indent();
out.print("throws ");
while (throwsElement != null) {
String throwsIdref = getFirstChildElement(throwsElement, "reference").getAttribute("idref");
Element throwsClass = constructor.getOwnerDocument().getElementById(throwsIdref);
String throwsClassName = throwsClass.getAttribute("name");
/***
Element throwsCategory = getParentNodeElement(throwsClass);
String throwsPackageName = throwsCategory != null ? throwsCategory.getAttribute("package") : "";
if (throwsPackageName.length() == 0) {
throwsPackageName = null;
}
if (packageName != null && throwsPackageName != null) {
if (!packageName.equals(throwsPackageName)) {
out.print(throwsPackageName);
out.print('.');
}
}
/***/
out.print(throwsClassName);
throwsElement = getNextSiblingElement(throwsElement, "throws");
if (throwsElement != null) {
out.print(", ");
}
}
out.outdent();
}
out.println(" {");
out.println('}');
out.println();
}
public void printMethodComment(Element method) {
out.println("/**");
Element note = getFirstChildElement(method, "note");
if (note == null) {
out.print(" * ");
out.print(method.getAttribute("name"));
out.println();
}
else {
while (note != null) {
out.print(" * ");
out.println(getElementText(note));
note = getNextSiblingElement(note, "note");
if (note != null) {
out.println(" * <p>");
}
}
}
Element param = getFirstChildElement(method, "param");
Element returns = getFirstChildElement(method, "returns");
if (param != null || returns != null) {
out.println(" * ");
}
if (param != null) {
while (param != null) {
printParamComment(param);
param = getNextSiblingElement(param, "param");
}
}
if (returns != null) {
if (getFirstChildElement(method, "param") != null) {
out.println(" * ");
}
printReturnsComment(returns);
}
out.println(" */");
}
// print: methods
public void printMethods(Element object, boolean body) {
Element method = getFirstChildElement(object, "method");
if (method != null) {
out.println("//");
out.println("// Methods");
out.println("//");
out.println();
while (method != null) {
printMethod(method, body);
method = getNextSiblingElement(method, "method");
}
}
}
public void printImplementedMethods(Element cls) {
Element implementsElement = getFirstChildElement(cls, "implements");
while (implementsElement != null) {
Element referenceElement = getLastChildElement(implementsElement, "reference");
String referenceIdref = referenceElement.getAttribute("idref");
Element interfaceElement = cls.getOwnerDocument().getElementById(referenceIdref);
Element method = getFirstChildElement(interfaceElement, "method");
if (method != null) {
out.println("//");
out.print("// ");
out.print(interfaceElement.getAttribute("name"));
out.println(" methods");
out.println("//");
out.println();
while (method != null) {
printMethod(method, true);
method = getNextSiblingElement(method, "method");
}
}
implementsElement = getNextSiblingElement(implementsElement, "implements");
}
}
public void printMethod(Element method, boolean body) {
printMethodComment(method);
out.print(method.getAttribute("visibility"));
out.print(' ');
Element returns = getFirstChildElement(method, "returns");
String defaultValue = null;
if (returns != null) {
defaultValue = printType(out, getLastChildElement(returns));
}
else {
out.print("void");
}
out.print(' ');
String name = method.getAttribute("name");
out.print(name);
out.print('(');
Element param = getFirstChildElement(method, "param");
while (param != null) {
printType(out, getLastChildElement(param));
out.print(' ');
out.print(param.getAttribute("name"));
param = getNextSiblingElement(param, "param");
if (param != null) {
out.print(", ");
}
}
out.print(')');
Element throwsElement = getFirstChildElement(method, "throws");
if (throwsElement != null) {
Element packageElement = getParentNodeElement(method, "category");
String packageName = packageElement != null ? packageElement.getAttribute("package") : "";
out.println();
out.indent();
out.print("throws ");
while (throwsElement != null) {
String throwsIdref = getFirstChildElement(throwsElement, "reference").getAttribute("idref");
Element throwsClass = method.getOwnerDocument().getElementById(throwsIdref);
String throwsClassName = throwsClass.getAttribute("name");
/***
Element throwsCategory = getParentNodeElement(throwsClass);
String throwsPackageName = throwsCategory != null ? throwsCategory.getAttribute("package") : "";
if (throwsPackageName.length() == 0) {
throwsPackageName = null;
}
if (packageName != null && throwsPackageName != null) {
if (!packageName.equals(throwsPackageName)) {
out.print(throwsPackageName);
out.print('.');
}
}
/***/
out.print(throwsClassName);
throwsElement = getNextSiblingElement(throwsElement, "throws");
if (throwsElement != null) {
out.print(", ");
}
}
out.outdent();
}
if (body) {
out.println(" {");
if (defaultValue != null) {
out.indent();
out.print("return ");
out.print(defaultValue);
out.println(';');
out.outdent();
}
out.print("} // ");
out.println(name);
}
else {
out.println(';');
}
out.println();
}
public void printConstructorComment(Element constructor) {
out.println("/**");
Element note = getFirstChildElement(constructor, "note");
if (note == null) {
out.print(" * ");
out.print(constructor.getAttribute("name"));
out.println();
}
else {
while (note != null) {
out.print(" * ");
out.println(getElementText(note));
note = getNextSiblingElement(note, "note");
if (note != null) {
out.println(" * <p>");
}
}
}
Element param = getFirstChildElement(constructor, "param");
if (param != null) {
out.println(" * ");
}
if (param != null) {
while (param != null) {
printParamComment(param);
param = getNextSiblingElement(param, "param");
}
}
out.println(" */");
}
public void printParamComment(Element param) {
out.print(" * @param ");
out.print(param.getAttribute("name"));
out.print(' ');
Element note = getFirstChildElement(param, "note");
while (note != null) {
out.print(getElementText(note));
note = getNextSiblingElement(note, "note");
if (note != null) {
out.println();
out.println("<p>");
out.print(" * ");
}
}
out.println();
}
public void printReturnsComment(Element returns) {
out.print(" * @return ");
Element note = getFirstChildElement(returns, "note");
while (note != null) {
out.print(getElementText(note));
note = getNextSiblingElement(returns, "note");
if (note != null) {
out.println();
out.println(" * <p>");
out.print(" * ");
}
}
out.println();
}
// print: class
/***
public void printClassProlog(Element cls) {
Element category = getParentNodeElement(cls, "category");
String classPackageName = "";
if (category != null) {
classPackageName = category.getAttribute("package");
if (classPackageName.length() > 0) {
out.print("package ");
out.print(classPackageName);
out.print(';');
out.println();
out.println();
}
}
Vector references = new Vector();
collectImports(cls, classPackageName, references);
Element implementsElement = getFirstChildElement(cls, "implements");
while (implementsElement != null) {
Element referenceElement = getLastChildElement(implementsElement, "reference");
String referenceIdref = referenceElement.getAttribute("idref");
Element interfaceElement = cls.getOwnerDocument().getElementById(referenceIdref);
collectImports(interfaceElement, classPackageName, references);
implementsElement = getNextSiblingElement(implementsElement, "implements");
}
int referenceCount = references.size();
if (referenceCount > 0) {
for (int i = 0; i < referenceCount; i++) {
out.print("import ");
out.print(String.valueOf(references.elementAt(i)));
out.print(';');
out.println();
}
out.println();
}
}
/***/
public void printClassHeader(Element cls) {
printObjectComment(cls);
out.print(cls.getAttribute("visibility"));
out.print(" class ");
out.print(cls.getAttribute("name"));
Element extendsElement = getFirstChildElement(cls, "extends");
Element implementsElement = getFirstChildElement(cls, "implements");
if (extendsElement != null || implementsElement != null) {
/***
Element category = getParentNodeElement(cls, "category");
String packageName = category != null ? category.getAttribute("package") : "";
if (packageName.length() == 0) {
packageName = null;
}
/***/
if (extendsElement != null) {
out.println();
out.indent();
out.print("extends ");
String extendsIdref = getFirstChildElement(extendsElement, "reference").getAttribute("idref");
Element extendsClass = cls.getOwnerDocument().getElementById(extendsIdref);
String extendsClassName = extendsClass.getAttribute("name");
/***
Element extendsCategory = getParentNodeElement(extendsClass);
String extendsPackageName = extendsCategory != null ? extendsCategory.getAttribute("package") : "";
if (extendsPackageName.length() == 0) {
extendsPackageName = null;
}
if (packageName != null && extendsPackageName != null) {
if (!packageName.equals(extendsPackageName)) {
out.print(extendsPackageName);
out.print('.');
}
}
/***/
out.print(extendsClassName);
out.outdent();
}
if (implementsElement != null) {
out.println();
out.indent();
out.print("implements ");
while (implementsElement != null) {
String implementsIdref = getFirstChildElement(implementsElement, "reference").getAttribute("idref");
Element implementsInterface = cls.getOwnerDocument().getElementById(implementsIdref);
String implementsInterfaceName = implementsInterface.getAttribute("name");
/***
Element implementsPackage = getParentNodeElement(implementsInterface, "category");
String implementsPackageName = implementsPackage != null ? implementsPackage.getAttribute("package") : "";
if (implementsPackageName.length() == 0) {
implementsPackageName = null;
}
if (packageName != null && implementsPackageName != null) {
if (!packageName.equals(implementsPackageName)) {
out.print(implementsPackageName);
out.print('.');
}
}
/***/
out.print(implementsInterfaceName);
implementsElement = getNextSiblingElement(implementsElement, "implements");
if (implementsElement != null) {
out.print(", ");
}
}
out.outdent();
}
}
out.println(" {");
out.println();
}
public void printClassFooter(Element cls) {
out.print("} // class ");
out.println(cls.getAttribute("name"));
}
// print: interface
/***
public void printInterfaceProlog(Element inter) {
Element category = getParentNodeElement(inter, "category");
if (category != null) {
String packageName = category.getAttribute("package");
if (packageName.length() > 0) {
out.print("package ");
out.print(packageName);
out.print(';');
out.println();
out.println();
}
}
// REVISIT: How about adding the imports here?
}
/***/
public void printInterfaceHeader(Element inter) {
printObjectComment(inter);
out.print(inter.getAttribute("visibility"));
out.print(" interface ");
out.print(inter.getAttribute("name"));
Element extendsElement = getFirstChildElement(inter, "extends");
if (extendsElement != null) {
out.println();
out.indent();
out.print("extends ");
String extendsIdref = getFirstChildElement(extendsElement, "reference").getAttribute("idref");
Element extendsClass = inter.getOwnerDocument().getElementById(extendsIdref);
String extendsClassName = extendsClass.getAttribute("name");
/***
Element extendsCategory = getParentNodeElement(extendsClass);
String extendsPackageName = extendsCategory != null ? extendsCategory.getAttribute("package") : "";
if (extendsPackageName.length() == 0) {
extendsPackageName = null;
}
Element category = getParentNodeElement(inter, "category");
String packageName = category != null ? category.getAttribute("package") : "";
if (packageName.length() == 0) {
packageName = null;
}
if (packageName != null && extendsPackageName != null) {
if (!packageName.equals(extendsPackageName)) {
out.print(extendsPackageName);
out.print('.');
}
}
/***/
out.print(extendsClassName);
out.outdent();
}
out.println(" {");
out.println();
}
public void printInterfaceFooter(Element inter) {
out.print("} // interface ");
out.println(inter.getAttribute("name"));
}
//
// Private static methods
//
// other
private void collectImports(Element object, String objectPackageName,
Vector references) {
Element place = getFirstChildElement(object);
while (place != null) {
if (place.getNodeName().equals("reference")) {
String idref = place.getAttribute("idref");
Element idrefElement = place.getOwnerDocument().getElementById(idref);
Element idrefCategoryElement = getParentNodeElement(idrefElement, "category");
String packageName = idrefCategoryElement.getAttribute("package");
if (packageName.length() > 0 && !packageName.equals(objectPackageName)) {
String reference = packageName + '.' + idrefElement.getAttribute("name");
if (!references.contains(reference)) {
int index = references.size();
while (index > 0) {
if (reference.compareTo((String)references.elementAt(index - 1)) >= 0) {
break;
}
index--;
}
references.insertElementAt(reference, index);
}
}
}
Element next = getFirstChildElement(place);
while (next == null) {
next = getNextSiblingElement(place);
if (next == null) {
place = getParentNodeElement(place);
if (place == object) {
break;
}
}
}
place = next;
}
}
// file name generation
private static String makeFilename(Element object) {
String name = object.getAttribute("name");
Element packageElement = getParentNodeElement(object, "category");
String packageName = packageElement != null ? packageElement.getAttribute("package") : "";
int packageNameLen = packageName.length();
StringBuffer path = new StringBuffer(packageNameLen+1+name.length()+5);
if (packageNameLen > 0) {
path.append(packageName.replace('.', '/'));
path.append('/');
}
path.append(name);
path.append(".java");
return path.toString();
}
// printing
private static String printType(IndentingWriter out, Element type) {
String name = type.getNodeName();
if (name.equals("array")) {
printType(out, getLastChildElement(type));
String dimensionString = type.getAttribute("dimension");
int dimension = Integer.parseInt(dimensionString);
for (int i = 0; i < dimension; i++) {
out.print("[]");
}
return "null";
}
if (name.equals("primitive")) {
String typeName = type.getAttribute("type");
out.print(typeName);
if (typeName.equals("long") || typeName.equals("int") || typeName.equals("short")) {
return "-1";
}
if (typeName.equals("char")) {
return "'\\uFFFE'"; // 0xFFFE == Not a character
}
if (typeName.equals("boolean")) {
return "false";
}
return "???";
}
if (name.equals("reference")) {
String idref = type.getAttribute("idref");
type = type.getOwnerDocument().getElementById(idref);
String typeName = type.getAttribute("name");
/***
String typePackageName = ((Element)type.getParentNode()).getAttribute("package");
if (typePackageName.length() == 0) {
typePackageName = null;
}
Element category = (Element)type.getParentNode();
while (!category.getNodeName().equals("category")) {
category = (Element)category.getParentNode();
}
String packageName = category.getAttribute("package");
if (packageName.length() == 0) {
packageName = null;
}
if (packageName != null && typePackageName != null) {
if (!packageName.equals(typePackageName)) {
out.print(typePackageName);
out.print('.');
}
}
/***/
out.print(typeName);
return "null";
}
if (name.equals("collection")) {
Element child = getFirstChildElement(type);
while (!child.getNodeName().equals("collector")) {
child = getNextSiblingElement(type);
}
printType(out, getLastChildElement(child));
return "null";
}
out.print("???");
return "???";
}
// dom utils
private static Element getParentNodeElement(Node node) {
Node parent = node.getParentNode();
while (parent != null) {
if (parent.getNodeType() == Node.ELEMENT_NODE) {
return (Element)parent;
}
parent = parent.getParentNode();
}
return null;
}
private static Element getParentNodeElement(Node node, String name) {
Node parent = node.getParentNode();
while (parent != null) {
if (parent.getNodeType() == Node.ELEMENT_NODE && parent.getNodeName().equals(name)) {
return (Element)parent;
}
parent = parent.getParentNode();
}
return null;
}
private static String getElementText(Element element) {
Node child = element.getFirstChild();
if (child != null) {
StringBuffer str = new StringBuffer();
while (child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
str.append(child.getNodeValue());
}
child = child.getNextSibling();
}
return str.toString();
}
return "";
}
private static Element getFirstChildElement(Node parent) {
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
return (Element)child;
}
child = child.getNextSibling();
}
return null;
}
private static Element getFirstChildElement(Node parent, String name) {
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(name)) {
return (Element)child;
}
child = child.getNextSibling();
}
return null;
}
private static Element getLastChildElement(Node parent) {
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
return (Element)child;
}
child = child.getPreviousSibling();
}
return null;
}
private static Element getLastChildElement(Node parent, String name) {
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(name)) {
return (Element)child;
}
child = child.getPreviousSibling();
}
return null;
}
private static Element getNextSiblingElement(Node node) {
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
return (Element)sibling;
}
sibling = sibling.getNextSibling();
}
return null;
}
private static Element getNextSiblingElement(Node node, String name) {
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE && sibling.getNodeName().equals(name)) {
return (Element)sibling;
}
sibling = sibling.getNextSibling();
}
return null;
}
private static Element getPreviousSiblingElement(Node node) {
Node sibling = node.getPreviousSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
return (Element)sibling;
}
sibling = sibling.getPreviousSibling();
}
return null;
}
private static Element getPreviousSiblingElement(Node node, String name) {
Node sibling = node.getPreviousSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE && sibling.getNodeName().equals(name)) {
return (Element)sibling;
}
sibling = sibling.getPreviousSibling();
}
return null;
}
//
// Classes
//
public static class IndentingWriter
extends FilterWriter {
//
// Data
//
private PrintWriter out;
private int space = 4;
private String spaceStr = " ";
private int level;
private boolean indent = true;
//
// Constructors
//
public IndentingWriter(PrintWriter out) {
super(out);
this.out = out;
}
//
// Public methods
//
public void indent() {
level++;
}
public void outdent() {
level--;
}
//
// PrintWriter methods
//
public void print(char ch) {
if (indent) { printIndent(); }
out.print(ch);
}
public void print(String s) {
if (indent) { printIndent(); }
out.print(s);
}
public void println(char ch) {
print(ch);
println();
}
public void println(String s) {
print(s);
println();
}
public void println() {
out.println();
indent = true;
}
//
// Private methods
//
private void printIndent() {
for (int i = 0; i < level; i++) {
out.print(spaceStr);
}
indent = false;
}
} // class IndentingWriter
} // class Design
| {
"content_hash": "bd70285c528ea38948cdec82f9e136a8",
"timestamp": "",
"source": "github",
"line_count": 1172,
"max_line_length": 126,
"avg_line_length": 36.2542662116041,
"alnum_prop": 0.52833607907743,
"repo_name": "ronsigal/xerces",
"id": "1c2b068a7d4287b17ec276a483198f50777829db",
"size": "43294",
"binary": false,
"copies": "6",
"ref": "refs/heads/jboss-2.11.0.SP",
"path": "design/src/DesignDoc.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2183"
},
{
"name": "CSS",
"bytes": "2394"
},
{
"name": "HTML",
"bytes": "291055"
},
{
"name": "Java",
"bytes": "9196447"
},
{
"name": "Shell",
"bytes": "2449"
},
{
"name": "XSLT",
"bytes": "23366"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Monogr. Discom. Bohem. (Prague) 382 (1934)
#### Original name
Vibrissea crenulata Velen.
### Remarks
null | {
"content_hash": "ca5d3f8293edebd9c737b16d7d5a7d49",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 42,
"avg_line_length": 13,
"alnum_prop": 0.7041420118343196,
"repo_name": "mdoering/backbone",
"id": "5c4292ff3ba28f4ffe6b68f8d5055bc33133ab19",
"size": "219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Vibrisseaceae/Vibrissea/Vibrissea crenulata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.hadoop.hive.metastore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.ql.log.PerfLogger;
import org.datanucleus.exceptions.NucleusException;
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class RetryingHMSHandler implements InvocationHandler {
private static final Logger LOG = LoggerFactory.getLogger(RetryingHMSHandler.class);
private static final String CLASS_NAME = RetryingHMSHandler.class.getName();
private static class Result {
private final Object result;
private final int numRetries;
public Result(Object result, int numRetries) {
this.result = result;
this.numRetries = numRetries;
}
}
private final IHMSHandler baseHandler;
private final MetaStoreInit.MetaStoreInitData metaStoreInitData =
new MetaStoreInit.MetaStoreInitData();
private final HiveConf origConf; // base configuration
private final Configuration activeConf; // active configuration
private RetryingHMSHandler(HiveConf hiveConf, IHMSHandler baseHandler, boolean local) throws MetaException {
this.origConf = hiveConf;
this.baseHandler = baseHandler;
if (local) {
baseHandler.setConf(hiveConf); // tests expect configuration changes applied directly to metastore
}
activeConf = baseHandler.getConf();
// This has to be called before initializing the instance of HMSHandler
// Using the hook on startup ensures that the hook always has priority
// over settings in *.xml. The thread local conf needs to be used because at this point
// it has already been initialized using hiveConf.
MetaStoreInit.updateConnectionURL(hiveConf, getActiveConf(), null, metaStoreInitData);
try {
//invoking init method of baseHandler this way since it adds the retry logic
//in case of transient failures in init method
invoke(baseHandler, baseHandler.getClass().getDeclaredMethod("init", (Class<?>[]) null),
null);
} catch (Throwable e) {
LOG.error("HMSHandler Fatal error: " + ExceptionUtils.getStackTrace(e));
MetaException me = new MetaException(e.getMessage());
me.initCause(e);
throw me;
}
}
public static IHMSHandler getProxy(HiveConf hiveConf, IHMSHandler baseHandler, boolean local)
throws MetaException {
RetryingHMSHandler handler = new RetryingHMSHandler(hiveConf, baseHandler, local);
return (IHMSHandler) Proxy.newProxyInstance(
RetryingHMSHandler.class.getClassLoader(),
new Class[] { IHMSHandler.class }, handler);
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
int retryCount = -1;
int threadId = HiveMetaStore.HMSHandler.get();
boolean error = true;
PerfLogger perfLogger = PerfLogger.getPerfLogger(origConf, false);
perfLogger.PerfLogBegin(CLASS_NAME, method.getName());
try {
Result result = invokeInternal(proxy, method, args);
retryCount = result.numRetries;
error = false;
return result.result;
} finally {
StringBuffer additionalInfo = new StringBuffer();
additionalInfo.append("threadId=").append(threadId).append(" retryCount=").append(retryCount)
.append(" error=").append(error);
perfLogger.PerfLogEnd(CLASS_NAME, method.getName(), additionalInfo.toString());
}
}
public Result invokeInternal(final Object proxy, final Method method, final Object[] args) throws Throwable {
boolean gotNewConnectUrl = false;
boolean reloadConf = HiveConf.getBoolVar(origConf,
HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF);
long retryInterval = HiveConf.getTimeVar(origConf,
HiveConf.ConfVars.HMSHANDLERINTERVAL, TimeUnit.MILLISECONDS);
int retryLimit = HiveConf.getIntVar(origConf,
HiveConf.ConfVars.HMSHANDLERATTEMPTS);
long timeout = HiveConf.getTimeVar(origConf,
HiveConf.ConfVars.METASTORE_CLIENT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
Deadline.registerIfNot(timeout);
if (reloadConf) {
MetaStoreInit.updateConnectionURL(origConf, getActiveConf(),
null, metaStoreInitData);
}
int retryCount = 0;
Throwable caughtException = null;
while (true) {
try {
if (reloadConf || gotNewConnectUrl) {
baseHandler.setConf(getActiveConf());
}
Object object = null;
boolean isStarted = Deadline.startTimer(method.getName());
try {
object = method.invoke(baseHandler, args);
} finally {
if (isStarted) {
Deadline.stopTimer();
}
}
return new Result(object, retryCount);
} catch (javax.jdo.JDOException e) {
caughtException = e;
} catch (UndeclaredThrowableException e) {
if (e.getCause() != null) {
if (e.getCause() instanceof javax.jdo.JDOException) {
// Due to reflection, the jdo exception is wrapped in
// invocationTargetException
caughtException = e.getCause();
} else if (e.getCause() instanceof MetaException && e.getCause().getCause() != null
&& e.getCause().getCause() instanceof javax.jdo.JDOException) {
// The JDOException may be wrapped further in a MetaException
caughtException = e.getCause().getCause();
} else {
LOG.error(ExceptionUtils.getStackTrace(e.getCause()));
throw e.getCause();
}
} else {
LOG.error(ExceptionUtils.getStackTrace(e));
throw e;
}
} catch (InvocationTargetException e) {
if (e.getCause() instanceof javax.jdo.JDOException) {
// Due to reflection, the jdo exception is wrapped in
// invocationTargetException
caughtException = e.getCause();
} else if (e.getCause() instanceof NoSuchObjectException || e.getTargetException().getCause() instanceof NoSuchObjectException) {
String methodName = method.getName();
if (!methodName.startsWith("get_database") && !methodName.startsWith("get_table")
&& !methodName.startsWith("get_partition") && !methodName.startsWith("get_function")) {
LOG.error(ExceptionUtils.getStackTrace(e.getCause()));
}
throw e.getCause();
} else if (e.getCause() instanceof MetaException && e.getCause().getCause() != null) {
if (e.getCause().getCause() instanceof javax.jdo.JDOException ||
e.getCause().getCause() instanceof NucleusException) {
// The JDOException or the Nucleus Exception may be wrapped further in a MetaException
caughtException = e.getCause().getCause();
} else if (e.getCause().getCause() instanceof DeadlineException) {
// The Deadline Exception needs no retry and be thrown immediately.
Deadline.clear();
LOG.error("Error happens in method " + method.getName() + ": " +
ExceptionUtils.getStackTrace(e.getCause()));
throw e.getCause();
} else {
LOG.error(ExceptionUtils.getStackTrace(e.getCause()));
throw e.getCause();
}
} else {
LOG.error(ExceptionUtils.getStackTrace(e.getCause()));
throw e.getCause();
}
}
if (retryCount >= retryLimit) {
LOG.error("HMSHandler Fatal error: " + ExceptionUtils.getStackTrace(caughtException));
MetaException me = new MetaException(caughtException.getMessage());
me.initCause(caughtException);
throw me;
}
assert (retryInterval >= 0);
retryCount++;
LOG.error(
String.format(
"Retrying HMSHandler after %d ms (attempt %d of %d)", retryInterval, retryCount, retryLimit) +
" with error: " + ExceptionUtils.getStackTrace(caughtException));
Thread.sleep(retryInterval);
// If we have a connection error, the JDO connection URL hook might
// provide us with a new URL to access the datastore.
String lastUrl = MetaStoreInit.getConnectionURL(getActiveConf());
gotNewConnectUrl = MetaStoreInit.updateConnectionURL(origConf, getActiveConf(),
lastUrl, metaStoreInitData);
}
}
public Configuration getActiveConf() {
return activeConf;
}
}
| {
"content_hash": "ece3bea9b99e9b93e94db91cad8a2c4a",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 137,
"avg_line_length": 41.178082191780824,
"alnum_prop": 0.6831891772011532,
"repo_name": "vergilchiu/hive",
"id": "f19ff6c312a9f4bc8fd436e2ae29cd523ee0fe3b",
"size": "9824",
"binary": false,
"copies": "1",
"ref": "refs/heads/branch-2.3-htdc",
"path": "metastore/src/java/org/apache/hadoop/hive/metastore/RetryingHMSHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "54494"
},
{
"name": "Batchfile",
"bytes": "845"
},
{
"name": "C",
"bytes": "28218"
},
{
"name": "C++",
"bytes": "76808"
},
{
"name": "CSS",
"bytes": "4263"
},
{
"name": "GAP",
"bytes": "155326"
},
{
"name": "HTML",
"bytes": "50822"
},
{
"name": "Java",
"bytes": "39751326"
},
{
"name": "JavaScript",
"bytes": "25851"
},
{
"name": "M4",
"bytes": "2276"
},
{
"name": "PHP",
"bytes": "148097"
},
{
"name": "PLSQL",
"bytes": "8797"
},
{
"name": "PLpgSQL",
"bytes": "339745"
},
{
"name": "Perl",
"bytes": "319842"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Protocol Buffer",
"bytes": "8769"
},
{
"name": "Python",
"bytes": "386664"
},
{
"name": "Roff",
"bytes": "5379"
},
{
"name": "SQLPL",
"bytes": "20290"
},
{
"name": "Shell",
"bytes": "313510"
},
{
"name": "Thrift",
"bytes": "107584"
},
{
"name": "XSLT",
"bytes": "7619"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_74a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-74a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
using namespace std;
namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_74
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(map<int, int64_t *> dataMap);
void bad()
{
int64_t * data;
map<int, int64_t *> dataMap;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int64_t *)malloc(100*sizeof(int64_t));
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
badSink(dataMap);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, int64_t *> dataMap);
static void goodG2B()
{
int64_t * data;
map<int, int64_t *> dataMap;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new */
data = new int64_t;
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodG2BSink(dataMap);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(map<int, int64_t *> dataMap);
static void goodB2G()
{
int64_t * data;
map<int, int64_t *> dataMap;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int64_t *)malloc(100*sizeof(int64_t));
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodB2GSink(dataMap);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_74; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "2e83a31c3199f484bd7f17554c8a1afb",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 132,
"avg_line_length": 26.388429752066116,
"alnum_prop": 0.643282179768243,
"repo_name": "maurer/tiamat",
"id": "ecdc8f886b14dd494bd54ae5d905f59a4d6ff3ad",
"size": "3193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_74a.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace Hummelflug\Result\Storage\Factory;
use Hummelflug\Result\Storage\StorageInterface;
/**
* Class StorageFactory
* @package Hummelflug\Result\Storage\Factory
*/
class StorageFactory
{
/**
* @param array $options
*
* @return StorageInterface
*/
public static function create(array $options)
{
$storage = new $options['type'];
foreach ($options as $key => $value) {
switch ($key) {
case 'type';
break;
default:
$method = 'set' . ucfirst($key);
if (method_exists($storage, $method)) {
$storage->$method($value);
}
}
}
return $storage;
}
} | {
"content_hash": "4d171ab08b4c748c913315cca62179ae",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 59,
"avg_line_length": 21.216216216216218,
"alnum_prop": 0.4929936305732484,
"repo_name": "scheddel/hummelflug",
"id": "c872b986aa6c83740549497d38fbce3201253112",
"size": "785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Hummelflug/Result/Storage/Factory/StorageFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "768970"
}
],
"symlink_target": ""
} |
<h3>Add some possible useful attributes</h3>
Choose the attributes you want to add to your mailinglist system: | {
"content_hash": "c53927ad1819a18c2a2c52014f1ff283",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 65,
"avg_line_length": 55,
"alnum_prop": 0.8090909090909091,
"repo_name": "jeromio/motr",
"id": "debc6619c9f9a0581677b74300c9a3654de681ed",
"size": "110",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "list_v3.02/admin/info/en/defaults.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "6368"
},
{
"name": "Assembly",
"bytes": "1137778"
},
{
"name": "Batchfile",
"bytes": "66"
},
{
"name": "C",
"bytes": "128361"
},
{
"name": "C++",
"bytes": "46792"
},
{
"name": "CSS",
"bytes": "3191179"
},
{
"name": "ColdFusion",
"bytes": "7942"
},
{
"name": "Groff",
"bytes": "155107"
},
{
"name": "HTML",
"bytes": "20588643"
},
{
"name": "JavaScript",
"bytes": "6870285"
},
{
"name": "PHP",
"bytes": "36508700"
},
{
"name": "PLpgSQL",
"bytes": "17239"
},
{
"name": "Perl",
"bytes": "5806"
},
{
"name": "Shell",
"bytes": "9822"
}
],
"symlink_target": ""
} |
# HashMark
[](https://travis-ci.org/keithamus/hashmark)
<a target='_blank' rel='nofollow' href='https://app.codesponsor.io/link/ygkcNhfZ9nTDeVM6P8LSGn1C/keithamus/hashmark'> <img alt='Sponsor' width='888' height='68' src='https://app.codesponsor.io/embed/ygkcNhfZ9nTDeVM6P8LSGn1C/keithamus/hashmark.svg' /></a>
HashMark is a small utility which takes a file (or sdtin) as input, and writes
the contents of the input to a file named with a hash digest of the file. This
is useful for cache busting sticky caches - files can have far future expires
headers and when the code changes, a new filename is created.
## Examples:
### Shell
```bash
cat file.js | ./bin/hashmark 'file.{hash}.js' # Writes to test.3eae1599bb7f187b86d6427942d172ba8dd7ee5962aab03e0839ad9d59c37eb0.js
> Computed hash: 3eae1599bb7f187b86d6427942d172ba8dd7ee5962aab03e0839ad9d59c37eb0
>
cat file.js | ./bin/hashmark -l 8 'file.{hash}.js' # Writes to test.3eae1599.js
> Computed hash: 3eae1599
>
cat file.js | ./bin/hashmark -l 4 -d md5 'dist/{hash}.js' # Writes to dist/cbd8.js
> Computed hash: cbd8
>
```
It is useful to use globs — meaning you can read in many files and it will output
hashed versions of each:
```bash
./bin/hashmark path/to/*.js 'dist/{name}.{hash}.js'
./bin/hashmark path/to/{filea,fileb,filec}.js 'dist/{name}.{hash}.js'
./bin/hashmark **/*.js 'dist/{dir}/{name}.{hash}.js'
./bin/hashmark **/*.{js,css} 'dist/{dir}/{name}.{hash}{ext}'
./bin/hashmark **/*.{js,css} 'dist/{dir}/{hash}-{base}'
```
The above even works in shells that do not support globs (such as cmd.exe on
Windows), because `hashmark` has support for expanding globs itself. Note that
if your shell supports the `*` glob but not the `**` glob (such as bash before
version 4), the shell will interpret `**` as two `*` in a row, which means that
hashmark never receives the `**` and therefore cannot expand it. In that case
you need to quote your argument. Therefore, if you want to write cross-platform
scripts it is best to always quote the args:
Available pattern keys includes all the keys returned by [`path.parse(filename)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) and `hash` (ie: `hash`, `root`, `dir`, `name`, `base`, `ext`).
```bash
./bin/hashmark 'dir/**/*.{js,css}' 'test/*.js' 'dist/{dir}/{name}.{hash}{ext}'
```
The `hashmark` command will output some JSON to stdout with a map of filenames
and their new hashes, meaning you can pipe the hash to other programs. To make
`hashmark` completely silent - simply pass the `--silent` or `-s` flag.
```bash
./bin/hashmark -l 4 file.js 'dist/{hash}.js' --silent
```
You can also output the JSON map to a file, by passing the `--asset-map` or `-m`
flag. It will still be logged to stdout unless you pass `--silent`
```bash
./bin/hashmark -l 4 file.js 'dist/{hash}.js' --asset-map assets.json
```
You can specify from which directory to work from with `--cwd` or `-c`. _Note:_ `asset-map` will be relative to this directory.
```bash
mkdir dist/subdir
echo 'abracadabra' > dist/subdir/file.js
./bin/hashmark --cwd dist -d md5 -l 8 '**/*.js' '{dir}/{name}-{hash}{ext}'
> {"subdir/file.js":"subdir/file-97640ef5.js"}
```
### Integrations
**[replaceinfiles](https://github.com/songkick/replaceinfiles)**
Now that your assets have been renamed, you might want to update references to them in some other files _(ex:background image reference in your css files)_. That's exactly what `replaceinfiles` is made for. Just pipe it to `hashmark`. _It just work™._ [Full example](https://github.com/songkick/replaceinfiles/tree/master/examples/hashmark).
### Programmatically
The hashmark function can be used programmatically. You can pass it a String,
Buffer or Stream as the first argument, an options object as the second
argument, and a callback as the third.
The callback receives an error as the first argument (or null) and an object
which maps each given file to the newly hashed file name.
```js
var hashmark = require('hashmark');
var file = fs.createReadStream('file.js');
hashmark(file, { length: 8, digest: 'md5', 'pattern': '{hash}'}, function (err, map) {
console.log(map);
});
```
The function also returns an event emitter which emits `error`, `file` and `end`
events. File events get fired when an individual file has been hashed, and the
`end` event is fired when all have been done. `file` is given two arguments -
the files old name, and the new calculated filename (given the template string),
and the `end` event is given an object mapping of all files.
```js
var hashmark = require('hashmark');
var file = fs.createReadStream('file.js');
hashmark(file, { length: 8, digest: 'md5', pattern: 'hash'})
.on('file', function (oldFileName, newFileName) {
console.log('File hashed!', oldFileName, newFileName);
})
.on('end', function (jsonMap) {
console.log('~FIN');
})
```
Files can be a single Stream, or filename String, or an Array of Streams and/or
filename Strings.
```js
var hashmark = require('hashmark');
var file = fs.createReadStream('file.js');
hashmark([file, 'file2.js'], { length: 8, digest: 'md5', file: 'file.#.js'}, function (err, hash) {
console.log('File written to file.' + hash + '.js');
console.log(hash);
});
```
## Contributing
This is such a small utility - there's very little point in contributing. If it
doesn't do something that you really think it should, feel free to raise an
issue - just be aware I might say no. If you can make it faster/better/stronger
without changing the API/functionality then send a PR!
| {
"content_hash": "db50ce1f9f04078845bbfebba317241d",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 341,
"avg_line_length": 40.69565217391305,
"alnum_prop": 0.7127849002849003,
"repo_name": "keithamus/hashmark",
"id": "677a5d4dce3ce582a4d54b09e1040f7666df294e",
"size": "5620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6659"
}
],
"symlink_target": ""
} |
import json
import httpretty
import pytest
import pypuppetdb
def stub_request(url, data=None, method=httpretty.GET, status=200, **kwargs):
if data is None:
body = '[]'
else:
with open(data, 'r') as d:
body = json.load(d.read())
return httpretty.register_uri(method, url, body=body, status=status,
**kwargs)
@pytest.fixture(params=['string', 'QueryBuilder'])
def query(request):
key = 'certname'
value = 'node1'
if request.param == 'string':
return '["{0}", "=", "{1}"]'.format(key, value)
elif request.param == 'QueryBuilder':
return pypuppetdb.QueryBuilder.EqualsOperator(key, value)
class TestQueryAPI(object):
def test_facts(self, api):
facts_body = [{
'certname': 'test_certname',
'name': 'test_name',
'value': 'test_value',
'environment': 'test_environment',
}]
facts_url = 'http://localhost:8080/pdb/query/v4/facts'
httpretty.enable()
httpretty.register_uri(httpretty.GET, facts_url,
body=json.dumps(facts_body))
for fact in api.facts():
pass
assert httpretty.last_request().path == '/pdb/query/v4/facts'
httpretty.disable()
httpretty.reset()
def test_fact_names(self, api):
httpretty.enable()
stub_request('http://localhost:8080/pdb/query/v4/fact-names')
api.fact_names()
assert httpretty.last_request().path == '/pdb/query/v4/fact-names'
httpretty.disable()
httpretty.reset()
def test_normalize_resource_type(self, api):
assert api._normalize_resource_type('sysctl::value') == \
'Sysctl::Value'
assert api._normalize_resource_type('user') == 'User'
def test_environments(self, api):
httpretty.enable()
stub_request('http://localhost:8080/pdb/query/v4/environments')
api.environments()
assert httpretty.last_request().path == '/pdb/query/v4/environments'
httpretty.disable()
httpretty.reset()
def test_inventory(self, api):
inventory_body = [{
'certname': 'test_certname',
'timestamp': '2017-06-05T20:18:23.374Z',
'environment': 'test_environment',
'facts': 'test_facts',
'trusted': 'test_trusted'
}]
inventory_url = 'http://localhost:8080/pdb/query/v4/inventory'
httpretty.enable()
httpretty.register_uri(httpretty.GET, inventory_url,
body=json.dumps(inventory_body))
for inv in api.inventory():
pass
assert httpretty.last_request().path == '/pdb/query/v4/inventory'
httpretty.disable()
httpretty.reset()
def test_nodes_single(self, api):
body = {
"cached_catalog_status": "not_used",
"catalog_environment": "production",
"catalog_timestamp": "2016-08-15T11:06:26.275Z",
"certname": "greenserver.vm",
"deactivated": None,
"expired": None,
"facts_environment": "production",
"facts_timestamp": "2016-08-15T11:06:26.140Z",
"latest_report_hash": "4a956674b016d95a7b77c99513ba26e4a744f8d1",
"latest_report_noop": False,
"latest_report_noop_pending": None,
"latest_report_status": "changed",
"report_environment": "production",
"report_timestamp": "2016-08-15T11:06:18.393Z"
}
url = 'http://localhost:8080/pdb/query/v4/nodes'
httpretty.enable()
httpretty.register_uri(httpretty.GET, url,
body=json.dumps(body))
nodes = list(api.nodes(query='["=","certname","greenserver.vm"'))
assert len(nodes) == 1
assert nodes[0].name == "greenserver.vm"
assert httpretty.last_request().path.startswith('/pdb/query/v4/nodes')
httpretty.disable()
httpretty.reset()
| {
"content_hash": "f5ffe2efaa564ea8200f2923c23d7c2a",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 78,
"avg_line_length": 32.488,
"alnum_prop": 0.5685791676926866,
"repo_name": "puppet-community/pypuppetdb",
"id": "7c38c2fccbad5a8596bb1c392730c1528503e293",
"size": "4061",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_api_query.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "200266"
}
],
"symlink_target": ""
} |
package org.apache.activemq.artemis.tests.unit.core.journal.impl;
import java.util.LinkedList;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.artemis.core.journal.impl.JournalFile;
import org.apache.activemq.artemis.core.journal.impl.JournalFilesRepository;
import org.apache.activemq.artemis.core.journal.impl.JournalImpl;
import org.apache.activemq.artemis.junit.Wait;
import org.apache.activemq.artemis.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.actors.OrderedExecutorFactory;
import org.junit.Assert;
import org.junit.Test;
public class JournalFileRepositoryOrderTest extends ActiveMQTestBase {
@Test
public void testOrder() throws Throwable {
ExecutorService executorService = Executors.newFixedThreadPool(3, new ActiveMQThreadFactory("test", false, JournalFileRepositoryOrderTest.class.getClassLoader()));
final AtomicBoolean running = new AtomicBoolean(true);
Thread t = null;
try {
FakeSequentialFileFactory fakeSequentialFileFactory = new FakeSequentialFileFactory();
JournalImpl journal = new JournalImpl(new OrderedExecutorFactory(executorService), 10 * 1024, 2, -1, -1, 0, fakeSequentialFileFactory, "file", "file", 1, 0);
final JournalFilesRepository repository = journal.getFilesRepository();
final BlockingDeque<JournalFile> dataFiles = new LinkedBlockingDeque<>();
// this is simulating how compating would return files into the journal
t = new Thread() {
@Override
public void run() {
while (running.get()) {
try {
Wait.waitFor(() -> !running.get() || dataFiles.size() > 10, 1000, 1);
while (running.get()) {
JournalFile file = dataFiles.poll();
if (file == null) break;
repository.addFreeFile(file, false);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
};
t.start();
JournalFile file = null;
LinkedList<Integer> values = new LinkedList<>();
for (int i = 0; i < 5000; i++) {
file = repository.openFile();
Assert.assertNotNull(file);
values.add(file.getRecordID());
dataFiles.push(file);
}
int previous = Integer.MIN_VALUE;
for (Integer v : values) {
Assert.assertTrue(v.intValue() > previous);
previous = v;
}
} finally {
running.set(false);
executorService.shutdownNow();
}
}
}
| {
"content_hash": "58807eefe394c1b879efa70324254430",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 169,
"avg_line_length": 39.166666666666664,
"alnum_prop": 0.6438625204582651,
"repo_name": "orpiske/activemq-artemis",
"id": "e223f0906f412463142ca6a8ab11c26f3ff800af",
"size": "3854",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/journal/impl/JournalFileRepositoryOrderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7352"
},
{
"name": "CSS",
"bytes": "65634"
},
{
"name": "Groovy",
"bytes": "94858"
},
{
"name": "HTML",
"bytes": "76288"
},
{
"name": "Java",
"bytes": "28360560"
},
{
"name": "JavaScript",
"bytes": "169496"
},
{
"name": "Shell",
"bytes": "36019"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<phpunit colors="true" backupGlobals="false" bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="wp-queue">
<directory prefix="Test" suffix=".php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
<exclude>
<directory suffix=".php">./vendor</directory>
</exclude>
</whitelist>
</filter>
</phpunit> | {
"content_hash": "60540876a94da18258ed3c58df818d46",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 77,
"avg_line_length": 33.8125,
"alnum_prop": 0.5767097966728281,
"repo_name": "A5hleyRich/wp-queue",
"id": "af6f6175e07fc2c58a6fabe531b97420ff2fa34a",
"size": "541",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "phpunit.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "27557"
}
],
"symlink_target": ""
} |
package org.apache.nutch.util;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.CounterGroup;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.Job;
import org.apache.nutch.metadata.Nutch;
public class ToolUtil {
public static final Map<String, Object> toArgMap(Object... args) {
if (args == null) {
return null;
}
if (args.length % 2 != 0) {
throw new RuntimeException("expected pairs of argName argValue");
}
HashMap<String, Object> res = new HashMap<String, Object>();
for (int i = 0; i < args.length; i += 2) {
if (args[i + 1] != null) {
res.put(String.valueOf(args[i]), args[i + 1]);
}
}
return res;
}
@SuppressWarnings("unchecked")
public static final void recordJobStatus(String label, Job job,
Map<String, Object> results) {
Map<String, Object> jobs = (Map<String, Object>) results
.get(Nutch.STAT_JOBS);
if (jobs == null) {
jobs = new LinkedHashMap<String, Object>();
results.put(Nutch.STAT_JOBS, jobs);
}
Map<String, Object> stats = new HashMap<String, Object>();
Map<String, Object> countStats = new HashMap<String, Object>();
try {
Counters counters = job.getCounters();
for (CounterGroup cg : counters) {
Map<String, Object> cnts = new HashMap<String, Object>();
countStats.put(cg.getDisplayName(), cnts);
for (Counter c : cg) {
cnts.put(c.getName(), c.getValue());
}
}
} catch (Exception e) {
countStats.put("error", e.toString());
}
stats.put(Nutch.STAT_COUNTERS, countStats);
stats.put("jobName", job.getJobName());
stats.put("jobID", job.getJobID());
if (label == null) {
label = job.getJobName();
if (job.getJobID() != null) {
label = label + "-" + job.getJobID();
}
}
jobs.put(label, stats);
}
}
| {
"content_hash": "ed3915599c356aab9cfdfba70e561895",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 71,
"avg_line_length": 30.439393939393938,
"alnum_prop": 0.6187157789945247,
"repo_name": "acailic/uns-search-elastic-nutch",
"id": "a01aef2cd234a8364e244872dada2fabc7766ace",
"size": "2967",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ApacheNutchCourse-master/src/java/org/apache/nutch/util/ToolUtil.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11506"
},
{
"name": "CSS",
"bytes": "19077"
},
{
"name": "HTML",
"bytes": "13928779"
},
{
"name": "Java",
"bytes": "2146383"
},
{
"name": "JavaScript",
"bytes": "62408"
},
{
"name": "Python",
"bytes": "589"
},
{
"name": "Shell",
"bytes": "26174"
},
{
"name": "XSLT",
"bytes": "1822"
}
],
"symlink_target": ""
} |
/////////////////////////////////////////////////////////////////////////////
// Name: wx/unix/private/fswatcher_kqueue.h
// Purpose: File system watcher impl classes
// Author: Bartosz Bekier
// Created: 2009-05-26
// Copyright: (c) 2009 Bartosz Bekier <[email protected]>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef WX_UNIX_PRIVATE_FSWATCHER_KQUEUE_H_
#define WX_UNIX_PRIVATE_FSWATCHER_KQUEUE_H_
#include <fcntl.h>
#include <unistd.h>
#include "wx/dir.h"
#include "wx/debug.h"
#include "wx/arrstr.h"
// ============================================================================
// wxFSWatcherEntry implementation & helper declarations
// ============================================================================
class wxFSWatcherImplKqueue;
class wxFSWatchEntryKq : public wxFSWatchInfo
{
public:
struct wxDirState
{
wxDirState(const wxFSWatchInfo& winfo)
{
if (!wxDir::Exists(winfo.GetPath()))
return;
wxDir dir(winfo.GetPath());
wxCHECK_RET( dir.IsOpened(),
wxString::Format("Unable to open dir '%s'", winfo.GetPath()));
wxString filename;
bool ret = dir.GetFirst(&filename);
while (ret)
{
files.push_back(filename);
ret = dir.GetNext(&filename);
}
}
wxSortedArrayString files;
};
wxFSWatchEntryKq(const wxFSWatchInfo& winfo) :
wxFSWatchInfo(winfo), m_lastState(winfo)
{
m_fd = wxOpen(m_path, O_RDONLY, 0);
if (m_fd == -1)
{
wxLogSysError(_("Unable to open path '%s'"), m_path);
}
}
virtual ~wxFSWatchEntryKq()
{
(void) Close();
}
bool Close()
{
if (!IsOk())
return false;
int ret = close(m_fd);
if (ret == -1)
{
wxLogSysError(_("Unable to close path '%s'"), m_path);
}
m_fd = -1;
return ret != -1;
}
bool IsOk() const
{
return m_fd != -1;
}
int GetFileDescriptor() const
{
return m_fd;
}
void RefreshState()
{
m_lastState = wxDirState(*this);
}
const wxDirState& GetLastState() const
{
return m_lastState;
}
private:
int m_fd;
wxDirState m_lastState;
wxDECLARE_NO_COPY_CLASS(wxFSWatchEntryKq);
};
#endif /* WX_UNIX_PRIVATE_FSWATCHER_KQUEUE_H_ */
| {
"content_hash": "6a437a73e871c1c3c7dd6c34552d4fac",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 80,
"avg_line_length": 23.65740740740741,
"alnum_prop": 0.47906066536203523,
"repo_name": "chartly/portfolio",
"id": "de3d489a382a6b73d4ce85866347edb0eee053fe",
"size": "2555",
"binary": false,
"copies": "129",
"ref": "refs/heads/master",
"path": "ditfw-gfx/deps/wxwidgets/include/wx/unix/private/fswatcher_kqueue.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1858"
},
{
"name": "AppleScript",
"bytes": "8932"
},
{
"name": "Assembly",
"bytes": "56211"
},
{
"name": "Awk",
"bytes": "42674"
},
{
"name": "C",
"bytes": "14658690"
},
{
"name": "C#",
"bytes": "16016"
},
{
"name": "C++",
"bytes": "152172949"
},
{
"name": "CSS",
"bytes": "63103"
},
{
"name": "D",
"bytes": "416653"
},
{
"name": "HTML",
"bytes": "10956176"
},
{
"name": "JavaScript",
"bytes": "83645"
},
{
"name": "Lua",
"bytes": "2489072"
},
{
"name": "Makefile",
"bytes": "110228"
},
{
"name": "Mercury",
"bytes": "7093"
},
{
"name": "Nemerle",
"bytes": "28217"
},
{
"name": "Objective-C",
"bytes": "5596199"
},
{
"name": "Objective-C++",
"bytes": "1315875"
},
{
"name": "Pascal",
"bytes": "28104"
},
{
"name": "Perl",
"bytes": "18473"
},
{
"name": "Prolog",
"bytes": "4605"
},
{
"name": "Python",
"bytes": "333684"
},
{
"name": "R",
"bytes": "672260"
},
{
"name": "Rebol",
"bytes": "1286"
},
{
"name": "Shell",
"bytes": "1153351"
},
{
"name": "TeX",
"bytes": "202321"
},
{
"name": "XSLT",
"bytes": "44320"
}
],
"symlink_target": ""
} |
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import fft
from gnuradio import gr
from gnuradio import uhd
from gnuradio.eng_option import eng_option
from gnuradio.fft import window
from gnuradio.filter import firdes
from optparse import OptionParser
import time
class SALSA_eceiver(gr.top_block):
def __init__(self):
gr.top_block.__init__(self, "Salsa Eceiver")
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 5000000.0
self.outfile = outfile = "/tmp/vale.dat"
self.int_time = int_time = 10
self.gain = gain = 60
self.fftsize = fftsize = 4096
self.c_freq = c_freq = 1420.4e6
##################################################
# Blocks
##################################################
self.uhd_usrp_source_0 = uhd.usrp_source(
device_addr="addr=192.168.10.2",
stream_args=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
self.uhd_usrp_source_0.set_samp_rate(samp_rate)
self.uhd_usrp_source_0.set_center_freq(c_freq, 0)
self.uhd_usrp_source_0.set_gain(gain, 0)
self.fft_vxx_0 = fft.fft_vcc(fftsize, True, (window.blackmanharris(fftsize)), True, 1)
self.blocks_vector_to_stream_0 = blocks.vector_to_stream(gr.sizeof_gr_complex*1, fftsize)
self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, fftsize)
self.blocks_head_0 = blocks.head(gr.sizeof_float*1, int(int_time*samp_rate))
self.blocks_file_sink_0 = blocks.file_sink(gr.sizeof_float*1, outfile, False)
self.blocks_file_sink_0.set_unbuffered(False)
self.blocks_complex_to_mag_squared_0 = blocks.complex_to_mag_squared(1)
##################################################
# Connections
##################################################
self.connect((self.fft_vxx_0, 0), (self.blocks_vector_to_stream_0, 0))
self.connect((self.uhd_usrp_source_0, 0), (self.blocks_stream_to_vector_0, 0))
self.connect((self.blocks_vector_to_stream_0, 0), (self.blocks_complex_to_mag_squared_0, 0))
self.connect((self.blocks_complex_to_mag_squared_0, 0), (self.blocks_head_0, 0))
self.connect((self.blocks_head_0, 0), (self.blocks_file_sink_0, 0))
self.connect((self.blocks_stream_to_vector_0, 0), (self.fft_vxx_0, 0))
# QT sink close method reimplementation
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)
def get_outfile(self):
return self.outfile
def set_outfile(self, outfile):
self.outfile = outfile
self.blocks_file_sink_0.open(self.outfile)
def get_int_time(self):
return self.int_time
def set_int_time(self, int_time):
self.int_time = int_time
def get_gain(self):
return self.gain
def set_gain(self, gain):
self.gain = gain
self.uhd_usrp_source_0.set_gain(self.gain, 0)
def get_fftsize(self):
return self.fftsize
def set_fftsize(self, fftsize):
self.fftsize = fftsize
def get_c_freq(self):
return self.c_freq
def set_c_freq(self, c_freq):
self.c_freq = c_freq
self.uhd_usrp_source_0.set_center_freq(self.c_freq, 0)
if __name__ == '__main__':
parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
(options, args) = parser.parse_args()
tb = SALSA_eceiver()
tb.start()
tb.wait()
| {
"content_hash": "300a5fcf2c588a64c2b94bd2b537911d",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 100,
"avg_line_length": 35.09345794392523,
"alnum_prop": 0.5736351531291611,
"repo_name": "varenius/salsa",
"id": "4ebe7333ca04f08fbc730656e2f2def3514b7a7a",
"size": "3970",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "USRP/usrp_gnuradio_dev/SALSA_eceiver.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "587"
},
{
"name": "MATLAB",
"bytes": "137727"
},
{
"name": "PHP",
"bytes": "6663"
},
{
"name": "Python",
"bytes": "311661"
},
{
"name": "Shell",
"bytes": "5475"
},
{
"name": "TeX",
"bytes": "324522"
},
{
"name": "Vim Script",
"bytes": "940"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.